uql-codemod 0.54.0 → 0.55.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.
package/README.md CHANGED
@@ -26,12 +26,13 @@ Only `--flag=value` is read, and anything unrecognised is an error. It exits `0`
26
26
 
27
27
  - `virtual` to `computed` (on `@Field` and in `defineEntity`'s `fields`), a check's `expression` and a filter's `condition` to `where` (`@Entity`, `defineEntity`, `@Filter`), `raw('...')` to the `sql` tagged template, and a second argument onto `.as()`.
28
28
  - A column's options to its builder, last, after the rewrites above: `@Id()` and `@Field({ type: String, nullable: true, length: 80 })` to `@Field(f.number().autoIncrement())` and `@Field(f.string().nullable().length(80))`, a NOT NULL column losing its `nullable: false`, `computed` to `@Computed((row) => f.string().as(...))` or `@Computed((row) => row.books.count())`, and a defined entity's `fields` likewise; its other options to the sections chained after it, and its `aggregates` to `.relations()`' second callback. A defined column's foreign key becomes a relation: its `references` is dropped where a relation joins on the column (by `(order) => order.customerId`, by `[{ local, foreign }]` pairs, or as the ORM infers the one column naming its target, written into it), its `onDelete` moved into that relation, and where none joins, a `manyToOne` named as the column less its `Id` is written for it: `customer: () => rel.manyToOne(Customer, { references: (order) => order.customerId })`. Then each index, check and trigger entry, in `@Entity` and `defineEntity`, goes to the helper its callback is handed: `(post, index) => [index([post.title], 'by_title')]`.
29
+ - A relation decorator's target first, as `defineEntity`'s `rel.*` take it: `@ManyToOne({ entity: () => User, references })` to `@ManyToOne(() => User, { references })`, and `@OneToMany({ entity: () => Post })` to `@OneToMany(() => Post)`, last, after the rewrites reading its options.
29
30
  - A migration's columns to the same methods: `table.string('email', { length: 80, nullable: true })` to `table.string('email').length(80).nullable()`, `.defaultValue()` to `.default()`, `.primaryKey()` to `.id()`, `.computed()` to `.as()`, and `.notNullable()` dropped.
30
31
  - `@Index`, `@Trigger` and `@Filter` into `@Entity`'s `indexes`, `triggers` and `filters`, each decorator's comments kept above its entry; a class with no `@Entity` becomes `@Entity({ abstract: true, ... })`, a base that is never a table.
31
32
  - Members named by string to callbacks: `mappedBy: 'author'` to `(post) => post.author`, and `include`, `references` and `@Entity`/`defineEntity`'s `indexes` and `hooks` likewise: `{ columns: (post) => [post.title] }`.
32
33
  - `references: (post) => post.authorId` on a to-one (`@ManyToOne`, `@OneToOne`, or in `defineEntity`) that names no foreign key, declaring `@Field({ references: () => User }) authorId` first on a decorated class that has no such column, typed as the key it points at.
33
34
  - A partial-index `where` string to `sql`, importing it, on entities and in the migration builder.
34
- - A class registered with `defineEntity(Post, { ... })` to the `defineEntity({ ... })` call it stands for, whole or not at all: `export const Post = defineEntity({ name: 'Post', fields })` with its sections chained, as a defined entity's options are above, and `export type Post = InstanceType<typeof Post>`. The class is removed and a table it named kept as `table`; a field stating no `type` takes the one its property declares (`authorId?: number | null` is `f.number().nullable()`), each relation becomes `author: () => rel.manyToOne(User, { ... })`, a relation aggregate an aggregate field (`(post) => ({ total: () => post.comments.count() })`), a hook's method a function of the row (`this` read as the row), and the same class's `defineField`, `defineId`, `defineRelation`, `defineHook`, `defineIndex`, `defineTrigger` and `defineFilter` are folded in.
35
+ - A class registered with `defineEntity(Post, { ... })` to the `defineEntity({ ... })` call it stands for, whole or not at all: `export const Post = defineEntity({ name: 'Post', fields })` with its sections chained, as a defined entity's options are above, and `export interface Post extends InstanceType<typeof Post> {}`. The class is removed and a table it named kept as `table`; a field stating no `type` takes the one its property declares (`authorId?: number | null` is `f.number().nullable()`), each relation becomes `author: () => rel.manyToOne(User, { ... })`, a relation aggregate an aggregate field (`(post) => ({ total: () => post.comments.count() })`), a hook's method a function of the row (`this` read as the row), and the same class's `defineField`, `defineId`, `defineRelation`, `defineHook`, `defineIndex`, `defineTrigger` and `defineFilter` are folded in.
35
36
  - A JSON index entry to the path read off the column's ref: `{ column: post.kind, jsonPath: { path: 'theme', type: Number } }` to `{ column: post.kind.theme, type: Number }`, and a `jsonArray`'s element type to `type: [String]`.
36
37
  - `col('cost')` to the ref it names, ``(product) => sql`${product.cost}` `` in a `computed` and `refs(Item).cost` in a statement, and `$lock: { wait: 'skip' }` to `{ $wait: 'skip' }`, or to `true` for `{}` and a `'block'` wait.
37
38
  - `$exclude` to a `$select` leaving its fields out: `$exclude: { password: true }` to `$select: { password: false }`, at every depth of `$populate`.
@@ -64,7 +65,7 @@ Reported with what to do, never guessed:
64
65
  - A file that already names something the codemod would write (`sql`, `refs`, `idKey`, `f`, a renamed export): left unchanged and reported, since the new import would shadow it or be shadowed.
65
66
  - A property whose type maps to no column (`Json<T>`, a vector, a mixed union).
66
67
  - 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.
67
- - A `@Field`/`@Id` with no `type`, and a relation with no `entity`: declare the column as a builder (`f.string()`) and name the target (`entity: () => Target`). A branded string id's column, `f.uuid()` or `f.string()`, is yours to pick.
68
+ - 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.
68
69
  - `Relation<T>` imported from `uql-orm`, which no longer exports it: write the property's type without it, and drop the import.
69
70
 
70
71
  ## After it runs
@@ -263,7 +263,7 @@ function definedOf(name, cls, calls, entityCall, unit) {
263
263
  }
264
264
  const prefix = exported ? 'export ' : '';
265
265
  return {
266
- text: `${prefix}const ${name} = defineEntity({\n${lines.map((line) => `${unit}${line},`).join('\n')}\n});\n${prefix}type ${name} = InstanceType<typeof ${name}>;`,
266
+ text: `${prefix}const ${name} = defineEntity({\n${lines.map((line) => `${unit}${line},`).join('\n')}\n});\n${prefix}interface ${name} extends InstanceType<typeof ${name}> {}`,
267
267
  notes,
268
268
  };
269
269
  }
package/dist/edits.d.ts CHANGED
@@ -39,14 +39,15 @@ export declare function reparsedAgain(fileName: string, pass: Pass, edits: (sour
39
39
  */
40
40
  export declare function editedText(source: string, edits: readonly Edit[]): Pass;
41
41
  export declare function replaced(node: ts.Node, text: Replacement): Edit;
42
- export declare function inserted(node: ts.Node, text: string): Edit;
42
+ export declare function inserted(node: ts.Node, text: Replacement): Edit;
43
43
  export declare function appended(node: ts.Node, text: string): Edit;
44
44
  /** `node`'s text with each of `uses`, the nodes inside it, written as `text`. */
45
45
  export declare function replacingUses(node: ts.Node, uses: readonly ts.Node[], text: string): string;
46
46
  /**
47
47
  * Removes elements of a comma-separated list, at least one of them kept, with the separators that would dangle.
48
- * Each removed element takes the text up to the next item; the removed run at the end takes the separator before
49
- * it, so the ranges never overlap. `source` is passed because a tree from `ts.parseJsonText` has no `getStart()`.
48
+ * Each removed element takes the text up to the next item, short of that item's comments; the removed run at the end
49
+ * takes the separator before it, so the ranges never overlap. `source` is passed because a tree from
50
+ * `ts.parseJsonText` has no `getStart()`.
50
51
  */
51
52
  export declare function removeFromList(items: readonly ts.Node[], removed: readonly ts.Node[], source: ts.SourceFile): readonly Edit[];
52
53
  /**
package/dist/edits.js CHANGED
@@ -92,15 +92,19 @@ export function replacingUses(node, uses, text) {
92
92
  }
93
93
  /**
94
94
  * Removes elements of a comma-separated list, at least one of them kept, with the separators that would dangle.
95
- * Each removed element takes the text up to the next item; the removed run at the end takes the separator before
96
- * it, so the ranges never overlap. `source` is passed because a tree from `ts.parseJsonText` has no `getStart()`.
95
+ * Each removed element takes the text up to the next item, short of that item's comments; the removed run at the end
96
+ * takes the separator before it, so the ranges never overlap. `source` is passed because a tree from
97
+ * `ts.parseJsonText` has no `getStart()`.
97
98
  */
98
99
  export function removeFromList(items, removed, source) {
99
100
  const kept = items.map((item) => !removed.includes(item));
100
101
  const lastKept = kept.lastIndexOf(true);
102
+ const upTo = (item, next) => ts.getLeadingCommentRanges(source.text, next.pos)?.length
103
+ ? { start: item.pos, end: next.pos }
104
+ : { start: item.getStart(source), end: next.getStart(source) };
101
105
  const between = items
102
106
  .slice(0, lastKept + 1)
103
- .flatMap((item, at) => kept[at] ? [] : [{ start: item.getStart(source), end: items[at + 1].getStart(source), text: '' }]);
107
+ .flatMap((item, at) => (kept[at] ? [] : [{ ...upTo(item, items[at + 1]), text: '' }]));
104
108
  const trailing = items.slice(lastKept + 1);
105
109
  if (!trailing.length) {
106
110
  return between;
@@ -0,0 +1,2 @@
1
+ /** Passes each relation decorator's target first, as `defineEntity`'s `rel.*` take it. Off the text the other passes wrote. */
2
+ export declare function toRelationTargets(fileName: string, text: string): string;
@@ -0,0 +1,31 @@
1
+ import ts from 'typescript';
2
+ import { applyEdits, inserted, original, removeFromList, replaced } from './edits.js';
3
+ import { decoratorName, namedProperty, RELATION_DECORATORS } from './syntax.js';
4
+ /** `@ManyToOne(() => User, { references })` from `@ManyToOne({ entity: () => User, references })`, the rest kept as written. */
5
+ function targetFirst(options) {
6
+ const entity = namedProperty(options, 'entity');
7
+ if (!entity)
8
+ return [];
9
+ const target = original(ts.isPropertyAssignment(entity) ? entity.initializer : entity.name);
10
+ if (options.properties.length === 1)
11
+ return [replaced(options, [target])];
12
+ return [inserted(options, [target, ', ']), ...removeFromList(options.properties, [entity], options.getSourceFile())];
13
+ }
14
+ /** Passes each relation decorator's target first, as `defineEntity`'s `rel.*` take it. Off the text the other passes wrote. */
15
+ export function toRelationTargets(fileName, text) {
16
+ if (!/@(?:OneToOne|ManyToOne|OneToMany|ManyToMany)\(\s*\{/.test(text))
17
+ return text;
18
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
19
+ const edits = [];
20
+ const visit = (node) => {
21
+ if (ts.isDecorator(node) && ts.isCallExpression(node.expression) && RELATION_DECORATORS.has(decoratorName(node))) {
22
+ const [options, ...rest] = node.expression.arguments;
23
+ if (options && !rest.length && ts.isObjectLiteralExpression(options)) {
24
+ edits.push(...targetFirst(options));
25
+ }
26
+ }
27
+ ts.forEachChild(node, visit);
28
+ };
29
+ visit(source);
30
+ return applyEdits(text, edits);
31
+ }
package/dist/syntax.d.ts CHANGED
@@ -74,6 +74,7 @@ export declare function decoratorsOf(node: ts.Node): readonly ts.Decorator[];
74
74
  export declare function decoratorName(node: ts.Decorator): string | undefined;
75
75
  /** The decorators declaring a field: `@Field`, and `@Id` for the key the class names. */
76
76
  export declare const FIELD_DECORATORS: ReadonlySet<string | undefined>;
77
+ export declare const RELATION_DECORATORS: ReadonlySet<string | undefined>;
77
78
  /** Where the line holding offset `at` of `text` starts. */
78
79
  export declare function lineStartOf(text: string, at: number): number;
79
80
  /** The whitespace the line holding `node` starts with. */
package/dist/syntax.js CHANGED
@@ -183,6 +183,12 @@ export function decoratorName(node) {
183
183
  }
184
184
  /** The decorators declaring a field: `@Field`, and `@Id` for the key the class names. */
185
185
  export const FIELD_DECORATORS = new Set(['Field', 'Id']);
186
+ export const RELATION_DECORATORS = new Set([
187
+ 'OneToOne',
188
+ 'ManyToOne',
189
+ 'OneToMany',
190
+ 'ManyToMany',
191
+ ]);
186
192
  /** Where the line holding offset `at` of `text` starts. */
187
193
  export function lineStartOf(text, at) {
188
194
  return text.lastIndexOf('\n', at - 1) + 1;
package/dist/transform.js CHANGED
@@ -14,9 +14,9 @@ import { rewriteBuilderIndexLengths, rewriteJsonIndexEntries } from './jsonIndex
14
14
  import { entityGetterTarget, fieldKeysEdits, isCallback, keyListEdits, mappedByEdits, memberAccess, paramFor, quoted, referencesEdits, } from './keyMaps.js';
15
15
  import { toMigrationBuilders } from './migrationBuilders.js';
16
16
  import { relationTargetFor } from './relationTarget.js';
17
+ import { toRelationTargets } from './relationTargets.js';
17
18
  import { statementTemplate } from './statementSql.js';
18
- import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, } from './syntax.js';
19
- const RELATION_DECORATORS = new Set(['OneToOne', 'ManyToOne', 'OneToMany', 'ManyToMany']);
19
+ import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, RELATION_DECORATORS, } from './syntax.js';
20
20
  const TO_ONE_DECORATORS = new Set(['OneToOne', 'ManyToOne']);
21
21
  const TO_ONE_CARDINALITIES = new Set(['11', 'm1']);
22
22
  /**
@@ -634,24 +634,34 @@ function rewriteProperty(node, ctx) {
634
634
  renameSqlOption(options, 'virtual', 'computed', node, owner, ctx);
635
635
  }
636
636
  if (RELATION_DECORATORS.has(name)) {
637
- reportMissingOption(decorator, node, ctx, {
638
- option: 'entity',
639
- satisfiedBy: ['entity'],
640
- advice: 'name its target, `entity: () => Target`',
641
- });
642
- if (options.kind === 'literal') {
643
- const target = relationTargetFor(ctx.checker.getTypeAtLocation(node), ctx.checker);
644
- rewriteRelationOptions(options.node, owner.param, ctx, paramFor(target));
645
- }
646
- if (options.kind === 'literal' && TO_ONE_DECORATORS.has(name)) {
647
- addForeignKeyReference(options.node, propertyKey(node.name), owner, ctx, node);
648
- }
637
+ rewriteRelation(decorator, name, node, owner, ctx);
649
638
  }
650
639
  }
651
640
  if (decorators.length) {
652
641
  dropDeclare(node, ctx);
653
642
  }
654
643
  }
644
+ /** A relation decorator holding its target as `entity`, which a later pass moves first; one passing it first is current. */
645
+ function rewriteRelation(decorator, name, node, owner, ctx) {
646
+ const [first] = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
647
+ if (first && isCallback(first)) {
648
+ return;
649
+ }
650
+ reportMissingOption(decorator, node, ctx, {
651
+ option: 'entity',
652
+ satisfiedBy: ['entity'],
653
+ advice: 'pass its target first, `@ManyToOne(() => Target)`',
654
+ });
655
+ const options = decoratorOptions(decorator);
656
+ if (options.kind !== 'literal') {
657
+ return;
658
+ }
659
+ const target = relationTargetFor(ctx.checker.getTypeAtLocation(node), ctx.checker);
660
+ rewriteRelationOptions(options.node, owner.param, ctx, paramFor(target));
661
+ if (TO_ONE_DECORATORS.has(name)) {
662
+ addForeignKeyReference(options.node, propertyKey(node.name), owner, ctx, node);
663
+ }
664
+ }
655
665
  /** Whether a field decorator already declares its column with a builder, which states everything the rewrites add. */
656
666
  function writesBuilder(decorator) {
657
667
  const [first] = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
@@ -734,7 +744,7 @@ export function transformFile(source, checker, options = { strictNullChecks: tru
734
744
  const builders = toBuilders(source.fileName, legacy.text, { locate: located(legacy), taken });
735
745
  const migrated = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
736
746
  const { unresolved } = migrated;
737
- const text = toGeneratedKeys(source.fileName, migrated.text);
747
+ const text = toRelationTargets(source.fileName, toGeneratedKeys(source.fileName, migrated.text));
738
748
  return {
739
749
  fileName: source.fileName,
740
750
  text,
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.54.0",
5
+ "version": "0.55.0",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=22.18"