cel-proto-parser 0.2.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.
@@ -0,0 +1,504 @@
1
+ "use strict";
2
+ /**
3
+ * CEL Deparser - Converts CEL AST back to CEL expression strings
4
+ *
5
+ * This module provides functionality to convert a CEL Abstract Syntax Tree (AST)
6
+ * back into a valid CEL expression string. It handles all CEL constructs including:
7
+ * - Literals (int, uint, double, string, bytes, bool, null)
8
+ * - Identifiers and field selection
9
+ * - Function calls and operators
10
+ * - Lists and maps
11
+ * - Comprehensions (macros like all, exists, filter, map)
12
+ * - Ternary conditionals
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.PRECEDENCE = void 0;
16
+ exports.deparse = deparse;
17
+ exports.generateDeparserCode = generateDeparserCode;
18
+ // CEL operator precedence (higher number = higher precedence)
19
+ exports.PRECEDENCE = {
20
+ CONDITIONAL: 1, // ?:
21
+ OR: 2, // ||
22
+ AND: 3, // &&
23
+ RELATION: 4, // == != < <= > >= in
24
+ ADDITION: 5, // + -
25
+ MULTIPLICATION: 6, // * / %
26
+ UNARY: 7, // ! -
27
+ MEMBER: 8, // . [] ()
28
+ PRIMARY: 9 // literals, identifiers, parentheses
29
+ };
30
+ // Binary operators and their precedence
31
+ const BINARY_OPERATORS = {
32
+ '_||_': { symbol: '||', precedence: exports.PRECEDENCE.OR },
33
+ '_&&_': { symbol: '&&', precedence: exports.PRECEDENCE.AND },
34
+ '_==_': { symbol: '==', precedence: exports.PRECEDENCE.RELATION },
35
+ '_!=_': { symbol: '!=', precedence: exports.PRECEDENCE.RELATION },
36
+ '_<_': { symbol: '<', precedence: exports.PRECEDENCE.RELATION },
37
+ '_<=_': { symbol: '<=', precedence: exports.PRECEDENCE.RELATION },
38
+ '_>_': { symbol: '>', precedence: exports.PRECEDENCE.RELATION },
39
+ '_>=_': { symbol: '>=', precedence: exports.PRECEDENCE.RELATION },
40
+ '@in': { symbol: 'in', precedence: exports.PRECEDENCE.RELATION },
41
+ '_in_': { symbol: 'in', precedence: exports.PRECEDENCE.RELATION },
42
+ '_+_': { symbol: '+', precedence: exports.PRECEDENCE.ADDITION },
43
+ '_-_': { symbol: '-', precedence: exports.PRECEDENCE.ADDITION },
44
+ '_*_': { symbol: '*', precedence: exports.PRECEDENCE.MULTIPLICATION },
45
+ '_/_': { symbol: '/', precedence: exports.PRECEDENCE.MULTIPLICATION },
46
+ '_%%_': { symbol: '%', precedence: exports.PRECEDENCE.MULTIPLICATION }
47
+ };
48
+ // Unary operators
49
+ const UNARY_OPERATORS = {
50
+ '!_': '!',
51
+ '-_': '-'
52
+ };
53
+ /**
54
+ * Escape a string for CEL string literal
55
+ */
56
+ function escapeString(str) {
57
+ return str
58
+ .replace(/\\/g, '\\\\')
59
+ .replace(/"/g, '\\"')
60
+ .replace(/\n/g, '\\n')
61
+ .replace(/\r/g, '\\r')
62
+ .replace(/\t/g, '\\t');
63
+ }
64
+ /**
65
+ * Escape bytes for CEL bytes literal
66
+ */
67
+ function escapeBytes(bytes) {
68
+ if (typeof bytes === 'string') {
69
+ // Assume it's already a hex string or similar
70
+ return bytes;
71
+ }
72
+ return Array.from(bytes)
73
+ .map((b) => {
74
+ if (b >= 32 && b < 127 && b !== 34 && b !== 92) {
75
+ return String.fromCharCode(b);
76
+ }
77
+ return '\\x' + b.toString(16).padStart(2, '0');
78
+ })
79
+ .join('');
80
+ }
81
+ /**
82
+ * Get the precedence of an expression
83
+ */
84
+ function getExprPrecedence(expr) {
85
+ if (expr.constExpr)
86
+ return exports.PRECEDENCE.PRIMARY;
87
+ if (expr.identExpr)
88
+ return exports.PRECEDENCE.PRIMARY;
89
+ if (expr.listExpr)
90
+ return exports.PRECEDENCE.PRIMARY;
91
+ if (expr.structExpr)
92
+ return exports.PRECEDENCE.PRIMARY;
93
+ if (expr.selectExpr)
94
+ return exports.PRECEDENCE.MEMBER;
95
+ if (expr.callExpr) {
96
+ const fn = expr.callExpr.function || '';
97
+ if (UNARY_OPERATORS[fn])
98
+ return exports.PRECEDENCE.UNARY;
99
+ if (BINARY_OPERATORS[fn])
100
+ return BINARY_OPERATORS[fn].precedence;
101
+ if (fn === '_?_:_')
102
+ return exports.PRECEDENCE.CONDITIONAL;
103
+ if (fn === '_[_]')
104
+ return exports.PRECEDENCE.MEMBER;
105
+ return exports.PRECEDENCE.MEMBER; // function call
106
+ }
107
+ if (expr.comprehensionExpr)
108
+ return exports.PRECEDENCE.PRIMARY;
109
+ return exports.PRECEDENCE.PRIMARY;
110
+ }
111
+ /**
112
+ * Deparse a CEL expression AST to a string
113
+ */
114
+ function deparse(expr, options = {}) {
115
+ const spaces = options.spaces ?? true;
116
+ const sp = spaces ? ' ' : '';
117
+ function deparseExpr(e, parentPrecedence = 0) {
118
+ // Constant expression
119
+ if (e.constExpr) {
120
+ return deparseConstant(e.constExpr);
121
+ }
122
+ // Identifier expression
123
+ if (e.identExpr) {
124
+ return e.identExpr.name || '';
125
+ }
126
+ // Select expression (field access)
127
+ if (e.selectExpr) {
128
+ const operand = e.selectExpr.operand
129
+ ? deparseExpr(e.selectExpr.operand, exports.PRECEDENCE.MEMBER)
130
+ : '';
131
+ const field = e.selectExpr.field || '';
132
+ if (e.selectExpr.testOnly) {
133
+ // This is the result of has() macro
134
+ return `has(${operand}.${field})`;
135
+ }
136
+ return `${operand}.${field}`;
137
+ }
138
+ // Call expression (function calls and operators)
139
+ if (e.callExpr) {
140
+ return deparseCall(e.callExpr, parentPrecedence);
141
+ }
142
+ // List expression
143
+ if (e.listExpr) {
144
+ const elements = e.listExpr.elements || [];
145
+ const optionalIndices = new Set(e.listExpr.optionalIndices || []);
146
+ const items = elements.map((el, i) => {
147
+ const prefix = optionalIndices.has(i) ? '?' : '';
148
+ return prefix + deparseExpr(el);
149
+ });
150
+ return `[${items.join(', ')}]`;
151
+ }
152
+ // Struct expression (map or message)
153
+ if (e.structExpr) {
154
+ return deparseStruct(e.structExpr);
155
+ }
156
+ // Comprehension expression (macros)
157
+ if (e.comprehensionExpr) {
158
+ return deparseComprehension(e.comprehensionExpr);
159
+ }
160
+ return '';
161
+ }
162
+ function deparseConstant(c) {
163
+ if (c.nullValue !== undefined) {
164
+ return 'null';
165
+ }
166
+ if (c.boolValue !== undefined) {
167
+ return c.boolValue ? 'true' : 'false';
168
+ }
169
+ if (c.int64Value !== undefined) {
170
+ return String(c.int64Value);
171
+ }
172
+ if (c.uint64Value !== undefined) {
173
+ return String(c.uint64Value) + 'u';
174
+ }
175
+ if (c.doubleValue !== undefined) {
176
+ const d = c.doubleValue;
177
+ // Ensure it looks like a float
178
+ if (Number.isInteger(d)) {
179
+ return d.toFixed(1);
180
+ }
181
+ return String(d);
182
+ }
183
+ if (c.stringValue !== undefined) {
184
+ return `"${escapeString(c.stringValue)}"`;
185
+ }
186
+ if (c.bytesValue !== undefined) {
187
+ return `b"${escapeBytes(c.bytesValue)}"`;
188
+ }
189
+ return '';
190
+ }
191
+ function deparseCall(call, parentPrecedence) {
192
+ const fn = call.function || '';
193
+ const args = call.args || [];
194
+ const target = call.target;
195
+ // Ternary conditional
196
+ if (fn === '_?_:_' && args.length === 3) {
197
+ const condition = deparseExpr(args[0], exports.PRECEDENCE.CONDITIONAL);
198
+ const trueExpr = deparseExpr(args[1], exports.PRECEDENCE.CONDITIONAL);
199
+ const falseExpr = deparseExpr(args[2], exports.PRECEDENCE.CONDITIONAL);
200
+ const result = `${condition}${sp}?${sp}${trueExpr}${sp}:${sp}${falseExpr}`;
201
+ return parentPrecedence > exports.PRECEDENCE.CONDITIONAL
202
+ ? `(${result})`
203
+ : result;
204
+ }
205
+ // Index operator
206
+ if (fn === '_[_]' && args.length === 2) {
207
+ const obj = deparseExpr(args[0], exports.PRECEDENCE.MEMBER);
208
+ const index = deparseExpr(args[1]);
209
+ return `${obj}[${index}]`;
210
+ }
211
+ // Unary operators
212
+ if (UNARY_OPERATORS[fn] && args.length === 1) {
213
+ const op = UNARY_OPERATORS[fn];
214
+ const operand = deparseExpr(args[0], exports.PRECEDENCE.UNARY);
215
+ return `${op}${operand}`;
216
+ }
217
+ // Binary operators
218
+ if (BINARY_OPERATORS[fn] && args.length === 2) {
219
+ const { symbol, precedence } = BINARY_OPERATORS[fn];
220
+ const left = deparseExpr(args[0], precedence);
221
+ const right = deparseExpr(args[1], precedence + 1); // Right associative needs higher precedence
222
+ const result = `${left}${sp}${symbol}${sp}${right}`;
223
+ return parentPrecedence > precedence ? `(${result})` : result;
224
+ }
225
+ // Method call (target.function(args))
226
+ if (target) {
227
+ const targetStr = deparseExpr(target, exports.PRECEDENCE.MEMBER);
228
+ const argsStr = args.map((a) => deparseExpr(a)).join(', ');
229
+ return `${targetStr}.${fn}(${argsStr})`;
230
+ }
231
+ // Regular function call
232
+ const argsStr = args.map((a) => deparseExpr(a)).join(', ');
233
+ return `${fn}(${argsStr})`;
234
+ }
235
+ function deparseStruct(struct) {
236
+ const messageName = struct.messageName || '';
237
+ const entries = struct.entries || [];
238
+ const items = entries.map((entry) => {
239
+ const prefix = entry.optionalEntry ? '?' : '';
240
+ if (entry.fieldKey) {
241
+ // Message field
242
+ const value = entry.value ? deparseExpr(entry.value) : '';
243
+ return `${prefix}${entry.fieldKey}: ${value}`;
244
+ }
245
+ else if (entry.mapKey) {
246
+ // Map entry
247
+ const key = deparseExpr(entry.mapKey);
248
+ const value = entry.value ? deparseExpr(entry.value) : '';
249
+ return `${prefix}${key}: ${value}`;
250
+ }
251
+ return '';
252
+ });
253
+ if (messageName) {
254
+ // Message construction
255
+ return `${messageName}{${items.join(', ')}}`;
256
+ }
257
+ else {
258
+ // Map literal
259
+ return `{${items.join(', ')}}`;
260
+ }
261
+ }
262
+ function deparseComprehension(comp) {
263
+ // Comprehensions are typically the result of macro expansion
264
+ // We try to reconstruct the original macro call
265
+ const iterVar = comp.iterVar || '';
266
+ const iterRange = comp.iterRange ? deparseExpr(comp.iterRange) : '';
267
+ const loopCondition = comp.loopCondition
268
+ ? deparseExpr(comp.loopCondition)
269
+ : '';
270
+ const loopStep = comp.loopStep ? deparseExpr(comp.loopStep) : '';
271
+ const result = comp.result ? deparseExpr(comp.result) : '';
272
+ const accuVar = comp.accuVar || '';
273
+ const accuInit = comp.accuInit ? deparseExpr(comp.accuInit) : '';
274
+ // Try to detect common macros based on structure
275
+ // exists: __result__ == true, accu starts false, step is || condition
276
+ if (accuVar === '__result__' && accuInit === 'false') {
277
+ // This looks like exists()
278
+ return `${iterRange}.exists(${iterVar}, ${loopStep.replace('__result__ || ', '')})`;
279
+ }
280
+ // all: __result__ == true, accu starts true, step is && condition
281
+ if (accuVar === '__result__' && accuInit === 'true') {
282
+ // This looks like all()
283
+ return `${iterRange}.all(${iterVar}, ${loopStep.replace('__result__ && ', '')})`;
284
+ }
285
+ // For other comprehensions, output a comment indicating it's a comprehension
286
+ // This is a fallback - ideally we'd reconstruct the original macro
287
+ return `/* comprehension: ${iterVar} in ${iterRange} */`;
288
+ }
289
+ return deparseExpr(expr);
290
+ }
291
+ /**
292
+ * Generate TypeScript code for the deparser module
293
+ */
294
+ function generateDeparserCode() {
295
+ // Return the deparser code as a string that can be written to a file
296
+ return `/**
297
+ * CEL Deparser - Converts CEL AST back to CEL expression strings
298
+ *
299
+ * This file was automatically generated by cel-proto-parser.
300
+ * DO NOT MODIFY IT BY HAND.
301
+ */
302
+
303
+ import type { Expr, Constant, Call, CreateStruct, Comprehension } from './types';
304
+
305
+ // CEL operator precedence (higher number = higher precedence)
306
+ export const PRECEDENCE = {
307
+ CONDITIONAL: 1, // ?:
308
+ OR: 2, // ||
309
+ AND: 3, // &&
310
+ RELATION: 4, // == != < <= > >= in
311
+ ADDITION: 5, // + -
312
+ MULTIPLICATION: 6, // * / %
313
+ UNARY: 7, // ! -
314
+ MEMBER: 8, // . [] ()
315
+ PRIMARY: 9 // literals, identifiers, parentheses
316
+ } as const;
317
+
318
+ // Binary operators and their precedence
319
+ const BINARY_OPERATORS: Record<string, { symbol: string; precedence: number }> = {
320
+ '_||_': { symbol: '||', precedence: PRECEDENCE.OR },
321
+ '_&&_': { symbol: '&&', precedence: PRECEDENCE.AND },
322
+ '_==_': { symbol: '==', precedence: PRECEDENCE.RELATION },
323
+ '_!=_': { symbol: '!=', precedence: PRECEDENCE.RELATION },
324
+ '_<_': { symbol: '<', precedence: PRECEDENCE.RELATION },
325
+ '_<=_': { symbol: '<=', precedence: PRECEDENCE.RELATION },
326
+ '_>_': { symbol: '>', precedence: PRECEDENCE.RELATION },
327
+ '_>=_': { symbol: '>=', precedence: PRECEDENCE.RELATION },
328
+ '@in': { symbol: 'in', precedence: PRECEDENCE.RELATION },
329
+ '_in_': { symbol: 'in', precedence: PRECEDENCE.RELATION },
330
+ '_+_': { symbol: '+', precedence: PRECEDENCE.ADDITION },
331
+ '_-_': { symbol: '-', precedence: PRECEDENCE.ADDITION },
332
+ '_*_': { symbol: '*', precedence: PRECEDENCE.MULTIPLICATION },
333
+ '_/_': { symbol: '/', precedence: PRECEDENCE.MULTIPLICATION },
334
+ '_%%_': { symbol: '%', precedence: PRECEDENCE.MULTIPLICATION }
335
+ };
336
+
337
+ // Unary operators
338
+ const UNARY_OPERATORS: Record<string, string> = {
339
+ '!_': '!',
340
+ '-_': '-'
341
+ };
342
+
343
+ export interface DeparserOptions {
344
+ /** Whether to add spaces around operators */
345
+ spaces?: boolean;
346
+ }
347
+
348
+ /**
349
+ * Escape a string for CEL string literal
350
+ */
351
+ function escapeString(str: string): string {
352
+ return str
353
+ .replace(/\\\\/g, '\\\\\\\\')
354
+ .replace(/"/g, '\\\\"')
355
+ .replace(/\\n/g, '\\\\n')
356
+ .replace(/\\r/g, '\\\\r')
357
+ .replace(/\\t/g, '\\\\t');
358
+ }
359
+
360
+ /**
361
+ * Escape bytes for CEL bytes literal
362
+ */
363
+ function escapeBytes(bytes: Uint8Array | string): string {
364
+ if (typeof bytes === 'string') {
365
+ return bytes;
366
+ }
367
+ return Array.from(bytes)
368
+ .map((b) => {
369
+ if (b >= 32 && b < 127 && b !== 34 && b !== 92) {
370
+ return String.fromCharCode(b);
371
+ }
372
+ return '\\\\x' + b.toString(16).padStart(2, '0');
373
+ })
374
+ .join('');
375
+ }
376
+
377
+ /**
378
+ * Deparse a CEL expression AST to a string
379
+ */
380
+ export function deparse(expr: Expr, options: DeparserOptions = {}): string {
381
+ const spaces = options.spaces ?? true;
382
+ const sp = spaces ? ' ' : '';
383
+
384
+ function deparseExpr(e: Expr, parentPrecedence: number = 0): string {
385
+ if (e.constExpr) return deparseConstant(e.constExpr);
386
+ if (e.identExpr) return e.identExpr.name || '';
387
+ if (e.selectExpr) {
388
+ const operand = e.selectExpr.operand ? deparseExpr(e.selectExpr.operand, PRECEDENCE.MEMBER) : '';
389
+ const field = e.selectExpr.field || '';
390
+ if (e.selectExpr.testOnly) return \`has(\${operand}.\${field})\`;
391
+ return \`\${operand}.\${field}\`;
392
+ }
393
+ if (e.callExpr) return deparseCall(e.callExpr, parentPrecedence);
394
+ if (e.listExpr) {
395
+ const elements = e.listExpr.elements || [];
396
+ const optionalIndices = new Set(e.listExpr.optionalIndices || []);
397
+ const items = elements.map((el, i) => {
398
+ const prefix = optionalIndices.has(i) ? '?' : '';
399
+ return prefix + deparseExpr(el);
400
+ });
401
+ return \`[\${items.join(', ')}]\`;
402
+ }
403
+ if (e.structExpr) return deparseStruct(e.structExpr);
404
+ if (e.comprehensionExpr) return deparseComprehension(e.comprehensionExpr);
405
+ return '';
406
+ }
407
+
408
+ function deparseConstant(c: Constant): string {
409
+ if (c.nullValue !== undefined) return 'null';
410
+ if (c.boolValue !== undefined) return c.boolValue ? 'true' : 'false';
411
+ if (c.int64Value !== undefined) return String(c.int64Value);
412
+ if (c.uint64Value !== undefined) return String(c.uint64Value) + 'u';
413
+ if (c.doubleValue !== undefined) {
414
+ const d = c.doubleValue;
415
+ if (Number.isInteger(d)) return d.toFixed(1);
416
+ return String(d);
417
+ }
418
+ if (c.stringValue !== undefined) return \`"\${escapeString(c.stringValue)}"\`;
419
+ if (c.bytesValue !== undefined) return \`b"\${escapeBytes(c.bytesValue)}"\`;
420
+ return '';
421
+ }
422
+
423
+ function deparseCall(call: Call, parentPrecedence: number): string {
424
+ const fn = call.function || '';
425
+ const args = call.args || [];
426
+ const target = call.target;
427
+
428
+ if (fn === '_?_:_' && args.length === 3) {
429
+ const condition = deparseExpr(args[0], PRECEDENCE.CONDITIONAL);
430
+ const trueExpr = deparseExpr(args[1], PRECEDENCE.CONDITIONAL);
431
+ const falseExpr = deparseExpr(args[2], PRECEDENCE.CONDITIONAL);
432
+ const result = \`\${condition}\${sp}?\${sp}\${trueExpr}\${sp}:\${sp}\${falseExpr}\`;
433
+ return parentPrecedence > PRECEDENCE.CONDITIONAL ? \`(\${result})\` : result;
434
+ }
435
+
436
+ if (fn === '_[_]' && args.length === 2) {
437
+ const obj = deparseExpr(args[0], PRECEDENCE.MEMBER);
438
+ const index = deparseExpr(args[1]);
439
+ return \`\${obj}[\${index}]\`;
440
+ }
441
+
442
+ if (UNARY_OPERATORS[fn] && args.length === 1) {
443
+ const op = UNARY_OPERATORS[fn];
444
+ const operand = deparseExpr(args[0], PRECEDENCE.UNARY);
445
+ return \`\${op}\${operand}\`;
446
+ }
447
+
448
+ if (BINARY_OPERATORS[fn] && args.length === 2) {
449
+ const { symbol, precedence } = BINARY_OPERATORS[fn];
450
+ const left = deparseExpr(args[0], precedence);
451
+ const right = deparseExpr(args[1], precedence + 1);
452
+ const result = \`\${left}\${sp}\${symbol}\${sp}\${right}\`;
453
+ return parentPrecedence > precedence ? \`(\${result})\` : result;
454
+ }
455
+
456
+ if (target) {
457
+ const targetStr = deparseExpr(target, PRECEDENCE.MEMBER);
458
+ const argsStr = args.map((a) => deparseExpr(a)).join(', ');
459
+ return \`\${targetStr}.\${fn}(\${argsStr})\`;
460
+ }
461
+
462
+ const argsStr = args.map((a) => deparseExpr(a)).join(', ');
463
+ return \`\${fn}(\${argsStr})\`;
464
+ }
465
+
466
+ function deparseStruct(struct: CreateStruct): string {
467
+ const messageName = struct.messageName || '';
468
+ const entries = struct.entries || [];
469
+ const items = entries.map((entry) => {
470
+ const prefix = entry.optionalEntry ? '?' : '';
471
+ if (entry.fieldKey) {
472
+ const value = entry.value ? deparseExpr(entry.value) : '';
473
+ return \`\${prefix}\${entry.fieldKey}: \${value}\`;
474
+ } else if (entry.mapKey) {
475
+ const key = deparseExpr(entry.mapKey);
476
+ const value = entry.value ? deparseExpr(entry.value) : '';
477
+ return \`\${prefix}\${key}: \${value}\`;
478
+ }
479
+ return '';
480
+ });
481
+ if (messageName) return \`\${messageName}{\${items.join(', ')}}\`;
482
+ return \`{\${items.join(', ')}}\`;
483
+ }
484
+
485
+ function deparseComprehension(comp: Comprehension): string {
486
+ const iterVar = comp.iterVar || '';
487
+ const iterRange = comp.iterRange ? deparseExpr(comp.iterRange) : '';
488
+ const accuVar = comp.accuVar || '';
489
+ const accuInit = comp.accuInit ? deparseExpr(comp.accuInit) : '';
490
+ const loopStep = comp.loopStep ? deparseExpr(comp.loopStep) : '';
491
+
492
+ if (accuVar === '__result__' && accuInit === 'false') {
493
+ return \`\${iterRange}.exists(\${iterVar}, \${loopStep.replace('__result__ || ', '')})\`;
494
+ }
495
+ if (accuVar === '__result__' && accuInit === 'true') {
496
+ return \`\${iterRange}.all(\${iterVar}, \${loopStep.replace('__result__ && ', '')})\`;
497
+ }
498
+ return \`/* comprehension: \${iterVar} in \${iterRange} */\`;
499
+ }
500
+
501
+ return deparseExpr(expr);
502
+ }
503
+ `;
504
+ }
@@ -0,0 +1,22 @@
1
+ import * as t from '@babel/types';
2
+ /**
3
+ * Convert a protobuf Enum to a TypeScript string union type
4
+ */
5
+ export function convertEnumToTsUnionType(enumNode) {
6
+ const enumName = enumNode.name;
7
+ const values = enumNode.values;
8
+ // Create string literal types for each enum value
9
+ const unionTypes = Object.keys(values).map((key) => t.tsLiteralType(t.stringLiteral(key)));
10
+ const typeAlias = t.tsTypeAliasDeclaration(t.identifier(enumName), null, t.tsUnionType(unionTypes));
11
+ return t.exportNamedDeclaration(typeAlias, []);
12
+ }
13
+ /**
14
+ * Convert a protobuf Enum to a TypeScript enum declaration
15
+ */
16
+ export function convertEnumToTsEnumDeclaration(enumNode) {
17
+ const enumName = enumNode.name;
18
+ const values = enumNode.values;
19
+ const members = Object.entries(values).map(([key, value]) => t.tsEnumMember(t.identifier(key), t.numericLiteral(value)));
20
+ const enumDecl = t.tsEnumDeclaration(t.identifier(enumName), members);
21
+ return t.exportNamedDeclaration(enumDecl, []);
22
+ }
@@ -0,0 +1,2 @@
1
+ export * from './types';
2
+ export * from './enums';
@@ -0,0 +1,117 @@
1
+ import * as t from '@babel/types';
2
+ import { toCamelCase, getFieldName, createNamedImport } from '../utils';
3
+ // Type mapping from protobuf to TypeScript
4
+ const PROTO_TO_TS_TYPE = {
5
+ string: 'string',
6
+ bool: 'boolean',
7
+ int32: 'number',
8
+ int64: 'bigint',
9
+ uint32: 'number',
10
+ uint64: 'bigint',
11
+ float: 'number',
12
+ double: 'number',
13
+ bytes: 'Uint8Array'
14
+ };
15
+ /**
16
+ * Resolve a protobuf type name to a TypeScript type reference
17
+ */
18
+ export function resolveTypeName(typeName) {
19
+ // Handle well-known Google protobuf types
20
+ if (typeName.startsWith('google.protobuf.')) {
21
+ const shortName = typeName.replace('google.protobuf.', '');
22
+ // Return as a qualified type reference
23
+ return t.tsTypeReference(t.tsQualifiedName(t.tsQualifiedName(t.identifier('google'), t.identifier('protobuf')), t.identifier(shortName)));
24
+ }
25
+ // Handle primitive types
26
+ const tsType = PROTO_TO_TS_TYPE[typeName];
27
+ if (tsType) {
28
+ switch (tsType) {
29
+ case 'string':
30
+ return t.tsStringKeyword();
31
+ case 'boolean':
32
+ return t.tsBooleanKeyword();
33
+ case 'number':
34
+ return t.tsNumberKeyword();
35
+ case 'bigint':
36
+ return t.tsBigIntKeyword();
37
+ default:
38
+ return t.tsTypeReference(t.identifier(tsType));
39
+ }
40
+ }
41
+ // Handle custom types (reference to other interfaces)
42
+ return t.tsTypeReference(t.identifier(typeName));
43
+ }
44
+ /**
45
+ * Generate import statements for enums
46
+ */
47
+ export function generateEnumImports(enums, source) {
48
+ return createNamedImport(enums.map((e) => e.name), source);
49
+ }
50
+ /**
51
+ * Generate a Node union type that includes all AST node types
52
+ */
53
+ export function generateNodeUnionType(types) {
54
+ // Generate wrapped object types: { TypeName: TypeName }
55
+ const unionTypeNames = types.map((type) => t.tsTypeLiteral([
56
+ t.tsPropertySignature(t.identifier(type.name), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(type.name))))
57
+ ]));
58
+ const unionTypeAlias = t.tsTypeAliasDeclaration(t.identifier('Node'), null, t.tsUnionType(unionTypeNames));
59
+ return t.exportNamedDeclaration(unionTypeAlias, []);
60
+ }
61
+ /**
62
+ * Convert a protobuf Type to a TypeScript interface
63
+ */
64
+ export function convertTypeToTsInterface(type, options) {
65
+ const typeName = type.name;
66
+ const fields = type.fields;
67
+ const properties = Object.entries(fields).map(([fieldName, field]) => {
68
+ const resolvedType = resolveTypeName(field.type);
69
+ const fieldType = field.rule === 'repeated' ? t.tsArrayType(resolvedType) : resolvedType;
70
+ const prop = t.tsPropertySignature(t.identifier(getFieldName(field, fieldName)), t.tsTypeAnnotation(fieldType));
71
+ prop.optional = options.types.optionalFields;
72
+ return prop;
73
+ });
74
+ const interfaceDecl = t.tsInterfaceDeclaration(t.identifier(typeName), null, [], t.tsInterfaceBody(properties));
75
+ return t.exportNamedDeclaration(interfaceDecl, []);
76
+ }
77
+ /**
78
+ * Generate AST helper factory methods
79
+ */
80
+ export function generateAstHelperMethods(types) {
81
+ const creators = types.map((type) => {
82
+ const typeName = type.name;
83
+ const param = t.identifier('_p');
84
+ param.optional = true;
85
+ param.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)));
86
+ const fields = type.fields;
87
+ // const _j = {} as TypeName;
88
+ const astNodeInit = t.variableDeclaration('const', [
89
+ t.variableDeclarator(t.identifier('_j'), t.tsAsExpression(t.objectExpression([]), t.tsTypeReference(t.identifier(typeName))))
90
+ ]);
91
+ // _o.set(_j, 'fieldName', _p?.fieldName);
92
+ const setStatements = Object.entries(fields).map(([fName, field]) => {
93
+ const fieldName = getFieldName(field, fName);
94
+ return t.expressionStatement(t.callExpression(t.memberExpression(t.identifier('_o'), t.identifier('set')), [
95
+ t.identifier('_j'),
96
+ t.stringLiteral(fieldName),
97
+ t.optionalMemberExpression(t.identifier('_p'), t.identifier(fieldName), false, true)
98
+ ]));
99
+ });
100
+ const methodName = toCamelCase(typeName);
101
+ const method = t.objectMethod('method', t.identifier(methodName), [param], t.blockStatement([
102
+ astNodeInit,
103
+ ...setStatements,
104
+ t.returnStatement(t.identifier('_j'))
105
+ ]));
106
+ method.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)));
107
+ return method;
108
+ });
109
+ return t.exportDefaultDeclaration(t.objectExpression(creators));
110
+ }
111
+ /**
112
+ * Generate import specifiers for types
113
+ */
114
+ export function generateTypeImportSpecifiers(types, options) {
115
+ const importSpecifiers = types.map((type) => t.importSpecifier(t.identifier(type.name), t.identifier(type.name)));
116
+ return t.importDeclaration(importSpecifiers, t.stringLiteral(options.utils.astHelpers.typesSource));
117
+ }