Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: code migration for useAsyncData #26862

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions packages/nuxt/schematics/migrations/4_0_0/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
import type { SchematicContext } from '@wandeljs/core'
import { Tree, UnitTestTree } from '@wandeljs/core'
import update from './index'

describe('Schematics Migration 4_0_0', () => {
let tree: Tree

beforeEach(() => {
tree = new UnitTestTree(Tree.empty())
})

it('should convert basic scenario successfully', () => {
const t = update(tree)
const file = fs.readFileSync(path.resolve(__dirname, './snapshots/basic/before.vue'))
tree.create('test.vue', file)
t(tree, {} as SchematicContext)
const content = tree.read('test.vue')
expect(content?.toString()).toMatchFileSnapshot('./snapshots/basic/after.vue')
})

it('should convert complex scenario successfully', () => {
const t = update(tree)
const file = fs.readFileSync(path.resolve(__dirname, './snapshots/complex/before.vue'))
tree.create('test.vue', file)
t(tree, {} as SchematicContext)
const content = tree.read('test.vue')
expect(content?.toString()).toMatchFileSnapshot('./snapshots/complex/after.vue')
})

it('should not make any changes if not necessary', () => {
const t = update(tree)
const file = fs.readFileSync(path.resolve(__dirname, './snapshots/no-edit/before.vue'))
tree.create('test.vue', file)
t(tree, {} as SchematicContext)
const content = tree.read('test.vue')
expect(content?.toString()).toMatchFileSnapshot('./snapshots/no-edit/after.vue')
})
})
94 changes: 94 additions & 0 deletions packages/nuxt/schematics/migrations/4_0_0/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import type { Rule, Tree } from '@wandeljs/core'
import type { Identifier, OptionalKind, VariableDeclarationStructure } from 'ts-morph'
import { Node, Project, SyntaxKind, VariableDeclarationKind } from 'ts-morph'

class ContentsStore {
private _project: Project = null!

collection: Array<{ path: string, content: string }> = []

get project () {
if (!this._project) {
this._project = new Project({ useInMemoryFileSystem: true, manipulationSettings: {
usePrefixAndSuffixTextForRename: true,
} })
}

return this._project
}

track (path: string, content: string) {
this.collection.push({ path, content })
this.project.createSourceFile(path, content, {})
}
}

export default function update (tree: Tree): Rule {
return migrateUseAsyncData(tree)
}

function migrateUseAsyncData (host: Tree): Rule {
return () => {
const contentsStore = new ContentsStore()
host.visit((file) => {
if (file.includes('.vue')) {
host.beginUpdate(file)
const content = host.read(file)?.toString()
if (content && content.includes('useAsyncData')) {
contentsStore.track(file, content)
}
}
})

for (const { path: sourcePath } of contentsStore.collection) {
const sourceFile = contentsStore.project.getSourceFile(sourcePath)
if (sourceFile) {
let statusDeclaration: OptionalKind<VariableDeclarationStructure> | undefined = undefined
sourceFile.forEachChild((node) => {
if (Node.isVariableStatement(node)) {
const structure = node.getStructure()
if (!statusDeclaration) {
statusDeclaration = structure.declarations.find(declaration => declaration.name.includes('status'))
}
const declaration = structure.declarations.find(declaration => declaration.initializer?.includes('useAsyncData') && declaration.name.includes('pending'))
if (declaration) {
const identifiers = node.getDescendantsOfKind(SyntaxKind.Identifier)
const identifier = identifiers.reduce((acc, identifier) => {
const name = identifier.getFullText().trim()
if (name === 'pending') {
return { ...acc, pending: identifier }
} else if (name !== 'pending' && (identifier.compilerNode.parent as any).propertyName?.getFullText().trim() === 'pending') {
return { ...acc, pendingAlias: identifier }
}
return { ...acc }
}, { pending: undefined, pendingAlias: undefined } as { pending: undefined | Identifier, pendingAlias: undefined | Identifier })
const statusName = statusDeclaration ? 'dataStatus' : 'status'
const startLineNumber = node.getStartLineNumber() + 1
const name = identifier.pendingAlias ? identifier.pendingAlias.getFullText().trim() : 'pending'
if (identifier.pendingAlias && identifier.pending) {
sourceFile.replaceText([identifier.pending.getPos(), identifier.pendingAlias.getEnd()], statusDeclaration ? 'status: dataStatus' : 'status')
} else {
identifier.pending?.replaceWithText('status')
}
sourceFile.insertVariableStatement(startLineNumber, {
isExported: false,
isDefaultExport: false,
hasDeclareKeyword: false,
declarationKind: VariableDeclarationKind.Const,
declarations: [
{
name,
initializer: `computed(() => ${statusName}.value === 'pending' || ${statusName}.value === 'idle')`,
hasExclamationToken: false,
},
],
})
}
}
})
host.overwrite(sourcePath, sourceFile.getFullText())
}
return host
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<script setup lang="ts">
const { data, status, error, refresh } = await useAsyncData(async () => {
// do something
});
const pending = computed(() => status.value === 'pending' || status.value === 'idle');

</script>

<template>
<div v-if="pending">
Waiting for data
</div>
<pre v-else>
{{ data }}
</pre>
</template>

<style scoped>
:root {
font-family: 'Inter var';
}
</style>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<script setup lang="ts">
const { data, pending, error, refresh } = await useAsyncData(async () => {
// do something
});
</script>

<template>
<div v-if="pending">
Waiting for data
</div>
<pre v-else>
{{ data }}
</pre>
</template>

<style scoped>
:root {
font-family: 'Inter var';
}
</style>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<script setup lang="ts">
const pending = 'something-else'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might also be worth handling the situation of:

Suggested change
const pending = 'something-else'
const status = 'something-else'
const pending = 'something-else'

const status = 'something-else'
const { data,status: dataStatus } = await useAsyncData(async () => {
// do something
});
const testididi = computed(() => dataStatus.value === 'pending' || dataStatus.value === 'idle');

</script>

<template>
<div v-if="testididi">
Waiting for data
</div>
<pre v-else>
{{ data }}
</pre>
</template>

<style scoped>
:root {
font-family: 'Inter var';
}
</style>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<script setup lang="ts">
const pending = 'something-else'
const status = 'something-else'
const { data, pending: testididi } = await useAsyncData(async () => {
// do something
})
</script>

<template>
<div v-if="testididi">
Waiting for data
</div>
<pre v-else>
{{ data }}
</pre>
</template>

<style scoped>
:root {
font-family: 'Inter var';
}
</style>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<script setup lang="ts">
const pending = 'something-else'
</script>

<template>
<div v-if="pending">
Waiting for data
</div>
</template>

<style scoped>
:root {
font-family: 'Inter var';
}
</style>



Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<script setup lang="ts">
const pending = 'something-else'
</script>

<template>
<div v-if="pending">
Waiting for data
</div>
</template>

<style scoped>
:root {
font-family: 'Inter var';
}
</style>



10 changes: 10 additions & 0 deletions packages/nuxt/schematics/migrations/migration.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"$schema": "../../node_modules/@wandeljs/core/collection-schema.json",
"schematics": {
"nuxt-v4": {
"description": "All you ever wanted from Nuxt 4",
"version": "0.0.1",
"factory": "./4_0_0/index"
}
}
}
26 changes: 26 additions & 0 deletions packages/nuxt/schematics/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "nuxt",
"version": "0.0.0",
"description": "A blank schematics",
"keywords": [
"schematics"
],
"license": "MIT",
"author": "",
"scripts": {
"build": "tsc -p tsconfig.json",
"test": "vitest ./**/*spec.ts"
},
"dependencies": {
"@wandeljs/core": "^0.1.9",
"typescript": "~5.4.2",
"ts-morph": "22.0.0"
},
"devDependencies": {
"@wandeljs/cli": "^0.1.9",
"@types/node": "^18.18.0"
},
"wandel": {
"migrations": "./migrations/migration.json"
}
}
23 changes: 23 additions & 0 deletions packages/nuxt/schematics/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need a separate tsconfig.json for this package?

"compilerOptions": {
"baseUrl": "tsconfig",
"lib": ["es2018", "dom"],
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"skipDefaultLibCheck": true,
"skipLibCheck": true,
"sourceMap": true,
"strictNullChecks": true,
"target": "es6",
"types": ["vitest/globals", "node"]
},
"include": ["src/**/*", "migrations/**/*"],
"exclude": ["src/*/files/**/*"]
}
8 changes: 8 additions & 0 deletions packages/nuxt/schematics/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config'

export default defineConfig({
test: {
exclude: [],
globals: true,
},
})