rawsql-ts 0.11.18-beta → 0.11.19-beta

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.
@@ -12,6 +12,8 @@ export * from './transformers/CTEDisabler';
12
12
  export * from './transformers/CTEDependencyAnalyzer';
13
13
  export * from './transformers/CTEQueryDecomposer';
14
14
  export * from './transformers/CTEComposer';
15
+ export * from './transformers/CTERenamer';
16
+ export * from './transformers/ColumnReferenceCollector';
15
17
  export * from './transformers/Formatter';
16
18
  export * from './transformers/SqlFormatter';
17
19
  export * from './transformers/PostgresJsonQueryBuilder';
package/dist/src/index.js CHANGED
@@ -30,6 +30,8 @@ __exportStar(require("./transformers/CTEDisabler"), exports);
30
30
  __exportStar(require("./transformers/CTEDependencyAnalyzer"), exports);
31
31
  __exportStar(require("./transformers/CTEQueryDecomposer"), exports);
32
32
  __exportStar(require("./transformers/CTEComposer"), exports);
33
+ __exportStar(require("./transformers/CTERenamer"), exports);
34
+ __exportStar(require("./transformers/ColumnReferenceCollector"), exports);
33
35
  __exportStar(require("./transformers/Formatter"), exports);
34
36
  __exportStar(require("./transformers/SqlFormatter"), exports);
35
37
  __exportStar(require("./transformers/PostgresJsonQueryBuilder"), exports);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,oCAAoC;AACpC,8DAA4C;AAC5C,8DAA4C;AAE5C,6DAA2C;AAC3C,uDAAqC;AACrC,0DAAwC;AACxC,uDAAqC;AACrC,oDAAkC;AAClC,kDAAgC;AAEhC,8DAA4C;AAC5C,+DAA6C;AAC7C,6DAA2C;AAC3C,uEAAqD;AACrD,oEAAkD;AAClD,6DAA2C;AAC3C,2DAAyC;AACzC,8DAA4C;AAC5C,0EAAwD;AACxD,8DAA4C,CAAC,0BAA0B;AACvE,sEAAoD;AACpD,2EAAyD;AACzD,qEAAmD;AACnD,sEAAoD;AACpD,sEAA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E;AAA5D,sHAAA,gBAAgB,OAAA;AACzB,2EAAyD;AACzD,iFAA+D;AAE/D,iEAA+C;AAC/C,2EAAyD;AACzD,kEAAgD;AAChD,iEAA+C;AAC/C,uEAAqD;AACrD,qEAAmD;AAEnD,6DAA2C;AAC3C,8DAA4C;AAC5C,wDAAsC;AACtC,wDAAsC;AACtC,uDAAqC;AAGrC,oEAAoE"}
@@ -0,0 +1,144 @@
1
+ import { SelectQuery } from "../models/SelectQuery";
2
+ /**
3
+ * A utility class for renaming Common Table Expressions (CTEs) in SQL queries.
4
+ *
5
+ * This class provides functionality to safely rename CTEs while automatically updating
6
+ * all column references and table references throughout the query, including within
7
+ * nested CTE definitions and subqueries.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { CTERenamer, SelectQueryParser } from 'rawsql-ts';
12
+ *
13
+ * const sql = `
14
+ * WITH user_data AS (
15
+ * SELECT id, name FROM users
16
+ * ),
17
+ * order_summary AS (
18
+ * SELECT user_data.id, COUNT(*) as order_count
19
+ * FROM user_data
20
+ * JOIN orders ON user_data.id = orders.user_id
21
+ * GROUP BY user_data.id
22
+ * )
23
+ * SELECT * FROM order_summary
24
+ * `;
25
+ *
26
+ * const query = SelectQueryParser.parse(sql);
27
+ * const renamer = new CTERenamer();
28
+ *
29
+ * // Rename 'user_data' to 'customer_data'
30
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
31
+ *
32
+ * // All references are automatically updated:
33
+ * // - CTE definition: WITH customer_data AS (...)
34
+ * // - Column references: customer_data.id
35
+ * // - Table references: FROM customer_data
36
+ * ```
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // Error handling
41
+ * try {
42
+ * renamer.renameCTE(query, 'nonexistent_cte', 'new_name');
43
+ * } catch (error) {
44
+ * console.error(error.message); // "CTE 'nonexistent_cte' does not exist"
45
+ * }
46
+ *
47
+ * try {
48
+ * renamer.renameCTE(query, 'existing_cte', 'already_exists');
49
+ * } catch (error) {
50
+ * console.error(error.message); // "CTE 'already_exists' already exists"
51
+ * }
52
+ * ```
53
+ *
54
+ * @since 0.11.16
55
+ */
56
+ export declare class CTERenamer {
57
+ private dependencyAnalyzer;
58
+ private columnReferenceCollector;
59
+ private tableSourceCollector;
60
+ /**
61
+ * Creates a new instance of CTERenamer.
62
+ *
63
+ * The constructor initializes internal collectors and analyzers needed for
64
+ * comprehensive CTE renaming operations.
65
+ */
66
+ constructor();
67
+ /**
68
+ * Renames a Common Table Expression (CTE) and updates all references to it.
69
+ *
70
+ * This method performs a comprehensive rename operation that includes:
71
+ * - Updating the CTE definition name in the WITH clause
72
+ * - Updating all column references (e.g., `old_name.column` → `new_name.column`)
73
+ * - Updating all table references in FROM and JOIN clauses
74
+ * - Processing references within nested CTEs and subqueries
75
+ *
76
+ * @param query - The SQL query containing the CTE to rename. Can be either SimpleSelectQuery or BinarySelectQuery (UNION/INTERSECT/EXCEPT).
77
+ * @param oldName - The current name of the CTE to rename.
78
+ * @param newName - The new name for the CTE.
79
+ *
80
+ * @throws {Error} When the specified CTE does not exist in the query.
81
+ * @throws {Error} When a CTE with the new name already exists.
82
+ * @throws {Error} When the query type is not supported (not a SelectQuery).
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const renamer = new CTERenamer();
87
+ *
88
+ * // Basic usage
89
+ * renamer.renameCTE(query, 'old_cte_name', 'new_cte_name');
90
+ *
91
+ * // With error handling
92
+ * try {
93
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
94
+ * } catch (error) {
95
+ * if (error.message.includes('does not exist')) {
96
+ * console.log('CTE not found');
97
+ * } else if (error.message.includes('already exists')) {
98
+ * console.log('Name conflict');
99
+ * }
100
+ * }
101
+ * ```
102
+ *
103
+ * @since 0.11.16
104
+ */
105
+ renameCTE(query: SelectQuery, oldName: string, newName: string): void;
106
+ /**
107
+ * Validates input parameters for CTE renaming.
108
+ */
109
+ private validateInputs;
110
+ /**
111
+ * Handles CTE renaming for SimpleSelectQuery.
112
+ */
113
+ private renameInSimpleQuery;
114
+ /**
115
+ * Handles CTE renaming for BinarySelectQuery.
116
+ */
117
+ private renameInBinaryQuery;
118
+ /**
119
+ * Recursively handles CTE renaming for any SelectQuery type.
120
+ */
121
+ private renameInSelectQuery;
122
+ /**
123
+ * Renames the CTE definition in the WITH clause.
124
+ */
125
+ private renameCTEDefinition;
126
+ /**
127
+ * Updates all references to the old CTE name (column references and table sources).
128
+ */
129
+ private updateAllReferences;
130
+ /**
131
+ * Updates table sources within CTE definitions that reference the old CTE name.
132
+ * This method manually traverses CTE internals to avoid infinite recursion
133
+ * that occurs when using TableSourceCollector with selectableOnly=false.
134
+ */
135
+ private updateTableSourcesInCTEs;
136
+ /**
137
+ * Updates table sources in a specific query (used for CTE internals).
138
+ */
139
+ private updateTableSourcesInQuery;
140
+ /**
141
+ * Updates a specific table source if it matches the old CTE name.
142
+ */
143
+ private updateTableSource;
144
+ }
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CTERenamer = void 0;
4
+ const SimpleSelectQuery_1 = require("../models/SimpleSelectQuery");
5
+ const BinarySelectQuery_1 = require("../models/BinarySelectQuery");
6
+ const CTEDependencyAnalyzer_1 = require("./CTEDependencyAnalyzer");
7
+ const TableSourceCollector_1 = require("./TableSourceCollector");
8
+ const ColumnReferenceCollector_1 = require("./ColumnReferenceCollector");
9
+ const ValueComponent_1 = require("../models/ValueComponent");
10
+ /**
11
+ * Error messages for CTE renaming operations.
12
+ */
13
+ const ERROR_MESSAGES = {
14
+ nullQuery: 'Query cannot be null or undefined',
15
+ invalidOldName: 'Old CTE name must be a non-empty string',
16
+ invalidNewName: 'New CTE name must be a non-empty string',
17
+ sameNames: 'Old and new CTE names cannot be the same',
18
+ unsupportedQuery: 'Unsupported query type for CTE renaming',
19
+ cteNotExists: (name) => `CTE '${name}' does not exist`,
20
+ cteAlreadyExists: (name) => `CTE '${name}' already exists`,
21
+ cteNotFound: (name) => `CTE '${name}' not found`,
22
+ };
23
+ /**
24
+ * A utility class for renaming Common Table Expressions (CTEs) in SQL queries.
25
+ *
26
+ * This class provides functionality to safely rename CTEs while automatically updating
27
+ * all column references and table references throughout the query, including within
28
+ * nested CTE definitions and subqueries.
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * import { CTERenamer, SelectQueryParser } from 'rawsql-ts';
33
+ *
34
+ * const sql = `
35
+ * WITH user_data AS (
36
+ * SELECT id, name FROM users
37
+ * ),
38
+ * order_summary AS (
39
+ * SELECT user_data.id, COUNT(*) as order_count
40
+ * FROM user_data
41
+ * JOIN orders ON user_data.id = orders.user_id
42
+ * GROUP BY user_data.id
43
+ * )
44
+ * SELECT * FROM order_summary
45
+ * `;
46
+ *
47
+ * const query = SelectQueryParser.parse(sql);
48
+ * const renamer = new CTERenamer();
49
+ *
50
+ * // Rename 'user_data' to 'customer_data'
51
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
52
+ *
53
+ * // All references are automatically updated:
54
+ * // - CTE definition: WITH customer_data AS (...)
55
+ * // - Column references: customer_data.id
56
+ * // - Table references: FROM customer_data
57
+ * ```
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * // Error handling
62
+ * try {
63
+ * renamer.renameCTE(query, 'nonexistent_cte', 'new_name');
64
+ * } catch (error) {
65
+ * console.error(error.message); // "CTE 'nonexistent_cte' does not exist"
66
+ * }
67
+ *
68
+ * try {
69
+ * renamer.renameCTE(query, 'existing_cte', 'already_exists');
70
+ * } catch (error) {
71
+ * console.error(error.message); // "CTE 'already_exists' already exists"
72
+ * }
73
+ * ```
74
+ *
75
+ * @since 0.11.16
76
+ */
77
+ class CTERenamer {
78
+ /**
79
+ * Creates a new instance of CTERenamer.
80
+ *
81
+ * The constructor initializes internal collectors and analyzers needed for
82
+ * comprehensive CTE renaming operations.
83
+ */
84
+ constructor() {
85
+ this.dependencyAnalyzer = new CTEDependencyAnalyzer_1.CTEDependencyAnalyzer();
86
+ this.columnReferenceCollector = new ColumnReferenceCollector_1.ColumnReferenceCollector();
87
+ this.tableSourceCollector = new TableSourceCollector_1.TableSourceCollector(); // Use default selectableOnly=true to avoid infinite recursion
88
+ }
89
+ /**
90
+ * Renames a Common Table Expression (CTE) and updates all references to it.
91
+ *
92
+ * This method performs a comprehensive rename operation that includes:
93
+ * - Updating the CTE definition name in the WITH clause
94
+ * - Updating all column references (e.g., `old_name.column` → `new_name.column`)
95
+ * - Updating all table references in FROM and JOIN clauses
96
+ * - Processing references within nested CTEs and subqueries
97
+ *
98
+ * @param query - The SQL query containing the CTE to rename. Can be either SimpleSelectQuery or BinarySelectQuery (UNION/INTERSECT/EXCEPT).
99
+ * @param oldName - The current name of the CTE to rename.
100
+ * @param newName - The new name for the CTE.
101
+ *
102
+ * @throws {Error} When the specified CTE does not exist in the query.
103
+ * @throws {Error} When a CTE with the new name already exists.
104
+ * @throws {Error} When the query type is not supported (not a SelectQuery).
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * const renamer = new CTERenamer();
109
+ *
110
+ * // Basic usage
111
+ * renamer.renameCTE(query, 'old_cte_name', 'new_cte_name');
112
+ *
113
+ * // With error handling
114
+ * try {
115
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
116
+ * } catch (error) {
117
+ * if (error.message.includes('does not exist')) {
118
+ * console.log('CTE not found');
119
+ * } else if (error.message.includes('already exists')) {
120
+ * console.log('Name conflict');
121
+ * }
122
+ * }
123
+ * ```
124
+ *
125
+ * @since 0.11.16
126
+ */
127
+ renameCTE(query, oldName, newName) {
128
+ // Input validation
129
+ this.validateInputs(query, oldName, newName);
130
+ // Sanitize input names
131
+ const sanitizedOldName = oldName.trim();
132
+ const sanitizedNewName = newName.trim();
133
+ if (query instanceof SimpleSelectQuery_1.SimpleSelectQuery) {
134
+ this.renameInSimpleQuery(query, sanitizedOldName, sanitizedNewName);
135
+ }
136
+ else if (query instanceof BinarySelectQuery_1.BinarySelectQuery) {
137
+ this.renameInBinaryQuery(query, sanitizedOldName, sanitizedNewName);
138
+ }
139
+ else {
140
+ throw new Error(ERROR_MESSAGES.unsupportedQuery);
141
+ }
142
+ }
143
+ /**
144
+ * Validates input parameters for CTE renaming.
145
+ */
146
+ validateInputs(query, oldName, newName) {
147
+ if (!query) {
148
+ throw new Error(ERROR_MESSAGES.nullQuery);
149
+ }
150
+ if (!oldName || typeof oldName !== 'string' || oldName.trim() === '') {
151
+ throw new Error(ERROR_MESSAGES.invalidOldName);
152
+ }
153
+ if (!newName || typeof newName !== 'string' || newName.trim() === '') {
154
+ throw new Error(ERROR_MESSAGES.invalidNewName);
155
+ }
156
+ if (oldName.trim() === newName.trim()) {
157
+ throw new Error(ERROR_MESSAGES.sameNames);
158
+ }
159
+ }
160
+ /**
161
+ * Handles CTE renaming for SimpleSelectQuery.
162
+ */
163
+ renameInSimpleQuery(query, oldName, newName) {
164
+ // Get available CTE names
165
+ const availableCTEs = query.getCTENames();
166
+ // Check if CTE exists
167
+ if (!availableCTEs.includes(oldName)) {
168
+ throw new Error(ERROR_MESSAGES.cteNotExists(oldName));
169
+ }
170
+ // Check for name conflicts
171
+ if (availableCTEs.includes(newName)) {
172
+ throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));
173
+ }
174
+ // Rename CTE definition
175
+ this.renameCTEDefinition(query, oldName, newName);
176
+ // Update all references
177
+ this.updateAllReferences(query, oldName, newName);
178
+ }
179
+ /**
180
+ * Handles CTE renaming for BinarySelectQuery.
181
+ */
182
+ renameInBinaryQuery(query, oldName, newName) {
183
+ // Use toSimpleQuery() only for WITH clause inspection (not for writing back)
184
+ const withClauseQuery = query.toSimpleQuery();
185
+ // Get available CTE names from the converted query
186
+ let availableCTEs = [];
187
+ if (withClauseQuery.withClause && withClauseQuery.withClause.tables) {
188
+ availableCTEs = withClauseQuery.withClause.tables.map(cte => cte.aliasExpression.table.name);
189
+ }
190
+ // Check if CTE exists
191
+ if (!availableCTEs.includes(oldName)) {
192
+ throw new Error(ERROR_MESSAGES.cteNotExists(oldName));
193
+ }
194
+ // Check for name conflicts
195
+ if (availableCTEs.includes(newName)) {
196
+ throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));
197
+ }
198
+ // Rename CTE definition in the converted query (this affects the original BinarySelectQuery)
199
+ this.renameCTEDefinition(withClauseQuery, oldName, newName);
200
+ // Add withClause to original BinarySelectQuery and left query for proper formatting
201
+ if (withClauseQuery.withClause) {
202
+ query.withClause = withClauseQuery.withClause;
203
+ // Also add to left query so formatter can display it
204
+ if (query.left instanceof SimpleSelectQuery_1.SimpleSelectQuery) {
205
+ query.left.withClause = withClauseQuery.withClause;
206
+ }
207
+ }
208
+ // Recursively update references in left and right branches
209
+ this.renameInSelectQuery(query.left, oldName, newName);
210
+ this.renameInSelectQuery(query.right, oldName, newName);
211
+ }
212
+ /**
213
+ * Recursively handles CTE renaming for any SelectQuery type.
214
+ */
215
+ renameInSelectQuery(query, oldName, newName) {
216
+ if (query instanceof SimpleSelectQuery_1.SimpleSelectQuery) {
217
+ // For SimpleSelectQuery, only update references (not CTE definitions)
218
+ this.updateAllReferences(query, oldName, newName);
219
+ }
220
+ else if (query instanceof BinarySelectQuery_1.BinarySelectQuery) {
221
+ // Recursively process left and right branches
222
+ this.renameInSelectQuery(query.left, oldName, newName);
223
+ this.renameInSelectQuery(query.right, oldName, newName);
224
+ }
225
+ // ValuesQuery: do nothing
226
+ }
227
+ /**
228
+ * Renames the CTE definition in the WITH clause.
229
+ */
230
+ renameCTEDefinition(query, oldName, newName) {
231
+ if (!query.withClause || !query.withClause.tables) {
232
+ throw new Error(ERROR_MESSAGES.cteNotFound(oldName));
233
+ }
234
+ const cteToRename = query.withClause.tables.find(cte => cte.aliasExpression.table.name === oldName);
235
+ if (!cteToRename) {
236
+ throw new Error(ERROR_MESSAGES.cteNotFound(oldName));
237
+ }
238
+ cteToRename.aliasExpression.table.name = newName;
239
+ }
240
+ /**
241
+ * Updates all references to the old CTE name (column references and table sources).
242
+ */
243
+ updateAllReferences(query, oldName, newName) {
244
+ // Collect all column references from the query (including CTE internals)
245
+ const columnReferences = this.columnReferenceCollector.collect(query);
246
+ // Update all column references that reference the old CTE name
247
+ for (const columnRef of columnReferences) {
248
+ // Check namespaces for the old CTE name
249
+ if (columnRef.namespaces && columnRef.namespaces.length > 0) {
250
+ // Check if any namespace matches the old CTE name
251
+ for (const namespace of columnRef.namespaces) {
252
+ if (namespace.name === oldName) {
253
+ namespace.name = newName;
254
+ break;
255
+ }
256
+ }
257
+ }
258
+ }
259
+ // Update table sources in the main query
260
+ const tableSources = this.tableSourceCollector.collect(query);
261
+ for (const tableSource of tableSources) {
262
+ if (tableSource.getSourceName() === oldName) {
263
+ if (tableSource.qualifiedName.name instanceof ValueComponent_1.ColumnReference) {
264
+ // Handle ColumnReference case if needed
265
+ }
266
+ else if ('name' in tableSource.qualifiedName.name) {
267
+ // Handle IdentifierString
268
+ tableSource.qualifiedName.name.name = newName;
269
+ }
270
+ else {
271
+ // Handle RawString
272
+ tableSource.qualifiedName.name.value = newName;
273
+ }
274
+ }
275
+ }
276
+ // Update table sources that reference the old CTE name within CTEs
277
+ this.updateTableSourcesInCTEs(query, oldName, newName);
278
+ }
279
+ /**
280
+ * Updates table sources within CTE definitions that reference the old CTE name.
281
+ * This method manually traverses CTE internals to avoid infinite recursion
282
+ * that occurs when using TableSourceCollector with selectableOnly=false.
283
+ */
284
+ updateTableSourcesInCTEs(query, oldName, newName) {
285
+ if (!query.withClause || !query.withClause.tables) {
286
+ return;
287
+ }
288
+ // Traverse each CTE and update table sources in their FROM clauses
289
+ for (const cte of query.withClause.tables) {
290
+ this.updateTableSourcesInQuery(cte.query, oldName, newName);
291
+ }
292
+ }
293
+ /**
294
+ * Updates table sources in a specific query (used for CTE internals).
295
+ */
296
+ updateTableSourcesInQuery(query, oldName, newName) {
297
+ // Update FROM clause
298
+ if (query.fromClause && query.fromClause.source.datasource) {
299
+ this.updateTableSource(query.fromClause.source.datasource, oldName, newName);
300
+ }
301
+ // Update JOIN clauses
302
+ if (query.fromClause && query.fromClause.joins) {
303
+ for (const join of query.fromClause.joins) {
304
+ if (join.source.datasource) {
305
+ this.updateTableSource(join.source.datasource, oldName, newName);
306
+ }
307
+ }
308
+ }
309
+ }
310
+ /**
311
+ * Updates a specific table source if it matches the old CTE name.
312
+ */
313
+ updateTableSource(datasource, oldName, newName) {
314
+ // Type guard and null checks for security
315
+ if (!datasource || typeof datasource !== 'object') {
316
+ return;
317
+ }
318
+ const source = datasource;
319
+ // Safely check if this is a TableSource
320
+ if (typeof source.getSourceName === 'function') {
321
+ try {
322
+ const sourceName = source.getSourceName();
323
+ if (sourceName === oldName && source.qualifiedName && typeof source.qualifiedName === 'object') {
324
+ const qualifiedName = source.qualifiedName;
325
+ if (qualifiedName.name && typeof qualifiedName.name === 'object') {
326
+ const nameObj = qualifiedName.name;
327
+ if ('name' in nameObj && typeof nameObj.name === 'string') {
328
+ // Handle IdentifierString
329
+ nameObj.name = newName;
330
+ }
331
+ else if ('value' in nameObj && typeof nameObj.value === 'string') {
332
+ // Handle RawString
333
+ nameObj.value = newName;
334
+ }
335
+ }
336
+ }
337
+ }
338
+ catch (error) {
339
+ // Safely handle any unexpected errors during table source update
340
+ console.warn('Warning: Failed to update table source:', error);
341
+ }
342
+ }
343
+ }
344
+ }
345
+ exports.CTERenamer = CTERenamer;
346
+ //# sourceMappingURL=CTERenamer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CTERenamer.js","sourceRoot":"","sources":["../../../src/transformers/CTERenamer.ts"],"names":[],"mappings":";;;AAAA,mEAAgE;AAChE,mEAAgE;AAEhE,mEAAgE;AAChE,iEAA8D;AAC9D,yEAAsE;AACtE,6DAA2D;AAE3D;;GAEG;AACH,MAAM,cAAc,GAAG;IACnB,SAAS,EAAE,mCAAmC;IAC9C,cAAc,EAAE,yCAAyC;IACzD,cAAc,EAAE,yCAAyC;IACzD,SAAS,EAAE,0CAA0C;IACrD,gBAAgB,EAAE,yCAAyC;IAC3D,YAAY,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,QAAQ,IAAI,kBAAkB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