|
| 1 | +import * as fs from 'node:fs'; |
| 2 | +import * as fsp from 'node:fs/promises'; |
| 3 | +import * as path from 'node:path'; |
| 4 | +import JSZip from 'jszip'; |
| 5 | +import { appConfig } from '../config.js'; |
| 6 | +import { DEFAULT_GATEWAY, DEFAULT_HTTPS } from '../auth/defaults.js'; |
| 7 | + |
| 8 | +interface GraphMetadata { |
| 9 | + dataSourceKey: string; |
| 10 | + createInputType: string; |
| 11 | + updateInputType: string; |
| 12 | + fields?: Record<string, { nullable: boolean }>; |
| 13 | + createInputFields?: Record<string, { required: boolean }>; |
| 14 | + updateInputFields?: Record<string, { required: boolean }>; |
| 15 | +} |
| 16 | + |
| 17 | +interface ModelSchema { |
| 18 | + name: string; |
| 19 | + collection: string; |
| 20 | + graph?: GraphMetadata; |
| 21 | +} |
| 22 | + |
| 23 | +function referenceIdToGraphTypePrefix(referenceId: string): string { |
| 24 | + const parts = referenceId.split('_'); |
| 25 | + const head = parts[0] ?? ''; |
| 26 | + const capitalized = head.length === 0 ? '' : head.charAt(0).toUpperCase() + head.slice(1); |
| 27 | + const tail = parts.slice(1).join('_'); |
| 28 | + return tail ? `${capitalized}_${tail}` : capitalized; |
| 29 | +} |
| 30 | + |
| 31 | +export interface IntrospectionResult { |
| 32 | + /** Successfully enriched models, keyed by model name */ |
| 33 | + graph: Record<string, GraphMetadata>; |
| 34 | + /** Models where introspection returned null for at least one field */ |
| 35 | + missing: string[]; |
| 36 | +} |
| 37 | + |
| 38 | +export type IntrospectionSkipReason = |
| 39 | + | { kind: 'no-token' } |
| 40 | + | { kind: 'no-manifest'; path: string } |
| 41 | + | { kind: 'network-error'; message: string } |
| 42 | + | { kind: 'api-error'; message: string }; |
| 43 | + |
| 44 | +export type IntrospectionOutcome = |
| 45 | + | { ok: true; result: IntrospectionResult } |
| 46 | + | { ok: false; reason: IntrospectionSkipReason }; |
| 47 | + |
| 48 | +const ACCURACY_IMPACT = 'Generated code may not accurately reflect the live GraphQL schema.'; |
| 49 | + |
| 50 | +export function applyIntrospectionOutcome<T extends ModelSchema>( |
| 51 | + schemas: T[], |
| 52 | + outcome: IntrospectionOutcome |
| 53 | +): { schemas: T[]; warnings: string[] } { |
| 54 | + if (!outcome.ok) { |
| 55 | + const { reason } = outcome; |
| 56 | + if (reason.kind === 'no-token' || reason.kind === 'no-manifest') { |
| 57 | + return { schemas, warnings: [] }; |
| 58 | + } |
| 59 | + return { |
| 60 | + schemas, |
| 61 | + warnings: [`GraphQL introspection failed — ${reason.message}.\n${ACCURACY_IMPACT}`], |
| 62 | + }; |
| 63 | + } |
| 64 | + |
| 65 | + const { graph, missing } = outcome.result; |
| 66 | + const warnings: string[] = []; |
| 67 | + |
| 68 | + if (missing.length > 0) { |
| 69 | + warnings.push( |
| 70 | + `GraphQL introspection returned no data for: ${missing.join(', ')}.\n${ACCURACY_IMPACT}` |
| 71 | + ); |
| 72 | + } |
| 73 | + |
| 74 | + const enriched = schemas.map((s) => { |
| 75 | + const graphMeta = graph[s.name]; |
| 76 | + return graphMeta ? ({ ...s, graph: graphMeta } as T) : s; |
| 77 | + }); |
| 78 | + |
| 79 | + return { schemas: enriched, warnings }; |
| 80 | +} |
| 81 | + |
| 82 | +function capitalize(s: string): string { |
| 83 | + return s.length === 0 ? '' : s.charAt(0).toUpperCase() + s.slice(1); |
| 84 | +} |
| 85 | + |
| 86 | +async function readManifestContent(sourcePath: string, isZip: boolean): Promise<string | null> { |
| 87 | + if (isZip) { |
| 88 | + const buffer = await fsp.readFile(sourcePath); |
| 89 | + const zip = await JSZip.loadAsync(buffer); |
| 90 | + const entry = zip.files['appManifest.json']; |
| 91 | + if (!entry) return null; |
| 92 | + return entry.async('string'); |
| 93 | + } |
| 94 | + const manifestPath = path.join(sourcePath, 'appManifest.json'); |
| 95 | + if (!fs.existsSync(manifestPath)) return null; |
| 96 | + return fs.readFileSync(manifestPath, 'utf-8'); |
| 97 | +} |
| 98 | + |
| 99 | +function buildQuery(graphPrefix: string, schemas: ModelSchema[]): string { |
| 100 | + const selections = schemas |
| 101 | + .map(({ name, collection }) => { |
| 102 | + const dsType = `${graphPrefix}_${name}_DataSources`; |
| 103 | + const createType = `${graphPrefix}_${capitalize(collection)}Summary_Create_Input`; |
| 104 | + const updateType = `${graphPrefix}_${capitalize(collection)}Summary_Update_Input`; |
| 105 | + const summaryType = `${graphPrefix}_${name}Summary`; |
| 106 | + return [ |
| 107 | + ` ds_${name}: __type(name: ${JSON.stringify(dsType)}) { inputFields { name } }`, |
| 108 | + ` create_${name}: __type(name: ${JSON.stringify(createType)}) { name kind inputFields { name type { kind name ofType { kind name } } } }`, |
| 109 | + ` update_${name}: __type(name: ${JSON.stringify(updateType)}) { name kind inputFields { name type { kind name ofType { kind name } } } }`, |
| 110 | + ` summary_${name}: __type(name: ${JSON.stringify(summaryType)}) { fields { name type { kind name ofType { kind name } } } }`, |
| 111 | + ].join('\n'); |
| 112 | + }) |
| 113 | + .join('\n'); |
| 114 | + return `query IntrospectBindTypes {\n${selections}\n}`; |
| 115 | +} |
| 116 | + |
| 117 | +export async function introspectGraphTypes<T extends ModelSchema>( |
| 118 | + schemas: T[], |
| 119 | + extendSourcePath: string, |
| 120 | + isZip: boolean |
| 121 | +): Promise<IntrospectionOutcome> { |
| 122 | + const { auth = {} } = appConfig().read(); |
| 123 | + if (!auth.token) { |
| 124 | + return { ok: false, reason: { kind: 'no-token' } }; |
| 125 | + } |
| 126 | + const { gateway = DEFAULT_GATEWAY, https: useHttps = DEFAULT_HTTPS, token } = auth; |
| 127 | + |
| 128 | + let manifestContent: string | null; |
| 129 | + try { |
| 130 | + manifestContent = await readManifestContent(extendSourcePath, isZip); |
| 131 | + } catch { |
| 132 | + const manifestPath = isZip |
| 133 | + ? `${extendSourcePath}:appManifest.json` |
| 134 | + : path.join(extendSourcePath, 'appManifest.json'); |
| 135 | + return { ok: false, reason: { kind: 'no-manifest', path: manifestPath } }; |
| 136 | + } |
| 137 | + |
| 138 | + if (!manifestContent) { |
| 139 | + const manifestPath = isZip |
| 140 | + ? `${extendSourcePath}:appManifest.json` |
| 141 | + : path.join(extendSourcePath, 'appManifest.json'); |
| 142 | + return { ok: false, reason: { kind: 'no-manifest', path: manifestPath } }; |
| 143 | + } |
| 144 | + |
| 145 | + let manifest: { referenceId?: string }; |
| 146 | + try { |
| 147 | + manifest = JSON.parse(manifestContent) as { referenceId?: string }; |
| 148 | + } catch { |
| 149 | + return { |
| 150 | + ok: false, |
| 151 | + reason: { |
| 152 | + kind: 'no-manifest', |
| 153 | + path: isZip ? extendSourcePath : path.join(extendSourcePath, 'appManifest.json'), |
| 154 | + }, |
| 155 | + }; |
| 156 | + } |
| 157 | + |
| 158 | + if (typeof manifest.referenceId !== 'string' || !manifest.referenceId) { |
| 159 | + return { |
| 160 | + ok: false, |
| 161 | + reason: { |
| 162 | + kind: 'no-manifest', |
| 163 | + path: isZip ? extendSourcePath : path.join(extendSourcePath, 'appManifest.json'), |
| 164 | + }, |
| 165 | + }; |
| 166 | + } |
| 167 | + |
| 168 | + const { referenceId } = manifest; |
| 169 | + const graphPrefix = referenceIdToGraphTypePrefix(referenceId); |
| 170 | + const endpoint = `${useHttps ? 'https' : 'http'}://${gateway}/api/v1/data/graphql`; |
| 171 | + const query = buildQuery(graphPrefix, schemas); |
| 172 | + |
| 173 | + let response: Response; |
| 174 | + try { |
| 175 | + response = await fetch(endpoint, { |
| 176 | + method: 'POST', |
| 177 | + headers: { |
| 178 | + accept: 'application/json', |
| 179 | + 'content-type': 'application/json', |
| 180 | + Authorization: `Bearer ${token}`, |
| 181 | + }, |
| 182 | + body: JSON.stringify({ query }), |
| 183 | + }); |
| 184 | + } catch (e) { |
| 185 | + return { |
| 186 | + ok: false, |
| 187 | + reason: { |
| 188 | + kind: 'network-error', |
| 189 | + message: e instanceof Error ? e.message : String(e), |
| 190 | + }, |
| 191 | + }; |
| 192 | + } |
| 193 | + |
| 194 | + if (!response.ok) { |
| 195 | + return { |
| 196 | + ok: false, |
| 197 | + reason: { kind: 'api-error', message: `HTTP ${response.status}: ${response.statusText}` }, |
| 198 | + }; |
| 199 | + } |
| 200 | + |
| 201 | + const body = (await response.json()) as { |
| 202 | + data?: Record<string, unknown>; |
| 203 | + errors?: { message: string }[]; |
| 204 | + }; |
| 205 | + |
| 206 | + if (body.errors?.length) { |
| 207 | + return { |
| 208 | + ok: false, |
| 209 | + reason: { kind: 'api-error', message: body.errors.map((e) => e.message).join('; ') }, |
| 210 | + }; |
| 211 | + } |
| 212 | + |
| 213 | + const data = body.data ?? {}; |
| 214 | + const graph: Record<string, GraphMetadata> = {}; |
| 215 | + const missing: string[] = []; |
| 216 | + |
| 217 | + type GqlTypeRef = { |
| 218 | + kind: string; |
| 219 | + name: string | null; |
| 220 | + ofType: { kind: string; name: string | null } | null; |
| 221 | + }; |
| 222 | + type GqlInputField = { name: string; type: GqlTypeRef }; |
| 223 | + type GqlSummaryField = { name: string; type: GqlTypeRef }; |
| 224 | + |
| 225 | + for (const schema of schemas) { |
| 226 | + const { name, collection } = schema; |
| 227 | + |
| 228 | + const dsResult = data[`ds_${name}`] as { inputFields: { name: string }[] } | null; |
| 229 | + const createResult = data[`create_${name}`] as { |
| 230 | + name: string; |
| 231 | + kind: string; |
| 232 | + inputFields?: GqlInputField[]; |
| 233 | + } | null; |
| 234 | + const updateResult = data[`update_${name}`] as { |
| 235 | + name: string; |
| 236 | + kind: string; |
| 237 | + inputFields?: GqlInputField[]; |
| 238 | + } | null; |
| 239 | + const summaryResult = data[`summary_${name}`] as { fields?: GqlSummaryField[] } | null; |
| 240 | + |
| 241 | + const inputFields = dsResult?.inputFields ?? []; |
| 242 | + const preferred = inputFields.find((f) => f.name === `${referenceId}_${collection}`); |
| 243 | + const sorted = [...inputFields].sort((a, b) => a.name.localeCompare(b.name)); |
| 244 | + const dataSourceKey = preferred?.name ?? sorted[0]?.name; |
| 245 | + |
| 246 | + const createInputType = createResult?.kind === 'INPUT_OBJECT' ? createResult.name : null; |
| 247 | + const updateInputType = updateResult?.kind === 'INPUT_OBJECT' ? updateResult.name : null; |
| 248 | + |
| 249 | + if (!dataSourceKey || !createInputType || !updateInputType) { |
| 250 | + missing.push(name); |
| 251 | + } else { |
| 252 | + const meta: GraphMetadata = { dataSourceKey, createInputType, updateInputType }; |
| 253 | + |
| 254 | + if (summaryResult?.fields) { |
| 255 | + meta.fields = Object.fromEntries( |
| 256 | + summaryResult.fields.map((f) => [f.name, { nullable: f.type.kind !== 'NON_NULL' }]) |
| 257 | + ); |
| 258 | + } |
| 259 | + |
| 260 | + if (createResult?.inputFields) { |
| 261 | + meta.createInputFields = Object.fromEntries( |
| 262 | + createResult.inputFields.map((f) => [f.name, { required: f.type.kind === 'NON_NULL' }]) |
| 263 | + ); |
| 264 | + } |
| 265 | + |
| 266 | + if (updateResult?.inputFields) { |
| 267 | + meta.updateInputFields = Object.fromEntries( |
| 268 | + updateResult.inputFields.map((f) => [f.name, { required: f.type.kind === 'NON_NULL' }]) |
| 269 | + ); |
| 270 | + } |
| 271 | + |
| 272 | + graph[name] = meta; |
| 273 | + } |
| 274 | + } |
| 275 | + |
| 276 | + return { ok: true, result: { graph, missing } }; |
| 277 | +} |
0 commit comments