@memberjunction/codegen-lib 6.2.2 → 6.3.0-edge.1
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/README.md +38 -1
- package/dist/Angular/angular-codegen.js +1 -1
- package/dist/Config/config.d.ts +46 -0
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +17 -0
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts +7 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.js +23 -1
- package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
- package/dist/Database/config-retraction.d.ts +126 -0
- package/dist/Database/config-retraction.d.ts.map +1 -0
- package/dist/Database/config-retraction.js +151 -0
- package/dist/Database/config-retraction.js.map +1 -0
- package/dist/Database/manage-metadata.d.ts +196 -21
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +911 -259
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/organic-key-sync.d.ts +70 -0
- package/dist/Database/organic-key-sync.d.ts.map +1 -0
- package/dist/Database/organic-key-sync.js +83 -0
- package/dist/Database/organic-key-sync.js.map +1 -0
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +7 -0
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +83 -19
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +14 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts +2 -0
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts.map +1 -0
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js +36 -0
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js.map +1 -0
- package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js +5 -0
- package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
- package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
- package/dist/Database/providers/postgresql/metadataSupportObjects.js +64 -18
- package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
- package/dist/Database/providers/postgresql/viewFallback.d.ts +25 -0
- package/dist/Database/providers/postgresql/viewFallback.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/viewFallback.js +101 -48
- package/dist/Database/providers/postgresql/viewFallback.js.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +12 -2
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +106 -36
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js +65 -7
- package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js +30 -3
- package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js +41 -0
- package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
- package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
- package/dist/Database/sqlPassFailures.d.ts +26 -0
- package/dist/Database/sqlPassFailures.d.ts.map +1 -0
- package/dist/Database/sqlPassFailures.js +15 -0
- package/dist/Database/sqlPassFailures.js.map +1 -0
- package/dist/Database/sql_codegen.d.ts +85 -2
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +573 -128
- package/dist/Database/sql_codegen.js.map +1 -1
- package/dist/Database/unique-key-sets.d.ts +71 -0
- package/dist/Database/unique-key-sets.d.ts.map +1 -0
- package/dist/Database/unique-key-sets.js +140 -0
- package/dist/Database/unique-key-sets.js.map +1 -0
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +49 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.js +392 -60
- package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
- package/dist/Misc/advanced_generation.d.ts +15 -3
- package/dist/Misc/advanced_generation.d.ts.map +1 -1
- package/dist/Misc/advanced_generation.js +50 -3
- package/dist/Misc/advanced_generation.js.map +1 -1
- package/dist/Misc/createNewUser.js +4 -4
- package/dist/Misc/createNewUser.js.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.d.ts +11 -4
- package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.js +46 -14
- package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
- package/dist/Misc/file-write.d.ts.map +1 -1
- package/dist/Misc/file-write.js +16 -10
- package/dist/Misc/file-write.js.map +1 -1
- package/dist/Misc/smart-field-decision.d.ts +126 -0
- package/dist/Misc/smart-field-decision.d.ts.map +1 -0
- package/dist/Misc/smart-field-decision.js +222 -0
- package/dist/Misc/smart-field-decision.js.map +1 -0
- package/dist/Misc/sql_logging.d.ts +3 -1
- package/dist/Misc/sql_logging.d.ts.map +1 -1
- package/dist/Misc/sql_logging.js +4 -2
- package/dist/Misc/sql_logging.js.map +1 -1
- package/dist/Misc/system_integrity.d.ts +37 -0
- package/dist/Misc/system_integrity.d.ts.map +1 -1
- package/dist/Misc/system_integrity.js +74 -8
- package/dist/Misc/system_integrity.js.map +1 -1
- package/dist/Misc/typed_query_codegen.d.ts +144 -0
- package/dist/Misc/typed_query_codegen.d.ts.map +1 -0
- package/dist/Misc/typed_query_codegen.js +747 -0
- package/dist/Misc/typed_query_codegen.js.map +1 -0
- package/dist/Misc/validator-text.d.ts +14 -5
- package/dist/Misc/validator-text.d.ts.map +1 -1
- package/dist/Misc/validator-text.js +42 -13
- package/dist/Misc/validator-text.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.d.ts +10 -0
- package/dist/plugins/index.d.ts.map +1 -1
- package/dist/plugins/index.js +22 -2
- package/dist/plugins/index.js.map +1 -1
- package/dist/runCodeGen.d.ts +6 -0
- package/dist/runCodeGen.d.ts.map +1 -1
- package/dist/runCodeGen.js +75 -16
- package/dist/runCodeGen.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +30 -29
|
@@ -0,0 +1,747 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { ComputeTypedQuerySignature, } from '@memberjunction/core-entities';
|
|
4
|
+
import { UUIDsEqual, ordinalCompare } from '@memberjunction/global';
|
|
5
|
+
import { GetQueryDialect } from '@memberjunction/sql-dialect';
|
|
6
|
+
import { QueryTemplate } from '@memberjunction/sql-parser';
|
|
7
|
+
import { WriteFileIfChanged } from './file-write.js';
|
|
8
|
+
import { SanitizeSchemaFileName, SchemaKey } from './schema-emit.js';
|
|
9
|
+
import { LogWarning, logError, logStatus } from './status_logging.js';
|
|
10
|
+
/** The package that exports `DefineTypedQuery`: what generated typed-query files import by default. */
|
|
11
|
+
export const TypedQueryDefinerModule = '@memberjunction/core-entities';
|
|
12
|
+
/**
|
|
13
|
+
* The query shape {@link TypedQueryGeneratorBase} reads, built from `QueryEngine` queries: the
|
|
14
|
+
* entity names its child collections `QueryParameters`, `QueryFields` and `QueryEntities`.
|
|
15
|
+
*/
|
|
16
|
+
export function TypedQueryCodeGenQueriesFromEngine(queries) {
|
|
17
|
+
return queries.map((q) => ({
|
|
18
|
+
ID: q.ID,
|
|
19
|
+
Name: q.Name,
|
|
20
|
+
Description: q.Description,
|
|
21
|
+
SQL: q.SQL,
|
|
22
|
+
Status: q.Status,
|
|
23
|
+
Reusable: q.Reusable,
|
|
24
|
+
CategoryPath: q.CategoryPath,
|
|
25
|
+
Category: q.Category,
|
|
26
|
+
Parameters: q.QueryParameters,
|
|
27
|
+
Fields: q.QueryFields,
|
|
28
|
+
Entities: q.QueryEntities,
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
const VALID_DECLARED_PARAM_TYPES = new Set(['string', 'number', 'date', 'boolean', 'array']);
|
|
32
|
+
const NUMBER_SQL_TYPES = new Set([
|
|
33
|
+
'int',
|
|
34
|
+
'integer',
|
|
35
|
+
'bigint',
|
|
36
|
+
'smallint',
|
|
37
|
+
'tinyint',
|
|
38
|
+
'decimal',
|
|
39
|
+
'numeric',
|
|
40
|
+
'float',
|
|
41
|
+
'real',
|
|
42
|
+
'double precision',
|
|
43
|
+
'money',
|
|
44
|
+
'smallmoney',
|
|
45
|
+
'serial',
|
|
46
|
+
'bigserial',
|
|
47
|
+
]);
|
|
48
|
+
const BOOLEAN_SQL_TYPES = new Set(['bit', 'boolean', 'bool']);
|
|
49
|
+
const DATE_SQL_TYPES = new Set([
|
|
50
|
+
'date',
|
|
51
|
+
'datetime',
|
|
52
|
+
'datetime2',
|
|
53
|
+
'datetimeoffset',
|
|
54
|
+
'smalldatetime',
|
|
55
|
+
'time',
|
|
56
|
+
'timestamp',
|
|
57
|
+
'timestamptz',
|
|
58
|
+
'timestamp without time zone',
|
|
59
|
+
'timestamp with time zone',
|
|
60
|
+
]);
|
|
61
|
+
const TS_RESERVED_WORDS = new Set([
|
|
62
|
+
'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete',
|
|
63
|
+
'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if',
|
|
64
|
+
'import', 'in', 'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw',
|
|
65
|
+
'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', 'let', 'static', 'implements',
|
|
66
|
+
'interface', 'package', 'private', 'protected', 'public', 'await', 'abstract', 'boolean',
|
|
67
|
+
'byte', 'char', 'double', 'final', 'float', 'goto', 'int', 'long', 'native', 'short',
|
|
68
|
+
'synchronized', 'throws', 'transient', 'volatile', 'Queries',
|
|
69
|
+
]);
|
|
70
|
+
/**
|
|
71
|
+
* Maps a SQL base type name (e.g. `'nvarchar'`, `'int'`, `'datetimeoffset'`, `'bit'`) to its
|
|
72
|
+
* corresponding TypeScript row property type (`'string' | 'number' | 'boolean' | 'Date'`).
|
|
73
|
+
*/
|
|
74
|
+
export function MapSQLBaseTypeToTSType(sqlBaseType) {
|
|
75
|
+
const raw = (sqlBaseType ?? '').trim();
|
|
76
|
+
const parenIndex = raw.indexOf('(');
|
|
77
|
+
const cleaned = (parenIndex >= 0 ? raw.slice(0, parenIndex) : raw).trim().toLowerCase();
|
|
78
|
+
if (NUMBER_SQL_TYPES.has(cleaned)) {
|
|
79
|
+
return 'number';
|
|
80
|
+
}
|
|
81
|
+
if (BOOLEAN_SQL_TYPES.has(cleaned)) {
|
|
82
|
+
return 'boolean';
|
|
83
|
+
}
|
|
84
|
+
if (DATE_SQL_TYPES.has(cleaned)) {
|
|
85
|
+
return 'Date';
|
|
86
|
+
}
|
|
87
|
+
return 'string';
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Converts a query or category name into a valid PascalCase TypeScript identifier.
|
|
91
|
+
*/
|
|
92
|
+
export function ToQueryIdentifier(rawName) {
|
|
93
|
+
const trimmed = (rawName ?? '').trim();
|
|
94
|
+
if (!trimmed) {
|
|
95
|
+
return 'UnnamedQuery';
|
|
96
|
+
}
|
|
97
|
+
const words = trimmed
|
|
98
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
99
|
+
.split(/[^A-Za-z0-9]+/)
|
|
100
|
+
.filter((w) => w.length > 0);
|
|
101
|
+
if (words.length === 0) {
|
|
102
|
+
return 'UnnamedQuery';
|
|
103
|
+
}
|
|
104
|
+
let identifier = words
|
|
105
|
+
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
|
106
|
+
.join('');
|
|
107
|
+
if (/^[0-9]/.test(identifier)) {
|
|
108
|
+
identifier = `Q_${identifier}`;
|
|
109
|
+
}
|
|
110
|
+
if (TS_RESERVED_WORDS.has(identifier)) {
|
|
111
|
+
identifier = `${identifier}Query`;
|
|
112
|
+
}
|
|
113
|
+
return identifier;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Extracts ordered category path segments from a query's `CategoryPath` or fallback `Category`.
|
|
117
|
+
*/
|
|
118
|
+
export function ExtractQueryCategorySegments(query) {
|
|
119
|
+
if (query.CategoryPath && query.CategoryPath.trim().length > 0) {
|
|
120
|
+
return query.CategoryPath
|
|
121
|
+
.split('/')
|
|
122
|
+
.map((s) => s.trim())
|
|
123
|
+
.filter((s) => s.length > 0);
|
|
124
|
+
}
|
|
125
|
+
if (query.Category && query.Category.trim().length > 0) {
|
|
126
|
+
return query.Category
|
|
127
|
+
.split('/')
|
|
128
|
+
.map((s) => s.trim())
|
|
129
|
+
.filter((s) => s.length > 0);
|
|
130
|
+
}
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Builds the canonical `/` separated query path (`Category1/Category2/Query Name`).
|
|
135
|
+
*/
|
|
136
|
+
export function BuildTypedQueryFullPath(query) {
|
|
137
|
+
const segments = ExtractQueryCategorySegments(query);
|
|
138
|
+
const name = query.Name.trim();
|
|
139
|
+
return segments.length > 0 ? `${segments.join('/')}/${name}` : name;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Filters a query catalog down to queries eligible for typed wrapper generation:
|
|
143
|
+
* `Reusable === true` AND `Status === 'Approved'`.
|
|
144
|
+
*/
|
|
145
|
+
export function FilterEligibleTypedQueries(queries) {
|
|
146
|
+
return queries.filter((q) => Boolean(q.Reusable) && q.Status === 'Approved');
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Resolves the logical database schema that owns a query.
|
|
150
|
+
*
|
|
151
|
+
* Precedence:
|
|
152
|
+
* 1. Explicit `query.SchemaName` when present.
|
|
153
|
+
* 2. Referenced entities in `query.Entities` or `query.Fields` (`SourceEntityID` / `SourceEntity`):
|
|
154
|
+
* if any referenced entity belongs to a non-core schema, the most frequent non-core schema
|
|
155
|
+
* (ties broken alphabetically) wins.
|
|
156
|
+
* 3. Top-level category segment matching a known non-core schema.
|
|
157
|
+
* 4. Fallback to `mjCoreSchema` (`'__mj'`).
|
|
158
|
+
*/
|
|
159
|
+
export function ResolveTypedQuerySchema(query, entities, allSchemas, mjCoreSchema = '__mj') {
|
|
160
|
+
if (query.SchemaName && query.SchemaName.trim().length > 0) {
|
|
161
|
+
return query.SchemaName.trim();
|
|
162
|
+
}
|
|
163
|
+
const coreLower = mjCoreSchema.trim().toLowerCase();
|
|
164
|
+
const nonCoreCounts = new Map();
|
|
165
|
+
let sawCoreEntity = false;
|
|
166
|
+
const recordEntityMatch = (entity) => {
|
|
167
|
+
if (!entity || !entity.SchemaName)
|
|
168
|
+
return;
|
|
169
|
+
const schema = entity.SchemaName.trim();
|
|
170
|
+
if (!schema)
|
|
171
|
+
return;
|
|
172
|
+
if (schema.toLowerCase() === coreLower) {
|
|
173
|
+
sawCoreEntity = true;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
nonCoreCounts.set(schema, (nonCoreCounts.get(schema) ?? 0) + 1);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
for (const ref of query.Entities ?? []) {
|
|
180
|
+
const match = findEntity(entities, ref.EntityID, ref.Entity);
|
|
181
|
+
recordEntityMatch(match);
|
|
182
|
+
}
|
|
183
|
+
for (const field of query.Fields ?? []) {
|
|
184
|
+
const match = findEntity(entities, field.SourceEntityID, field.SourceEntity);
|
|
185
|
+
recordEntityMatch(match);
|
|
186
|
+
}
|
|
187
|
+
if (nonCoreCounts.size > 0) {
|
|
188
|
+
const sorted = [...nonCoreCounts.entries()].sort((a, b) => {
|
|
189
|
+
if (b[1] !== a[1])
|
|
190
|
+
return b[1] - a[1];
|
|
191
|
+
return ordinalCompare(a[0], b[0]);
|
|
192
|
+
});
|
|
193
|
+
return sorted[0][0];
|
|
194
|
+
}
|
|
195
|
+
if (sawCoreEntity) {
|
|
196
|
+
return mjCoreSchema;
|
|
197
|
+
}
|
|
198
|
+
const segments = ExtractQueryCategorySegments(query);
|
|
199
|
+
if (segments.length > 0) {
|
|
200
|
+
const firstSeg = segments[0].toLowerCase();
|
|
201
|
+
const schemaMatch = allSchemas.find((s) => {
|
|
202
|
+
const sLower = s.trim().toLowerCase();
|
|
203
|
+
return (sLower !== coreLower &&
|
|
204
|
+
(sLower === firstSeg ||
|
|
205
|
+
sLower === `__mj_bizapps${firstSeg}` ||
|
|
206
|
+
sLower.endsWith(`_${firstSeg}`)));
|
|
207
|
+
});
|
|
208
|
+
if (schemaMatch) {
|
|
209
|
+
return schemaMatch.trim();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return mjCoreSchema;
|
|
213
|
+
}
|
|
214
|
+
function findEntity(entities, entityId, entityName) {
|
|
215
|
+
if (entityId && entityId.trim().length > 0) {
|
|
216
|
+
const byId = entities.find((e) => UUIDsEqual(e.ID, entityId));
|
|
217
|
+
if (byId)
|
|
218
|
+
return byId;
|
|
219
|
+
}
|
|
220
|
+
if (entityName && entityName.trim().length > 0) {
|
|
221
|
+
const lower = entityName.trim().toLowerCase();
|
|
222
|
+
return entities.find((e) => e.Name.trim().toLowerCase() === lower);
|
|
223
|
+
}
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Generates the TypeScript source code for a single schema's approved, reusable queries.
|
|
228
|
+
* Pure function suitable for deterministic golden-file unit tests as well as CodeGen file emission.
|
|
229
|
+
*/
|
|
230
|
+
export function GenerateTypedQueriesFileContent(queries, entities = [], options = {}) {
|
|
231
|
+
const eligible = FilterEligibleTypedQueries(queries);
|
|
232
|
+
const resolved = resolveQuerySpecs(eligible, entities, options);
|
|
233
|
+
const emitZod = options.emitZodSchemas !== false;
|
|
234
|
+
const lines = [
|
|
235
|
+
'// AUTO-GENERATED FILE - DO NOT EDIT',
|
|
236
|
+
'// Generated by MemberJunction CodeGen (typed_query_codegen)',
|
|
237
|
+
'',
|
|
238
|
+
];
|
|
239
|
+
if (resolved.length === 0) {
|
|
240
|
+
lines.push('export const Queries = {} as const;');
|
|
241
|
+
lines.push('');
|
|
242
|
+
return lines.join('\n');
|
|
243
|
+
}
|
|
244
|
+
lines.push(`import { DefineTypedQuery } from '${options.definerModule ?? TypedQueryDefinerModule}';`);
|
|
245
|
+
if (emitZod) {
|
|
246
|
+
lines.push("import { z } from 'zod';");
|
|
247
|
+
}
|
|
248
|
+
lines.push('');
|
|
249
|
+
for (const spec of resolved) {
|
|
250
|
+
lines.push(renderQueryDeclarationBlock(spec, emitZod));
|
|
251
|
+
lines.push('');
|
|
252
|
+
}
|
|
253
|
+
lines.push(renderQueriesNamespaceTree(resolved));
|
|
254
|
+
lines.push('');
|
|
255
|
+
return lines.join('\n');
|
|
256
|
+
}
|
|
257
|
+
function resolveQuerySpecs(queries, entities, options) {
|
|
258
|
+
const platform = options.platform ?? 'sqlserver';
|
|
259
|
+
const dialect = GetQueryDialect(platform);
|
|
260
|
+
const warn = options.onWarning ?? ((msg) => LogWarning(msg));
|
|
261
|
+
const preliminary = queries
|
|
262
|
+
.map((query) => {
|
|
263
|
+
const categorySegments = ExtractQueryCategorySegments(query);
|
|
264
|
+
const fullPath = BuildTypedQueryFullPath(query);
|
|
265
|
+
const leafName = ToQueryIdentifier(query.Name);
|
|
266
|
+
const sqlText = (query.SQL ?? '').trim();
|
|
267
|
+
const template = sqlText.length > 0 ? QueryTemplate.Parse(sqlText, dialect) : null;
|
|
268
|
+
const docs = template ? template.DocComments().Value : null;
|
|
269
|
+
const templateParams = template ? template.Parameters().Value : [];
|
|
270
|
+
const summary = docs?.Summary ?? (query.Description?.trim() || null);
|
|
271
|
+
const parameters = resolveParametersForQuery(query, fullPath, templateParams, docs?.Parameters ?? [], warn);
|
|
272
|
+
const fields = resolveFieldsForQuery(query, entities, docs?.Fields ?? []);
|
|
273
|
+
const sigParams = query.Parameters && query.Parameters.length > 0
|
|
274
|
+
? query.Parameters.map((p) => ({
|
|
275
|
+
Name: p.Name,
|
|
276
|
+
Type: p.Type,
|
|
277
|
+
IsRequired: p.IsRequired,
|
|
278
|
+
DefaultValue: p.DefaultValue,
|
|
279
|
+
IsServerSet: p.IsServerSet,
|
|
280
|
+
}))
|
|
281
|
+
: parameters.map((p) => ({
|
|
282
|
+
Name: p.Name,
|
|
283
|
+
Type: p.SignatureType,
|
|
284
|
+
IsRequired: p.SignatureIsRequired,
|
|
285
|
+
DefaultValue: p.DefaultValue,
|
|
286
|
+
IsServerSet: false,
|
|
287
|
+
}));
|
|
288
|
+
const sigFields = query.Fields && query.Fields.length > 0
|
|
289
|
+
? query.Fields.map((f) => ({
|
|
290
|
+
Name: f.Name,
|
|
291
|
+
SQLBaseType: f.SQLBaseType,
|
|
292
|
+
InAllBranchVariants: f.InAllBranchVariants,
|
|
293
|
+
}))
|
|
294
|
+
: fields.map((f) => ({
|
|
295
|
+
Name: f.Name,
|
|
296
|
+
SQLBaseType: f.SQLBaseType,
|
|
297
|
+
InAllBranchVariants: !f.IsOptional,
|
|
298
|
+
}));
|
|
299
|
+
const signature = ComputeTypedQuerySignature({
|
|
300
|
+
Parameters: sigParams,
|
|
301
|
+
Fields: sigFields,
|
|
302
|
+
});
|
|
303
|
+
return {
|
|
304
|
+
Query: query,
|
|
305
|
+
Identifier: leafName,
|
|
306
|
+
LeafName: leafName,
|
|
307
|
+
CategorySegments: categorySegments,
|
|
308
|
+
FullPath: fullPath,
|
|
309
|
+
Summary: summary,
|
|
310
|
+
Parameters: parameters,
|
|
311
|
+
Fields: fields,
|
|
312
|
+
Signature: signature,
|
|
313
|
+
};
|
|
314
|
+
})
|
|
315
|
+
.sort((a, b) => ordinalCompare(a.FullPath, b.FullPath));
|
|
316
|
+
disambiguateCollisions(preliminary);
|
|
317
|
+
return preliminary;
|
|
318
|
+
}
|
|
319
|
+
function resolveParametersForQuery(query, fullPath, templateParams, docParams, warn) {
|
|
320
|
+
const storedByLower = new Map();
|
|
321
|
+
for (const p of query.Parameters ?? []) {
|
|
322
|
+
storedByLower.set(p.Name.trim().toLowerCase(), p);
|
|
323
|
+
}
|
|
324
|
+
const templateByLower = new Map();
|
|
325
|
+
for (const tp of templateParams) {
|
|
326
|
+
templateByLower.set(tp.Name.trim().toLowerCase(), tp);
|
|
327
|
+
}
|
|
328
|
+
const docByLower = new Map();
|
|
329
|
+
for (const dp of docParams) {
|
|
330
|
+
docByLower.set(dp.Name.trim().toLowerCase(), dp);
|
|
331
|
+
}
|
|
332
|
+
// Union parameter keys in deterministic order (sorted by canonical parameter name).
|
|
333
|
+
const orderedKeys = [];
|
|
334
|
+
const seen = new Set();
|
|
335
|
+
for (const p of query.Parameters ?? []) {
|
|
336
|
+
const key = p.Name.trim().toLowerCase();
|
|
337
|
+
if (key && !seen.has(key)) {
|
|
338
|
+
seen.add(key);
|
|
339
|
+
orderedKeys.push(key);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
for (const tp of templateParams) {
|
|
343
|
+
const key = tp.Name.trim().toLowerCase();
|
|
344
|
+
if (key && !seen.has(key)) {
|
|
345
|
+
seen.add(key);
|
|
346
|
+
orderedKeys.push(key);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
orderedKeys.sort(ordinalCompare);
|
|
350
|
+
const results = [];
|
|
351
|
+
for (const key of orderedKeys) {
|
|
352
|
+
const stored = storedByLower.get(key);
|
|
353
|
+
const tpl = templateByLower.get(key);
|
|
354
|
+
const doc = docByLower.get(key);
|
|
355
|
+
if (stored?.IsServerSet) {
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const name = stored?.Name?.trim() || tpl?.Name?.trim() || doc?.Name?.trim() || key;
|
|
359
|
+
// Precedence:
|
|
360
|
+
// 1. MJQ declared type (@param {type})
|
|
361
|
+
// 2. Manual parameter row type
|
|
362
|
+
// 3. Template InferredType (when not 'unknown')
|
|
363
|
+
// 4. Stored non-Manual parameter row type (when no template or when explicitly provided)
|
|
364
|
+
// 5. 'unknown' -> union type + warning
|
|
365
|
+
const declaredType = doc?.DeclaredType?.trim().toLowerCase() ?? null;
|
|
366
|
+
const storedType = stored?.Type?.trim().toLowerCase() ?? null;
|
|
367
|
+
const isManualRow = stored?.DetectionMethod === 'Manual';
|
|
368
|
+
const inferredType = tpl?.InferredType?.trim().toLowerCase() ?? null;
|
|
369
|
+
let effectiveType;
|
|
370
|
+
if (declaredType && VALID_DECLARED_PARAM_TYPES.has(declaredType)) {
|
|
371
|
+
effectiveType = declaredType;
|
|
372
|
+
}
|
|
373
|
+
else if (isManualRow && storedType && VALID_DECLARED_PARAM_TYPES.has(storedType)) {
|
|
374
|
+
effectiveType = storedType;
|
|
375
|
+
}
|
|
376
|
+
else if (inferredType && inferredType !== 'unknown' && VALID_DECLARED_PARAM_TYPES.has(inferredType)) {
|
|
377
|
+
effectiveType = inferredType;
|
|
378
|
+
}
|
|
379
|
+
else if (!tpl && storedType && VALID_DECLARED_PARAM_TYPES.has(storedType)) {
|
|
380
|
+
effectiveType = storedType;
|
|
381
|
+
}
|
|
382
|
+
else if (storedType && storedType !== 'string' && VALID_DECLARED_PARAM_TYPES.has(storedType)) {
|
|
383
|
+
effectiveType = storedType;
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
effectiveType = 'unknown';
|
|
387
|
+
warn(`[TypedQueryCodeGen] Query '${fullPath}' parameter '${name}' has type 'unknown'; ` +
|
|
388
|
+
`emitting 'string | number | boolean | Date | null'. Declare '@param {type} ${name}' or set the parameter type in metadata.`);
|
|
389
|
+
}
|
|
390
|
+
const defaultValue = stored?.DefaultValue != null && String(stored.DefaultValue).trim().length > 0
|
|
391
|
+
? String(stored.DefaultValue)
|
|
392
|
+
: tpl?.DefaultValue != null && String(tpl.DefaultValue).trim().length > 0
|
|
393
|
+
? String(tpl.DefaultValue)
|
|
394
|
+
: null;
|
|
395
|
+
const rawRequired = isManualRow && stored?.IsRequired !== undefined
|
|
396
|
+
? Boolean(stored.IsRequired)
|
|
397
|
+
: tpl !== undefined
|
|
398
|
+
? Boolean(tpl.IsRequired)
|
|
399
|
+
: Boolean(stored?.IsRequired);
|
|
400
|
+
const isRequired = rawRequired && defaultValue === null;
|
|
401
|
+
const signatureIsRequired = stored?.IsRequired !== undefined
|
|
402
|
+
? Boolean(stored.IsRequired) && defaultValue === null
|
|
403
|
+
: isRequired;
|
|
404
|
+
const description = doc?.Description?.trim() || stored?.Description?.trim() || null;
|
|
405
|
+
const signatureType = storedType && VALID_DECLARED_PARAM_TYPES.has(storedType) ? storedType : effectiveType;
|
|
406
|
+
results.push({
|
|
407
|
+
Name: name,
|
|
408
|
+
TSType: mapParamTypeToTSType(effectiveType),
|
|
409
|
+
EffectiveType: effectiveType,
|
|
410
|
+
SignatureType: signatureType,
|
|
411
|
+
SignatureIsRequired: signatureIsRequired,
|
|
412
|
+
IsRequired: isRequired,
|
|
413
|
+
DefaultValue: defaultValue,
|
|
414
|
+
Description: description,
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
results.sort((a, b) => ordinalCompare(a.Name, b.Name));
|
|
418
|
+
return results;
|
|
419
|
+
}
|
|
420
|
+
function mapParamTypeToTSType(paramType) {
|
|
421
|
+
switch (paramType) {
|
|
422
|
+
case 'string':
|
|
423
|
+
return 'string';
|
|
424
|
+
case 'number':
|
|
425
|
+
return 'number';
|
|
426
|
+
case 'boolean':
|
|
427
|
+
return 'boolean';
|
|
428
|
+
case 'date':
|
|
429
|
+
return 'Date | string';
|
|
430
|
+
case 'array':
|
|
431
|
+
return 'ReadonlyArray<string | number | boolean>';
|
|
432
|
+
default:
|
|
433
|
+
return 'string | number | boolean | Date | null';
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function resolveFieldsForQuery(query, entities, docFields) {
|
|
437
|
+
const docByLower = new Map();
|
|
438
|
+
for (const df of docFields) {
|
|
439
|
+
docByLower.set(df.Name.trim().toLowerCase(), df);
|
|
440
|
+
}
|
|
441
|
+
const sortedFields = [...(query.Fields ?? [])].sort((a, b) => {
|
|
442
|
+
const seqA = a.Sequence ?? Number.MAX_SAFE_INTEGER;
|
|
443
|
+
const seqB = b.Sequence ?? Number.MAX_SAFE_INTEGER;
|
|
444
|
+
if (seqA !== seqB)
|
|
445
|
+
return seqA - seqB;
|
|
446
|
+
return ordinalCompare(a.Name, b.Name);
|
|
447
|
+
});
|
|
448
|
+
return sortedFields.map((field, index) => {
|
|
449
|
+
const tsType = MapSQLBaseTypeToTSType(field.SQLBaseType);
|
|
450
|
+
const doc = docByLower.get(field.Name.trim().toLowerCase());
|
|
451
|
+
const description = doc?.Description?.trim() || field.Description?.trim() || null;
|
|
452
|
+
let isNullable = true;
|
|
453
|
+
if (!field.IsComputed && field.SourceFieldName && (field.SourceEntityID || field.SourceEntity)) {
|
|
454
|
+
const sourceEntity = findEntity(entities, field.SourceEntityID, field.SourceEntity);
|
|
455
|
+
const sourceFieldNameLower = field.SourceFieldName.trim().toLowerCase();
|
|
456
|
+
const sourceField = sourceEntity?.Fields.find((f) => f.Name.trim().toLowerCase() === sourceFieldNameLower);
|
|
457
|
+
if (sourceField) {
|
|
458
|
+
isNullable = Boolean(sourceField.AllowsNull);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const isOptional = field.InAllBranchVariants === false;
|
|
462
|
+
return {
|
|
463
|
+
Name: field.Name.trim(),
|
|
464
|
+
Sequence: field.Sequence ?? index + 1,
|
|
465
|
+
SQLBaseType: field.SQLBaseType,
|
|
466
|
+
TSType: tsType,
|
|
467
|
+
IsNullable: isNullable,
|
|
468
|
+
IsOptional: isOptional,
|
|
469
|
+
Description: description,
|
|
470
|
+
};
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
function disambiguateCollisions(specs) {
|
|
474
|
+
const byIdentifier = new Map();
|
|
475
|
+
for (const spec of specs) {
|
|
476
|
+
const list = byIdentifier.get(spec.Identifier);
|
|
477
|
+
if (list) {
|
|
478
|
+
list.push(spec);
|
|
479
|
+
}
|
|
480
|
+
else {
|
|
481
|
+
byIdentifier.set(spec.Identifier, [spec]);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
const usedIdentifiers = new Set();
|
|
485
|
+
for (const [id, group] of byIdentifier.entries()) {
|
|
486
|
+
if (group.length === 1) {
|
|
487
|
+
usedIdentifiers.add(id);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
for (const group of byIdentifier.values()) {
|
|
491
|
+
if (group.length <= 1)
|
|
492
|
+
continue;
|
|
493
|
+
for (const spec of group) {
|
|
494
|
+
let candidate = spec.LeafName;
|
|
495
|
+
// Walk category segments from leaf-most to root-most until unique
|
|
496
|
+
for (let depth = 1; depth <= spec.CategorySegments.length; depth++) {
|
|
497
|
+
const prefixSegments = spec.CategorySegments.slice(spec.CategorySegments.length - depth);
|
|
498
|
+
const prefix = prefixSegments.map((s) => ToQueryIdentifier(s)).join('');
|
|
499
|
+
const attempt = `${prefix}${spec.LeafName}`;
|
|
500
|
+
const collidesInGroup = group.some((other) => {
|
|
501
|
+
if (other === spec)
|
|
502
|
+
return false;
|
|
503
|
+
const otherPrefixSegments = other.CategorySegments.slice(Math.max(0, other.CategorySegments.length - depth));
|
|
504
|
+
const otherPrefix = otherPrefixSegments.map((s) => ToQueryIdentifier(s)).join('');
|
|
505
|
+
return `${otherPrefix}${other.LeafName}` === attempt;
|
|
506
|
+
});
|
|
507
|
+
if (!collidesInGroup && !usedIdentifiers.has(attempt)) {
|
|
508
|
+
candidate = attempt;
|
|
509
|
+
break;
|
|
510
|
+
}
|
|
511
|
+
candidate = attempt;
|
|
512
|
+
}
|
|
513
|
+
let finalId = candidate;
|
|
514
|
+
let suffix = 2;
|
|
515
|
+
while (usedIdentifiers.has(finalId)) {
|
|
516
|
+
finalId = `${candidate}${suffix}`;
|
|
517
|
+
suffix++;
|
|
518
|
+
}
|
|
519
|
+
spec.Identifier = finalId;
|
|
520
|
+
usedIdentifiers.add(finalId);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
function renderQueryDeclarationBlock(spec, emitZod) {
|
|
525
|
+
const lines = [];
|
|
526
|
+
const paramsInterfaceName = `${spec.Identifier}Params`;
|
|
527
|
+
const rowInterfaceName = `${spec.Identifier}Row`;
|
|
528
|
+
const rowSchemaName = `${spec.Identifier}RowSchema`;
|
|
529
|
+
// JSDoc header
|
|
530
|
+
lines.push('/**');
|
|
531
|
+
if (spec.Summary) {
|
|
532
|
+
for (const summaryLine of spec.Summary.split('\n')) {
|
|
533
|
+
lines.push(` * ${escapeJsDoc(summaryLine.trim())}`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
lines.push(` * Query: ${escapeJsDoc(spec.FullPath)} (ID ${spec.Query.ID})`);
|
|
537
|
+
lines.push(' */');
|
|
538
|
+
// Params interface
|
|
539
|
+
if (spec.Parameters.length === 0) {
|
|
540
|
+
lines.push(`export type ${paramsInterfaceName} = Record<string, never>;`);
|
|
541
|
+
}
|
|
542
|
+
else {
|
|
543
|
+
lines.push(`export interface ${paramsInterfaceName} {`);
|
|
544
|
+
for (const param of spec.Parameters) {
|
|
545
|
+
if (param.Description) {
|
|
546
|
+
lines.push(` /** ${escapeJsDoc(param.Description)} */`);
|
|
547
|
+
}
|
|
548
|
+
const propKey = formatPropertyKey(param.Name);
|
|
549
|
+
const opt = param.IsRequired ? '' : '?';
|
|
550
|
+
lines.push(` ${propKey}${opt}: ${param.TSType};`);
|
|
551
|
+
}
|
|
552
|
+
lines.push('}');
|
|
553
|
+
}
|
|
554
|
+
// Row interface
|
|
555
|
+
lines.push(`export interface ${rowInterfaceName} {`);
|
|
556
|
+
for (const field of spec.Fields) {
|
|
557
|
+
if (field.Description) {
|
|
558
|
+
lines.push(` /** ${escapeJsDoc(field.Description)} */`);
|
|
559
|
+
}
|
|
560
|
+
const propKey = formatPropertyKey(field.Name);
|
|
561
|
+
const opt = field.IsOptional ? '?' : '';
|
|
562
|
+
const nullUnion = field.IsNullable ? ' | null' : '';
|
|
563
|
+
lines.push(` ${propKey}${opt}: ${field.TSType}${nullUnion};`);
|
|
564
|
+
}
|
|
565
|
+
lines.push('}');
|
|
566
|
+
// Zod schema
|
|
567
|
+
if (emitZod) {
|
|
568
|
+
lines.push(`export const ${rowSchemaName} = z.object({`);
|
|
569
|
+
for (const field of spec.Fields) {
|
|
570
|
+
const propKey = formatPropertyKey(field.Name);
|
|
571
|
+
const zodExpr = buildZodFieldExpression(field);
|
|
572
|
+
lines.push(` ${propKey}: ${zodExpr},`);
|
|
573
|
+
}
|
|
574
|
+
lines.push('});');
|
|
575
|
+
}
|
|
576
|
+
// DefineTypedQuery constant
|
|
577
|
+
lines.push(`export const ${spec.Identifier} = DefineTypedQuery<${paramsInterfaceName}, ${rowInterfaceName}>({`);
|
|
578
|
+
lines.push(` QueryID: ${JSON.stringify(spec.Query.ID)},`);
|
|
579
|
+
lines.push(` Path: ${JSON.stringify(spec.FullPath)},`);
|
|
580
|
+
lines.push(` Signature: ${JSON.stringify(spec.Signature)},`);
|
|
581
|
+
if (emitZod) {
|
|
582
|
+
lines.push(` RowSchema: ${rowSchemaName},`);
|
|
583
|
+
}
|
|
584
|
+
lines.push('});');
|
|
585
|
+
return lines.join('\n');
|
|
586
|
+
}
|
|
587
|
+
function buildZodFieldExpression(field) {
|
|
588
|
+
let base;
|
|
589
|
+
switch (field.TSType) {
|
|
590
|
+
case 'number':
|
|
591
|
+
base = 'z.number()';
|
|
592
|
+
break;
|
|
593
|
+
case 'boolean':
|
|
594
|
+
base = 'z.boolean()';
|
|
595
|
+
break;
|
|
596
|
+
case 'Date':
|
|
597
|
+
base = 'z.coerce.date()';
|
|
598
|
+
break;
|
|
599
|
+
default:
|
|
600
|
+
base = 'z.string()';
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
if (field.IsNullable) {
|
|
604
|
+
base = `${base}.nullable()`;
|
|
605
|
+
}
|
|
606
|
+
if (field.IsOptional) {
|
|
607
|
+
base = `${base}.optional()`;
|
|
608
|
+
}
|
|
609
|
+
return base;
|
|
610
|
+
}
|
|
611
|
+
function renderQueriesNamespaceTree(specs) {
|
|
612
|
+
const root = {
|
|
613
|
+
children: new Map(),
|
|
614
|
+
queries: new Map(),
|
|
615
|
+
};
|
|
616
|
+
for (const spec of specs) {
|
|
617
|
+
let current = root;
|
|
618
|
+
for (const rawSegment of spec.CategorySegments) {
|
|
619
|
+
const segKey = ToQueryIdentifier(rawSegment);
|
|
620
|
+
let child = current.children.get(segKey);
|
|
621
|
+
if (!child) {
|
|
622
|
+
child = {
|
|
623
|
+
children: new Map(),
|
|
624
|
+
queries: new Map(),
|
|
625
|
+
};
|
|
626
|
+
current.children.set(segKey, child);
|
|
627
|
+
}
|
|
628
|
+
current = child;
|
|
629
|
+
}
|
|
630
|
+
let leafKey = spec.LeafName;
|
|
631
|
+
if (current.queries.has(leafKey) && current.queries.get(leafKey) !== spec.Identifier) {
|
|
632
|
+
leafKey = spec.Identifier;
|
|
633
|
+
}
|
|
634
|
+
current.queries.set(leafKey, spec.Identifier);
|
|
635
|
+
}
|
|
636
|
+
const bodyLines = renderNamespaceNode(root, 1);
|
|
637
|
+
return ['export const Queries = {', ...bodyLines, '} as const;'].join('\n');
|
|
638
|
+
}
|
|
639
|
+
function renderNamespaceNode(node, indentLevel) {
|
|
640
|
+
const indent = ' '.repeat(indentLevel);
|
|
641
|
+
const lines = [];
|
|
642
|
+
const childKeys = [...node.children.keys()].sort(ordinalCompare);
|
|
643
|
+
for (const key of childKeys) {
|
|
644
|
+
const child = node.children.get(key);
|
|
645
|
+
const propKey = formatPropertyKey(key);
|
|
646
|
+
lines.push(`${indent}${propKey}: {`);
|
|
647
|
+
lines.push(...renderNamespaceNode(child, indentLevel + 1));
|
|
648
|
+
lines.push(`${indent}},`);
|
|
649
|
+
}
|
|
650
|
+
const queryKeys = [...node.queries.keys()].sort(ordinalCompare);
|
|
651
|
+
for (const key of queryKeys) {
|
|
652
|
+
const targetIdentifier = node.queries.get(key);
|
|
653
|
+
let effectiveKey = key;
|
|
654
|
+
if (node.children.has(effectiveKey)) {
|
|
655
|
+
effectiveKey =
|
|
656
|
+
targetIdentifier !== effectiveKey && !node.children.has(targetIdentifier) && !node.queries.has(targetIdentifier)
|
|
657
|
+
? targetIdentifier
|
|
658
|
+
: `${effectiveKey}Query`;
|
|
659
|
+
let suffix = 2;
|
|
660
|
+
while (node.children.has(effectiveKey) || (effectiveKey !== key && node.queries.has(effectiveKey))) {
|
|
661
|
+
effectiveKey = `${key}Query_${suffix}`;
|
|
662
|
+
suffix++;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
const propKey = formatPropertyKey(effectiveKey);
|
|
666
|
+
if (propKey === targetIdentifier) {
|
|
667
|
+
lines.push(`${indent}${propKey},`);
|
|
668
|
+
}
|
|
669
|
+
else {
|
|
670
|
+
lines.push(`${indent}${propKey}: ${targetIdentifier},`);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return lines;
|
|
674
|
+
}
|
|
675
|
+
function formatPropertyKey(name) {
|
|
676
|
+
if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
|
|
677
|
+
return name;
|
|
678
|
+
}
|
|
679
|
+
return JSON.stringify(name);
|
|
680
|
+
}
|
|
681
|
+
function escapeJsDoc(text) {
|
|
682
|
+
return text.replace(/\*\//g, '*\\/');
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* CodeGen generator class that emits `queries/<schema>.ts` and `queries/index.ts`
|
|
686
|
+
* for approved, reusable MemberJunction queries.
|
|
687
|
+
*/
|
|
688
|
+
export class TypedQueryGeneratorBase {
|
|
689
|
+
GenerateTypedQueriesForDirectory(queries, entities, queriesOutputDir, schemaNames, options = {}) {
|
|
690
|
+
try {
|
|
691
|
+
const eligible = FilterEligibleTypedQueries(queries);
|
|
692
|
+
const allSchemas = Array.from(new Set([
|
|
693
|
+
...schemaNames,
|
|
694
|
+
...entities.map((e) => e.SchemaName),
|
|
695
|
+
])).filter(Boolean);
|
|
696
|
+
const bySchema = new Map();
|
|
697
|
+
for (const schema of schemaNames) {
|
|
698
|
+
bySchema.set(schema, []);
|
|
699
|
+
}
|
|
700
|
+
for (const q of eligible) {
|
|
701
|
+
const resolvedSchema = ResolveTypedQuerySchema(q, entities, allSchemas);
|
|
702
|
+
const matchingKey = [...bySchema.keys()].find((k) => SchemaKey(k) === SchemaKey(resolvedSchema));
|
|
703
|
+
if (matchingKey) {
|
|
704
|
+
bySchema.get(matchingKey).push(q);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
const filesToEmit = [];
|
|
708
|
+
let matchedCount = 0;
|
|
709
|
+
for (const [schema, schemaQueries] of bySchema.entries()) {
|
|
710
|
+
if (schemaQueries.length === 0 && SchemaKey(schema) !== '__mj') {
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
matchedCount += schemaQueries.length;
|
|
714
|
+
const stem = SanitizeSchemaFileName(schema);
|
|
715
|
+
const content = GenerateTypedQueriesFileContent(schemaQueries, entities, options);
|
|
716
|
+
filesToEmit.push({ stem, content });
|
|
717
|
+
}
|
|
718
|
+
if (filesToEmit.length === 0) {
|
|
719
|
+
return true;
|
|
720
|
+
}
|
|
721
|
+
fs.mkdirSync(queriesOutputDir, { recursive: true });
|
|
722
|
+
const barrelStems = [];
|
|
723
|
+
for (const { stem, content } of filesToEmit) {
|
|
724
|
+
barrelStems.push(stem);
|
|
725
|
+
const filePath = path.join(queriesOutputDir, `${stem}.ts`);
|
|
726
|
+
WriteFileIfChanged(filePath, content);
|
|
727
|
+
}
|
|
728
|
+
barrelStems.sort(ordinalCompare);
|
|
729
|
+
const barrelLines = [
|
|
730
|
+
'// AUTO-GENERATED FILE - DO NOT EDIT',
|
|
731
|
+
'// Generated by MemberJunction CodeGen (typed_query_codegen)',
|
|
732
|
+
'',
|
|
733
|
+
...barrelStems.map((stem) => `export * from './${stem}.js';`),
|
|
734
|
+
'',
|
|
735
|
+
];
|
|
736
|
+
const barrelPath = path.join(queriesOutputDir, 'index.ts');
|
|
737
|
+
WriteFileIfChanged(barrelPath, barrelLines.join('\n'));
|
|
738
|
+
logStatus(`Typed queries generated in ${queriesOutputDir} (${matchedCount} reusable approved quer${matchedCount === 1 ? 'y' : 'ies'})`);
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
catch (err) {
|
|
742
|
+
logError('Error generating typed queries', err);
|
|
743
|
+
return false;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
//# sourceMappingURL=typed_query_codegen.js.map
|