uql-codemod 0.55.0 → 0.56.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 CHANGED
@@ -42,6 +42,7 @@ Only `--flag=value` is read, and anything unrecognised is an error. It exits `0`
42
42
  - Imports off `uql-orm/maria`, `uql-orm/mongo` and `uql-orm/bunSql` to `uql-orm/mariadb`, `uql-orm/mongodb` and `uql-orm/bun-sql`, and off `uql-orm/type`, `uql-orm/dialect`, `uql-orm/entity`, `uql-orm/querier` and `uql-orm/namingStrategy` to `uql-orm`.
43
43
  - A sole numeric key to the generated one it was: `f.number().id()` to `f.number().autoIncrement()`, `f.bigint().id()` to `f.bigint().autoIncrement()`, and `.autoIncrement()` on `f.column('int').id()`. `.autoIncrement(false)` is dropped, a key no longer needing it, and a key a relation shares stays as it is. A class's `id!` stays too, which an insert then has to name until it is `id?` or listed in `[filledKey]`. On MongoDB, take `.autoIncrement()` off a numeric key: nothing generates one there. A subclass's `.autoIncrement()` on a column that is no key, its key inherited, stays and has to go by hand.
44
44
  - The `[idKey]?: '...'` brand, and its import, on a key not called `id`, `_id` or `uuid` and on every composite.
45
+ - A `security: true` filter to the policy replacing it, where it reads the context as data: `tenant: { where: (ctx) => (ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined), security: true }` in `@Entity`'s or `defineEntity`'s `filters` to `policies: [{ must: { companyId: $context.tenantId } }]`, keeping its `ops`, a `.filters({ ... })` section to `.policies([...])`, and one a `@Filter` declares once it is folded into `@Entity`.
45
46
 
46
47
  ## What it leaves to you
47
48
 
@@ -67,6 +68,7 @@ Reported with what to do, never guessed:
67
68
  - A column option it cannot write as a method: a `shape` a JSON column no longer takes, a migration column's options passed as a variable, or a flag such as `unique: isUnique` that no literal states.
68
69
  - A `@Field`/`@Id` with no `type`, and a relation with no target: declare the column as a builder (`f.string()`) and pass the target first (`@ManyToOne(() => Target)`). A branded string id's column, `f.uuid()` or `f.string()`, is yours to pick.
69
70
  - `Relation<T>` imported from `uql-orm`, which no longer exports it: write the property's type without it, and drop the import.
71
+ - A security filter it cannot read as data (a guard on another key, any other logic): declare it as a policy. A filter's `onMissing`, which no filter takes now: remove it.
70
72
 
71
73
  ## After it runs
72
74
 
@@ -0,0 +1,8 @@
1
+ import ts from 'typescript';
2
+ import type { Context } from './context.js';
3
+ /**
4
+ * `await client.findMany(...)`, which resolved to `{ data, count }` and now resolves to the value, as the pool's
5
+ * does: `(await ...).data` loses its `.data` (a `findManyAndCount`'s reads `[0]`, its `.count` `[1]`), `const { data: users } = await ...` becomes `const users = await ...`,
6
+ * and a `findManyAndCount`'s `{ data, count }` its `[data, count]`, a pair. Any other read of the result is reported.
7
+ */
8
+ export declare function rewriteClientAwait(node: ts.AwaitExpression, ctx: Context): void;
@@ -0,0 +1,76 @@
1
+ import ts from 'typescript';
2
+ import { original, replaced } from './edits.js';
3
+ /** The browser client's types: what each of its reads and writes once resolved to an envelope. */
4
+ const CLIENTS = new Set(['HttpQuerier', 'ClientQuerier']);
5
+ /** The method of uql's browser client `call` makes, `undefined` for any other call. */
6
+ function clientMethod(call, ctx) {
7
+ const callee = call.expression;
8
+ if (!ts.isPropertyAccessExpression(callee)) {
9
+ return undefined;
10
+ }
11
+ const declarations = ctx.checker.getSymbolAtLocation(callee.name)?.declarations ?? [];
12
+ if (!declarations.some((it) => it.getSourceFile().fileName.includes('/node_modules/uql-orm/'))) {
13
+ return undefined;
14
+ }
15
+ const receiver = ctx.checker.getTypeAtLocation(callee.expression);
16
+ const name = receiver.getSymbol()?.getName();
17
+ return name && CLIENTS.has(name) ? callee.name.text : undefined;
18
+ }
19
+ /** What each envelope key a result read reads now: the value itself, or where `findManyAndCount`'s pair holds it. */
20
+ const ENVELOPE = new Map([['data', '']]);
21
+ const PAIR = new Map([
22
+ ['data', '[0]'],
23
+ ['count', '[1]'],
24
+ ]);
25
+ /** `node` with the parentheses around it, the expression its parent reads. */
26
+ function outermost(node) {
27
+ return ts.isParenthesizedExpression(node.parent) ? outermost(node.parent) : node;
28
+ }
29
+ /** The binding of `key` in `pattern`, as `{ key }` or `{ key: local }` write it. */
30
+ function bindingOf(pattern, key) {
31
+ return pattern.elements.find((element) => (element.propertyName ?? element.name).getText() === key);
32
+ }
33
+ /**
34
+ * `await client.findMany(...)`, which resolved to `{ data, count }` and now resolves to the value, as the pool's
35
+ * does: `(await ...).data` loses its `.data` (a `findManyAndCount`'s reads `[0]`, its `.count` `[1]`), `const { data: users } = await ...` becomes `const users = await ...`,
36
+ * and a `findManyAndCount`'s `{ data, count }` its `[data, count]`, a pair. Any other read of the result is reported.
37
+ */
38
+ export function rewriteClientAwait(node, ctx) {
39
+ const call = node.expression;
40
+ const method = ts.isCallExpression(call) ? clientMethod(call, ctx) : undefined;
41
+ if (!method) {
42
+ return;
43
+ }
44
+ const pair = method === 'findManyAndCount';
45
+ const read = outermost(node);
46
+ const parent = read.parent;
47
+ // A result nobody reads, such as a delete's, changes nothing.
48
+ if (ts.isExpressionStatement(parent)) {
49
+ return;
50
+ }
51
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === read) {
52
+ const at = (pair ? PAIR : ENVELOPE).get(parent.name.text);
53
+ if (at !== undefined) {
54
+ ctx.edits.push(replaced(parent, [original(read), at]));
55
+ return;
56
+ }
57
+ }
58
+ if (ts.isVariableDeclaration(parent) && parent.initializer === read && ts.isObjectBindingPattern(parent.name)) {
59
+ const pattern = parent.name;
60
+ const data = bindingOf(pattern, 'data');
61
+ const count = bindingOf(pattern, 'count');
62
+ const bound = [data, count].filter(Boolean).length;
63
+ if (pair && bound && bound === pattern.elements.length) {
64
+ const rows = data ? [original(data.name)] : [];
65
+ const total = count ? [', ', original(count.name)] : [];
66
+ ctx.edits.push(replaced(pattern, ['[', ...rows, ...total, ']']));
67
+ return;
68
+ }
69
+ if (data && pattern.elements.length === 1 && !pair) {
70
+ ctx.edits.push(replaced(pattern, [original(data.name)]));
71
+ return;
72
+ }
73
+ }
74
+ ctx.report(node, `'${method}' answers the value now, not \`{ data, count }\`: read its result as it is` +
75
+ (pair ? ', `[rows, count]`' : ''));
76
+ }
package/dist/imports.js CHANGED
@@ -7,13 +7,34 @@ import { inserted, removeFromList, removeStatement, replaced } from './edits.js'
7
7
  */
8
8
  const REMOVED_EXPORTS = new Map([
9
9
  ['Relation', "write the property's type without it, and drop the import"],
10
- [
11
- 'setQuerierPool',
12
- 'pass the pool where it is used: `createFetchHandler({ pool, include })`, `querierMiddleware({ pool, include })`',
13
- ],
10
+ ['setQuerierPool', 'pass the pool where it is used: `createApi({ pool, include })`'],
14
11
  ['getQuerierPool', 'take the pool from the module that builds it, or from Nest DI'],
15
12
  ['getQuerier', 'use `pool.withQuerier(...)` / `pool.transaction(...)`, which release the connection'],
16
- ['ClientQuerierPool', "construct the `HttpQuerier` where it is used, `new HttpQuerier('/api')`"],
13
+ ['ClientQuerierPool', "build the client where it is used: `createClientQuerier(httpTransport('/api/v1'))`"],
14
+ [
15
+ 'HttpQuerier',
16
+ 'use `createClientQuerier(httpTransport(url, defaults))`, which answers what the pool answers: `rows`, not `{ data }`',
17
+ ],
18
+ ['HttpQuerierDefaults', '`httpTransport` takes `headers` and `readMethod`; `createClientQuerier` takes `entityPath`'],
19
+ ['createRequestHandler', 'build the API with `createApi(opts)`, then `toRequestHandler(api)`'],
20
+ [
21
+ 'createFetchHandler',
22
+ 'build the API with `createApi(opts)`, then `toFetchHandler(api)`, mounted on a catch-all under the base',
23
+ ],
24
+ ['querierMiddleware', 'build the API with `createApi(opts)`, then `toExpress(api)`'],
25
+ ['errorHandler', '`toExpress` answers every failure itself'],
26
+ ['RequestHandlerOptions', 'use `ApiOptions`'],
27
+ ['MiddlewareOptions', 'use `ApiOptions`'],
28
+ ...['RequestHook', 'RequestHookContext', 'ResponseHook'].map((name) => [
29
+ name,
30
+ 'write a middleware, `(call, context, next) => next(call)`, in `use` or `serve(Entity, { use })`',
31
+ ]),
32
+ ['RequestFindOptions', '`findManyAndCount` reads the count; a call takes `CallOptions`'],
33
+ ['RequestNotification', 'wrap the transport: `createClientQuerier((call, opts) => ...)`'],
34
+ ['RequestCallback', 'wrap the transport: `createClientQuerier((call, opts) => ...)`'],
35
+ ['WireFlags', "a call's `hardDelete` is a field of the `WireCall`; `findManyAndCount` is an op of its own"],
36
+ ...['RequestSuccessResponse', 'RequestCountedSuccessResponse', 'QuerierResult', 'QuerierCountedResult'].map((name) => [name, 'the client answers what the server does: the value, not an envelope']),
37
+ ...['CRUD_ROUTES', 'CrudRoute', 'HttpMethod'].map((name) => [name, 'a call is `POST {base}/:entity/:op`, a read also `GET {base}/:entity/:op?q=`: see `encodeCall`']),
17
38
  ['QueryWhereFieldMap', 'use `QueryWhere`'],
18
39
  ['QueryStreamProjected', 'use `QueryProjected`'],
19
40
  ['RelationMappedBy', "a 'mappedBy' is `(keys: KeyMap<E>) => Key<E>` now"],
@@ -116,8 +137,8 @@ const RENAMED_EXPORTS = new Map([
116
137
  ['UqlLockUsageError', { to: 'UqlUsageError' }],
117
138
  [LEGACY_SQL_TAG, { to: SQL_TAG }],
118
139
  [`uql-orm/util#${LEGACY_SQL_TAG}`, { to: SQL_TAG, from: 'uql-orm' }],
119
- ['uql-orm/http#Hook', { to: 'RequestHook' }],
120
- ['uql-orm/http#HookContext', { to: 'RequestHookContext' }],
140
+ ['uql-orm/http#CrudOperation', { to: 'ApiOp' }],
141
+ ['uql-orm/browser#RequestOptions', { to: 'CallOptions' }],
121
142
  ...UTIL_ROOT_EXPORTS.map((name) => [`uql-orm/util#${name}`, { to: name, from: 'uql-orm' }]),
122
143
  ]);
123
144
  /** What the root exported that is internal now, and what to write instead. */
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Each `security: true` filter that reads the context as data, as the `must` policy replacing it: in `@Entity`'s and
3
+ * `defineEntity`'s `filters`, a `.filters()` section becoming `.policies()`. Off the text the earlier passes wrote,
4
+ * so `@Filter` and `defineFilter` are folded in and every filter says `where`. Reports the rest, and an `onMissing`
5
+ * no filter takes now.
6
+ */
7
+ export declare function toPolicies(fileName: string, text: string, locate: (at: number) => string): {
8
+ readonly text: string;
9
+ readonly unresolved: readonly string[];
10
+ };
@@ -0,0 +1,192 @@
1
+ import ts from 'typescript';
2
+ import { formatFindings } from './context.js';
3
+ import { editedText, original, reparsedAgain } from './edits.js';
4
+ import { importEdits } from './imports.js';
5
+ import { isCallback, memberAccess } from './keyMaps.js';
6
+ import { chainOf, identifierText, isUndefined, namedProperty, objectLiteral, propertyKey, propertyValue, unwrapped, } from './syntax.js';
7
+ /** What a security filter states that its policy keeps (`where`, `ops`) or drops: any other leaves it to a human. */
8
+ const SECURITY_OPTIONS = new Set(['where', 'security', 'ops', 'onMissing', 'default']);
9
+ /**
10
+ * Each `security: true` filter that reads the context as data, as the `must` policy replacing it: in `@Entity`'s and
11
+ * `defineEntity`'s `filters`, a `.filters()` section becoming `.policies()`. Off the text the earlier passes wrote,
12
+ * so `@Filter` and `defineFilter` are folded in and every filter says `where`. Reports the rest, and an `onMissing`
13
+ * no filter takes now.
14
+ */
15
+ export function toPolicies(fileName, text, locate) {
16
+ if (!text.includes('security') && !text.includes('onMissing')) {
17
+ return { text, unresolved: [] };
18
+ }
19
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
20
+ const edits = [];
21
+ const findings = [];
22
+ const report = (node, message) => findings.push({ node, message });
23
+ const visit = (node) => {
24
+ const filters = filtersOf(node);
25
+ const split = filters && splitFilters(filters.literal, report);
26
+ if (filters && split && filters.policiesStated) {
27
+ report(node, 'move its security filters into the policies it states by hand');
28
+ }
29
+ else if (filters && split) {
30
+ edits.push(filters.write(split.kept, `[${split.policies.join(', ')}]`));
31
+ }
32
+ if (!filters) {
33
+ ts.forEachChild(node, visit);
34
+ }
35
+ };
36
+ visit(source);
37
+ const written = edits.length
38
+ ? reparsedAgain(fileName, editedText(text, edits), (edited) => importEdits(edited, new Set(['$context']), new Set())).text
39
+ : text;
40
+ return { text: written, unresolved: formatFindings(findings, locate) };
41
+ }
42
+ /** The filters `node` declares: an entity's `filters` option, or a `defineEntity(...).filters({ ... })` section. */
43
+ function filtersOf(node) {
44
+ if (ts.isPropertyAssignment(node) &&
45
+ ts.isObjectLiteralExpression(node.parent) &&
46
+ propertyKey(node.name) === 'filters') {
47
+ const literal = objectLiteral(node.initializer);
48
+ return (literal && {
49
+ literal,
50
+ policiesStated: namedProperty(node.parent, 'policies') !== undefined,
51
+ write: (kept, policies) => ({
52
+ start: node.getStart(),
53
+ end: node.getEnd(),
54
+ text: [...(kept.length ? ['filters: ', ...braced(kept), ', '] : []), `policies: ${policies}`],
55
+ }),
56
+ });
57
+ }
58
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) {
59
+ return undefined;
60
+ }
61
+ const { name } = node.expression;
62
+ const literal = name.text === 'filters' ? objectLiteral(node.arguments[0]) : undefined;
63
+ if (!literal) {
64
+ return undefined;
65
+ }
66
+ const { root, methods } = chainOf(node);
67
+ if (!ts.isCallExpression(root) || identifierText(root.expression) !== 'defineEntity') {
68
+ return undefined;
69
+ }
70
+ return {
71
+ literal,
72
+ policiesStated: methods.some((method) => method.name === 'policies'),
73
+ write: (kept, policies) => ({
74
+ start: name.getStart(),
75
+ end: node.getEnd(),
76
+ text: [...(kept.length ? ['filters(', ...braced(kept), ').'] : []), `policies(${policies})`],
77
+ }),
78
+ };
79
+ }
80
+ /**
81
+ * The filters `literal` keeps, and the policies its security filters become; `undefined` where none becomes one.
82
+ * Reports a security filter it cannot read as data, and an `onMissing` no filter takes now.
83
+ */
84
+ function splitFilters(literal, report) {
85
+ const kept = [];
86
+ const policies = [];
87
+ for (const prop of literal.properties) {
88
+ const options = ts.isPropertyAssignment(prop) ? objectLiteral(prop.initializer) : undefined;
89
+ const name = ts.isPropertyAssignment(prop) ? propertyKey(prop.name) : undefined;
90
+ const security = options && namedProperty(options, 'security') !== undefined;
91
+ const policy = security ? policyOf(options) : undefined;
92
+ if (policy) {
93
+ policies.push(policy);
94
+ continue;
95
+ }
96
+ if (security) {
97
+ report(prop, `security filter '${name}' is a policy now: declare it in the entity's 'policies', see https://uql-orm.dev/upgrade-guide`);
98
+ }
99
+ else if (options && namedProperty(options, 'onMissing')) {
100
+ report(prop, `filter '${name}' gives 'onMissing', which no filter takes now: one is skipped where the context lacks a key it reads, so remove it`);
101
+ }
102
+ kept.push(prop);
103
+ }
104
+ return policies.length ? { kept, policies } : undefined;
105
+ }
106
+ /** The `must` policy a security filter's options become, keeping their `ops`, where they read the context as data. */
107
+ function policyOf(filter) {
108
+ const where = propertyValue(filter, 'where');
109
+ const known = filter.properties.every((prop) => ts.isPropertyAssignment(prop) && SECURITY_OPTIONS.has(propertyKey(prop.name)));
110
+ const must = propertyValue(filter, 'security')?.kind === ts.SyntaxKind.TrueKeyword && known && where ? mustOf(where) : undefined;
111
+ const ops = propertyValue(filter, 'ops');
112
+ return must && `{ must: ${must}${ops ? `, ops: ${ops.getText()}` : ''} }`;
113
+ }
114
+ /**
115
+ * A security filter's `where` as a policy's: a literal as it is, and a callback each of whose fields reads a context
116
+ * key, `(ctx) => ({ companyId: ctx?.tenantId })`, where it tests only that those keys are there, as data.
117
+ */
118
+ function mustOf(where) {
119
+ if (ts.isObjectLiteralExpression(where)) {
120
+ return where.getText();
121
+ }
122
+ if (!isCallback(where) || where.parameters.length !== 1) {
123
+ return undefined;
124
+ }
125
+ const context = identifierText(where.parameters[0].name);
126
+ const body = returned(where.body);
127
+ if (!context || !body) {
128
+ return undefined;
129
+ }
130
+ const guarded = ts.isConditionalExpression(body) && isUndefined(body.whenFalse);
131
+ const scope = unwrapped(guarded ? body.whenTrue : body);
132
+ if (!ts.isObjectLiteralExpression(scope) || !scope.properties.length) {
133
+ return undefined;
134
+ }
135
+ const entries = scope.properties.map((prop) => {
136
+ if (!ts.isPropertyAssignment(prop)) {
137
+ return undefined;
138
+ }
139
+ const key = contextKey(prop.initializer, context);
140
+ return key && [prop.name.getText(), key];
141
+ });
142
+ if (!entries.every((entry) => entry !== undefined)) {
143
+ return undefined;
144
+ }
145
+ const keys = new Set(entries.map(([, key]) => key));
146
+ const tested = guarded ? presenceKeys(body.condition, context) : [];
147
+ if (!tested || !tested.every((key) => keys.has(key))) {
148
+ return undefined;
149
+ }
150
+ return `{ ${entries.map(([field, key]) => `${field}: ${memberAccess('$context', key)}`).join(', ')} }`;
151
+ }
152
+ /** What a function body returns: its expression, or a block's one `return`. */
153
+ function returned(body) {
154
+ if (!ts.isBlock(body)) {
155
+ return unwrapped(body);
156
+ }
157
+ const [statement, ...rest] = body.statements;
158
+ return statement && !rest.length && ts.isReturnStatement(statement) && statement.expression
159
+ ? unwrapped(statement.expression)
160
+ : undefined;
161
+ }
162
+ /** The context key `value` reads off `context`, `ctx.tenantId`, `ctx?.tenantId` or `ctx!.tenantId`. */
163
+ function contextKey(value, context) {
164
+ const access = unwrapped(value);
165
+ return ts.isPropertyAccessExpression(access) && identifierText(unwrapped(access.expression)) === context
166
+ ? access.name.text
167
+ : undefined;
168
+ }
169
+ /**
170
+ * The keys a condition tests are there, as `ctx?.tenantId`, `ctx?.tenantId != null` or `!== undefined`, joined by
171
+ * `&&`; `undefined` for a condition testing anything else.
172
+ */
173
+ function presenceKeys(condition, context) {
174
+ const test = unwrapped(condition);
175
+ if (!ts.isBinaryExpression(test)) {
176
+ const key = contextKey(test, context);
177
+ return key ? [key] : undefined;
178
+ }
179
+ const { operatorToken: op, left, right } = test;
180
+ if (op.kind === ts.SyntaxKind.AmpersandAmpersandToken) {
181
+ const [a, b] = [presenceKeys(left, context), presenceKeys(right, context)];
182
+ return a && b && [...a, ...b];
183
+ }
184
+ const absent = isUndefined(right) || right.kind === ts.SyntaxKind.NullKeyword;
185
+ const unequal = op.kind === ts.SyntaxKind.ExclamationEqualsToken || op.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken;
186
+ const key = absent && unequal ? contextKey(left, context) : undefined;
187
+ return key ? [key] : undefined;
188
+ }
189
+ /** `{ a, b }`, each property as it was written. */
190
+ function braced(props) {
191
+ return ['{ ', ...props.flatMap((prop, index) => [...(index ? [', '] : []), original(prop)]), ' }'];
192
+ }
package/dist/syntax.d.ts CHANGED
@@ -79,3 +79,7 @@ export declare const RELATION_DECORATORS: ReadonlySet<string | undefined>;
79
79
  export declare function lineStartOf(text: string, at: number): number;
80
80
  /** The whitespace the line holding `node` starts with. */
81
81
  export declare function indentOf(node: ts.Node): string;
82
+ /** `node` without the parentheses and `!` around it. */
83
+ export declare function unwrapped(node: ts.Expression): ts.Expression;
84
+ /** Whether `node` is `undefined`, as written or as `void 0`. */
85
+ export declare function isUndefined(node: ts.Expression): boolean;
package/dist/syntax.js CHANGED
@@ -199,3 +199,12 @@ export function indentOf(node) {
199
199
  const line = text.slice(lineStartOf(text, node.getStart()), node.getStart());
200
200
  return line.slice(0, line.length - line.trimStart().length);
201
201
  }
202
+ /** `node` without the parentheses and `!` around it. */
203
+ export function unwrapped(node) {
204
+ return ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node) ? unwrapped(node.expression) : node;
205
+ }
206
+ /** Whether `node` is `undefined`, as written or as `void 0`. */
207
+ export function isUndefined(node) {
208
+ const value = unwrapped(node);
209
+ return identifierText(value) === 'undefined' || ts.isVoidExpression(value);
210
+ }
package/dist/transform.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import ts from 'typescript';
2
2
  import { BUILDER_NAMES, isBuilder, toBuilders } from './builders.js';
3
3
  import { foldClassDecorators } from './classOptions.js';
4
+ import { rewriteClientAwait } from './clientCalls.js';
4
5
  import { rewriteColumnRefs } from './columnRefs.js';
5
6
  import { createContext, instanceTypeOf, locationAt, memberNames, ownerOf, } from './context.js';
6
7
  import { toDefinedEntities } from './definedEntity.js';
@@ -15,8 +16,9 @@ import { entityGetterTarget, fieldKeysEdits, isCallback, keyListEdits, mappedByE
15
16
  import { toMigrationBuilders } from './migrationBuilders.js';
16
17
  import { relationTargetFor } from './relationTarget.js';
17
18
  import { toRelationTargets } from './relationTargets.js';
19
+ import { toPolicies } from './securityFilters.js';
18
20
  import { statementTemplate } from './statementSql.js';
19
- import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, RELATION_DECORATORS, } from './syntax.js';
21
+ import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, RELATION_DECORATORS, isUndefined, } from './syntax.js';
20
22
  const TO_ONE_DECORATORS = new Set(['OneToOne', 'ManyToOne']);
21
23
  const TO_ONE_CARDINALITIES = new Set(['11', 'm1']);
22
24
  /**
@@ -208,6 +210,18 @@ function rewriteClassDecorators(node, ctx) {
208
210
  }
209
211
  }
210
212
  }
213
+ /** `UqlModule.forRoot({ getContext })`, and its async form, as `{ contextOf }`, which the NestJS module names it now. */
214
+ function rewriteModuleCall(call, ctx) {
215
+ const callee = call.expression;
216
+ const [options] = call.arguments;
217
+ if (!options ||
218
+ !ts.isPropertyAccessExpression(callee) ||
219
+ !['forRoot', 'forRootAsync'].includes(callee.name.text) ||
220
+ uqlExport(callee.expression, ctx.checker) !== 'UqlModule') {
221
+ return;
222
+ }
223
+ renameOption(optionsOf(options), 'getContext', 'contextOf', call, ctx);
224
+ }
211
225
  /**
212
226
  * Rewrites the imperative API the same way: `defineEntity(Post, { ... })`, `defineIndex(Post, { columns })`,
213
227
  * `defineRelation(Post, 'tag', { mappedBy, references })` and `defineFilter(Post, 'live', { condition })`.
@@ -480,9 +494,6 @@ function isWriteOptions(node, ctx) {
480
494
  .map((property) => property.name);
481
495
  return names.length > 0 && names.every((name) => name === 'returning');
482
496
  }
483
- function isUndefined(node) {
484
- return identifierText(node) === 'undefined';
485
- }
486
497
  /** The value of options holding `update` alone, `{ update: value }` or `{ update }`. */
487
498
  function upsertUpdate(options) {
488
499
  const literal = objectLiteral(options);
@@ -743,13 +754,13 @@ export function transformFile(source, checker, options = { strictNullChecks: tru
743
754
  const located = (pass) => (at) => locationAt(source, pass.sourceOffset(at));
744
755
  const builders = toBuilders(source.fileName, legacy.text, { locate: located(legacy), taken });
745
756
  const migrated = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
746
- const { unresolved } = migrated;
747
- const text = toRelationTargets(source.fileName, toGeneratedKeys(source.fileName, migrated.text));
757
+ const policies = toPolicies(source.fileName, migrated.text, located(followed(legacy, builders)));
758
+ const text = toRelationTargets(source.fileName, toGeneratedKeys(source.fileName, policies.text));
748
759
  return {
749
760
  fileName: source.fileName,
750
761
  text,
751
762
  changed: text !== source.getFullText(),
752
- unresolved: [...legacy.unresolved, ...builders.unresolved, ...unresolved],
763
+ unresolved: [...legacy.unresolved, ...builders.unresolved, ...migrated.unresolved, ...policies.unresolved],
753
764
  notes: legacy.notes,
754
765
  };
755
766
  }
@@ -778,6 +789,7 @@ export function rewriteLegacy(source, checker, options, taken = foreignNames(sou
778
789
  }
779
790
  if (ts.isCallExpression(node)) {
780
791
  rewriteDefineCall(node, ctx);
792
+ rewriteModuleCall(node, ctx);
781
793
  rewriteUpsertCall(node, ctx);
782
794
  if (importsUql) {
783
795
  rewriteBuilderCall(node, ctx);
@@ -790,6 +802,9 @@ export function rewriteLegacy(source, checker, options, taken = foreignNames(sou
790
802
  if (ts.isPropertyAssignment(node)) {
791
803
  rewriteStatementKeys(node, ctx);
792
804
  }
805
+ if (ts.isAwaitExpression(node)) {
806
+ rewriteClientAwait(node, ctx);
807
+ }
793
808
  if (importsUql && ts.isVariableDeclaration(node)) {
794
809
  rewriteUpsertResult(node, ctx);
795
810
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "uql-codemod",
3
3
  "description": "Upgrade uql-orm across versions that introduce breaking changes",
4
4
  "license": "MIT",
5
- "version": "0.55.0",
5
+ "version": "0.56.1",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=22.18"