@memberjunction/codegen-lib 6.2.0 → 6.3.0-edge.0

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