uql-codemod 0.56.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,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
@@ -16,8 +16,9 @@ import { entityGetterTarget, fieldKeysEdits, isCallback, keyListEdits, mappedByE
16
16
  import { toMigrationBuilders } from './migrationBuilders.js';
17
17
  import { relationTargetFor } from './relationTarget.js';
18
18
  import { toRelationTargets } from './relationTargets.js';
19
+ import { toPolicies } from './securityFilters.js';
19
20
  import { statementTemplate } from './statementSql.js';
20
- 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';
21
22
  const TO_ONE_DECORATORS = new Set(['OneToOne', 'ManyToOne']);
22
23
  const TO_ONE_CARDINALITIES = new Set(['11', 'm1']);
23
24
  /**
@@ -493,9 +494,6 @@ function isWriteOptions(node, ctx) {
493
494
  .map((property) => property.name);
494
495
  return names.length > 0 && names.every((name) => name === 'returning');
495
496
  }
496
- function isUndefined(node) {
497
- return identifierText(node) === 'undefined';
498
- }
499
497
  /** The value of options holding `update` alone, `{ update: value }` or `{ update }`. */
500
498
  function upsertUpdate(options) {
501
499
  const literal = objectLiteral(options);
@@ -756,13 +754,13 @@ export function transformFile(source, checker, options = { strictNullChecks: tru
756
754
  const located = (pass) => (at) => locationAt(source, pass.sourceOffset(at));
757
755
  const builders = toBuilders(source.fileName, legacy.text, { locate: located(legacy), taken });
758
756
  const migrated = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
759
- const { unresolved } = migrated;
760
- 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));
761
759
  return {
762
760
  fileName: source.fileName,
763
761
  text,
764
762
  changed: text !== source.getFullText(),
765
- unresolved: [...legacy.unresolved, ...builders.unresolved, ...unresolved],
763
+ unresolved: [...legacy.unresolved, ...builders.unresolved, ...migrated.unresolved, ...policies.unresolved],
766
764
  notes: legacy.notes,
767
765
  };
768
766
  }
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.56.0",
5
+ "version": "0.56.1",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=22.18"