Compare commits
46 Commits
@blitzjs/g
...
@blitzjs/a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c096891bf0 | ||
|
|
81b4b41a99 | ||
|
|
e8271d579c | ||
|
|
9e798b152b | ||
|
|
3c6f43a11d | ||
|
|
8107138e2f | ||
|
|
8cb1134d94 | ||
|
|
2073714f8d | ||
|
|
9631c45833 | ||
|
|
2150dcc3e7 | ||
|
|
63605961b4 | ||
|
|
d711948809 | ||
|
|
1f6b0b54c2 | ||
|
|
4603a2b7bd | ||
|
|
01f3a03ea9 | ||
|
|
36e26193b7 | ||
|
|
4a9aa9f7ff | ||
|
|
1e1bb73b2d | ||
|
|
99205f52d5 | ||
|
|
d03a1165d7 | ||
|
|
d87288a2e9 | ||
|
|
fdff45a592 | ||
|
|
469f55a429 | ||
|
|
e6c31704ed | ||
|
|
35a070ad7d | ||
|
|
9674efc0bf | ||
|
|
666a3ae3e6 | ||
|
|
c9cf7adc33 | ||
|
|
f4c2234c4d | ||
|
|
82916b21c2 | ||
|
|
bf1b2c8244 | ||
|
|
043c3498d0 | ||
|
|
a2ebdbe7d6 | ||
|
|
de4e8084ef | ||
|
|
bb9eaed520 | ||
|
|
ffe85b5ab6 | ||
|
|
6edeed7c5a | ||
|
|
1d9d890d9c | ||
|
|
b8f51a2354 | ||
|
|
6552b11b94 | ||
|
|
d1dd2bc56e | ||
|
|
09b732860d | ||
|
|
ccb6cfd2a0 | ||
|
|
502b8f7820 | ||
|
|
3888d7018a | ||
|
|
02f7822437 |
7
.changeset/breezy-cameras-double.md
Normal file
7
.changeset/breezy-cameras-double.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/next": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
Fix codegen and postinstall to make work with pnpm
|
||||
6
.changeset/dirty-monkeys-greet.md
Normal file
6
.changeset/dirty-monkeys-greet.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
Use alpha version for blitz dependency, fix package manager selection
|
||||
5
.changeset/empty-berries-rule.md
Normal file
5
.changeset/empty-berries-rule.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix app generator for pnpm unmet dependency
|
||||
5
.changeset/fair-wombats-sneeze.md
Normal file
5
.changeset/fair-wombats-sneeze.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
added superjson
|
||||
5
.changeset/flat-bees-approve.md
Normal file
5
.changeset/flat-bees-approve.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
set default enviornment variable to development unless build and start command
|
||||
9
.changeset/great-months-train.md
Normal file
9
.changeset/great-months-train.md
Normal file
@@ -0,0 +1,9 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/next": patch
|
||||
"@blitzjs/auth": patch
|
||||
"@blitzjs/rpc": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix route manifest codegen
|
||||
5
.changeset/lovely-colts-share.md
Normal file
5
.changeset/lovely-colts-share.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
fix broken cli versioning
|
||||
5
.changeset/nice-starfishes-live.md
Normal file
5
.changeset/nice-starfishes-live.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
add mounted check to app generator template
|
||||
5
.changeset/poor-shrimps-think.md
Normal file
5
.changeset/poor-shrimps-think.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
Setup SuperJson for GSSP and GSP
|
||||
@@ -16,10 +16,28 @@
|
||||
"toolkit-app": "1.0.0"
|
||||
},
|
||||
"changesets": [
|
||||
"breezy-cameras-double",
|
||||
"dirty-monkeys-greet",
|
||||
"empty-berries-rule",
|
||||
"fair-wombats-sneeze",
|
||||
"flat-bees-approve",
|
||||
"great-months-train",
|
||||
"lovely-colts-share",
|
||||
"nine-onions-admire",
|
||||
"ninety-pets-heal",
|
||||
"poor-peas-lick",
|
||||
"poor-shrimps-think",
|
||||
"quiet-feet-travel",
|
||||
"sharp-falcons-begin",
|
||||
"silent-colts-reply",
|
||||
"stupid-walls-sell",
|
||||
"swift-drinks-dress",
|
||||
"ten-rivers-burn",
|
||||
"twenty-beans-pump"
|
||||
"thirty-countries-build",
|
||||
"twenty-beans-pump",
|
||||
"two-kiwis-help",
|
||||
"unlucky-papayas-sleep",
|
||||
"wicked-ghosts-cough",
|
||||
"wise-frogs-give"
|
||||
]
|
||||
}
|
||||
|
||||
5
.changeset/quiet-feet-travel.md
Normal file
5
.changeset/quiet-feet-travel.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix source path for templates
|
||||
5
.changeset/sharp-falcons-begin.md
Normal file
5
.changeset/sharp-falcons-begin.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
Use routes manifest in template app
|
||||
5
.changeset/silent-colts-reply.md
Normal file
5
.changeset/silent-colts-reply.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
added index.cjs to blitz externals
|
||||
8
.changeset/stupid-walls-sell.md
Normal file
8
.changeset/stupid-walls-sell.md
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/auth": patch
|
||||
"@blitzjs/next": patch
|
||||
"@blitzjs/rpc": patch
|
||||
---
|
||||
|
||||
testing set dist-tag
|
||||
5
.changeset/swift-drinks-dress.md
Normal file
5
.changeset/swift-drinks-dress.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
Fix postinstall script not being found
|
||||
5
.changeset/thirty-countries-build.md
Normal file
5
.changeset/thirty-countries-build.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
add @blitzjs/generator as external
|
||||
5
.changeset/two-kiwis-help.md
Normal file
5
.changeset/two-kiwis-help.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
fix generate cli command
|
||||
5
.changeset/unlucky-papayas-sleep.md
Normal file
5
.changeset/unlucky-papayas-sleep.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
remove console logs inside onPostInstall in the new cli command
|
||||
5
.changeset/wicked-ghosts-cough.md
Normal file
5
.changeset/wicked-ghosts-cough.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
fix template sourcepath because of new env variable
|
||||
5
.changeset/wise-frogs-give.md
Normal file
5
.changeset/wise-frogs-give.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
use latest tag for generator template on rpc & auth packages
|
||||
37
.github/workflows/release.yml
vendored
Normal file
37
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Setup Node.js 16.x
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: 16.x
|
||||
|
||||
- name: Pre-publish
|
||||
uses: pnpm/action-setup@646cdf48217256a3d0b80361c5a50727664284f2
|
||||
with:
|
||||
version: 6.32.6
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm changeset version
|
||||
- run: pnpm build
|
||||
|
||||
- name: Create Release Pull Request
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
publish: pnpm changeset publish
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -62,6 +62,7 @@ examples/auth2
|
||||
.idea
|
||||
.ultra.cache.json
|
||||
db.sqlite-journal
|
||||
**/db/db.sqlite
|
||||
test/integration/**/db.json
|
||||
test/**/*/out
|
||||
test/**/blitz-env.d.ts
|
||||
|
||||
@@ -174,6 +174,7 @@ Your financial contributions help ensure Blitz continues to be developed and mai
|
||||
<tr>
|
||||
<td align="center"><a href="https://twitter.com/flybayer"><img src="https://avatars3.githubusercontent.com/u/8813276?v=4" width="100px;" alt=""/><br /><sub><b>Brandon Bayer</b></sub></a><br />Creator</td>
|
||||
<td align="center"><a href="http://aleksandra.codes"><img src="https://avatars.githubusercontent.com/u/9019397?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aleksandra Sikora</b></sub></a><br />Lead Maintainer</td>
|
||||
<td align="center"><a href="http://twitter.com/dillonraphael"><img src="https://avatars.githubusercontent.com/u/3496193?v=4" width="100px;" alt=""/><br /><sub><b>Dillon Raphael</b></sub></a><br />Senior Maintainer</td>
|
||||
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -1 +1 @@
|
||||
module.exports = require("@blitzjs/config/eslint")
|
||||
module.exports = require("@blitzjs/next/eslint")
|
||||
|
||||
@@ -1,5 +1,178 @@
|
||||
# toolkit-app
|
||||
|
||||
## 1.0.1-alpha.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.21
|
||||
- @blitzjs/auth@2.0.0-alpha.21
|
||||
- @blitzjs/next@2.0.0-alpha.21
|
||||
- @blitzjs/rpc@2.0.0-alpha.21
|
||||
- @blitzjs/config@2.0.0-alpha.21
|
||||
|
||||
## 1.0.1-alpha.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.20
|
||||
- @blitzjs/auth@2.0.0-alpha.20
|
||||
- @blitzjs/next@2.0.0-alpha.20
|
||||
- @blitzjs/rpc@2.0.0-alpha.20
|
||||
- @blitzjs/config@2.0.0-alpha.20
|
||||
|
||||
## 1.0.1-alpha.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- Updated dependencies [2150dcc3]
|
||||
- @blitzjs/next@2.0.0-alpha.19
|
||||
- blitz@2.0.0-alpha.19
|
||||
- @blitzjs/auth@2.0.0-alpha.19
|
||||
- @blitzjs/rpc@2.0.0-alpha.19
|
||||
- @blitzjs/config@2.0.0-alpha.19
|
||||
|
||||
## 1.0.1-alpha.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.18
|
||||
- @blitzjs/auth@2.0.0-alpha.18
|
||||
- @blitzjs/next@2.0.0-alpha.18
|
||||
- @blitzjs/rpc@2.0.0-alpha.18
|
||||
- @blitzjs/config@2.0.0-alpha.18
|
||||
|
||||
## 1.0.1-alpha.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.17
|
||||
- @blitzjs/auth@2.0.0-alpha.17
|
||||
- @blitzjs/next@2.0.0-alpha.17
|
||||
- @blitzjs/rpc@2.0.0-alpha.17
|
||||
- @blitzjs/config@2.0.0-alpha.17
|
||||
|
||||
## 1.0.1-alpha.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.16
|
||||
- @blitzjs/auth@2.0.0-alpha.16
|
||||
- @blitzjs/next@2.0.0-alpha.16
|
||||
- @blitzjs/rpc@2.0.0-alpha.16
|
||||
- @blitzjs/config@2.0.0-alpha.16
|
||||
|
||||
## 1.0.1-alpha.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.15
|
||||
- @blitzjs/auth@2.0.0-alpha.15
|
||||
- @blitzjs/next@2.0.0-alpha.15
|
||||
- @blitzjs/rpc@2.0.0-alpha.15
|
||||
- @blitzjs/config@2.0.0-alpha.15
|
||||
|
||||
## 1.0.1-alpha.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.14
|
||||
- @blitzjs/auth@2.0.0-alpha.14
|
||||
- @blitzjs/next@2.0.0-alpha.14
|
||||
- @blitzjs/rpc@2.0.0-alpha.14
|
||||
- @blitzjs/config@2.0.0-alpha.14
|
||||
|
||||
## 1.0.1-alpha.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.13
|
||||
- @blitzjs/next@2.0.0-alpha.13
|
||||
- @blitzjs/auth@2.0.0-alpha.13
|
||||
- @blitzjs/rpc@2.0.0-alpha.13
|
||||
- @blitzjs/config@2.0.0-alpha.13
|
||||
|
||||
## 1.0.1-alpha.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.12
|
||||
- @blitzjs/auth@2.0.0-alpha.12
|
||||
- @blitzjs/next@2.0.0-alpha.12
|
||||
- @blitzjs/rpc@2.0.0-alpha.12
|
||||
- @blitzjs/config@2.0.0-alpha.12
|
||||
|
||||
## 1.0.1-alpha.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/next@2.0.0-alpha.11
|
||||
- @blitzjs/auth@2.0.0-alpha.11
|
||||
- @blitzjs/rpc@2.0.0-alpha.11
|
||||
- @blitzjs/config@2.0.0-alpha.11
|
||||
- blitz@2.0.0-alpha.11
|
||||
|
||||
## 1.0.1-alpha.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.10
|
||||
- @blitzjs/auth@2.0.0-alpha.10
|
||||
- @blitzjs/next@2.0.0-alpha.10
|
||||
- @blitzjs/rpc@2.0.0-alpha.10
|
||||
- @blitzjs/config@2.0.0-alpha.10
|
||||
|
||||
## 1.0.1-alpha.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.9
|
||||
- @blitzjs/auth@2.0.0-alpha.9
|
||||
- @blitzjs/next@2.0.0-alpha.9
|
||||
- @blitzjs/rpc@2.0.0-alpha.9
|
||||
- @blitzjs/config@2.0.0-alpha.9
|
||||
|
||||
## 1.0.1-alpha.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.8
|
||||
- @blitzjs/auth@2.0.0-alpha.8
|
||||
- @blitzjs/next@2.0.0-alpha.8
|
||||
- @blitzjs/rpc@2.0.0-alpha.8
|
||||
- @blitzjs/config@2.0.0-alpha.8
|
||||
|
||||
## 1.0.1-alpha.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.7
|
||||
- @blitzjs/auth@2.0.0-alpha.7
|
||||
- @blitzjs/next@2.0.0-alpha.7
|
||||
- @blitzjs/rpc@2.0.0-alpha.7
|
||||
- @blitzjs/config@2.0.0-alpha.7
|
||||
|
||||
## 1.0.1-alpha.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/next@2.0.0-alpha.6
|
||||
- blitz@2.0.0-alpha.6
|
||||
- @blitzjs/auth@2.0.0-alpha.6
|
||||
- @blitzjs/rpc@2.0.0-alpha.6
|
||||
- @blitzjs/config@2.0.0-alpha.6
|
||||
|
||||
## 1.0.1-alpha.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Form, FORM_ERROR } from "app/core/components/Form"
|
||||
import login from "app/auth/mutations/login"
|
||||
import { Login } from "app/auth/validations"
|
||||
import { useMutation } from "@blitzjs/rpc"
|
||||
import { Routes } from "@blitzjs/next"
|
||||
|
||||
type LoginFormProps = {
|
||||
onSuccess?: (user: PromiseReturnType<typeof login>) => void
|
||||
@@ -39,7 +40,7 @@ export const LoginForm = (props: LoginFormProps) => {
|
||||
<LabeledTextField name="email" label="Email" placeholder="Email" />
|
||||
<LabeledTextField name="password" label="Password" placeholder="Password" type="password" />
|
||||
<div>
|
||||
<Link href="/auth/forgot-password" passHref>
|
||||
<Link href={Routes.ForgotPasswordPage()} passHref>
|
||||
<a>Forgot your password?</a>
|
||||
</Link>
|
||||
</div>
|
||||
@@ -47,7 +48,7 @@ export const LoginForm = (props: LoginFormProps) => {
|
||||
|
||||
<div style={{ marginTop: "1rem" }}>
|
||||
Or{" "}
|
||||
<Link href="/auth/signup" passHref>
|
||||
<Link href={Routes.SignupPage()} passHref>
|
||||
<a>Sign Up</a>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
import { NotFoundError, Ctx } from "blitz"
|
||||
import { prisma } from "db"
|
||||
import { NotFoundError } from "blitz"
|
||||
import { db } from "db"
|
||||
import { authenticateUser } from "./login"
|
||||
import { ChangePassword } from "../validations"
|
||||
import { resolver } from "@blitzjs/rpc"
|
||||
import { SecurePassword } from "@blitzjs/auth"
|
||||
|
||||
export default async function changePassword(input, ctx: Ctx) {
|
||||
ChangePassword.parse(input)
|
||||
ctx.session.$isAuthorized()
|
||||
export default resolver.pipe(
|
||||
resolver.zod(ChangePassword),
|
||||
resolver.authorize(),
|
||||
async ({ currentPassword, newPassword }, ctx) => {
|
||||
const user = await db.user.findFirst({ where: { id: ctx.session.userId as number } })
|
||||
if (!user) throw new NotFoundError()
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
id: ctx.session.userId as number,
|
||||
},
|
||||
})
|
||||
await authenticateUser(user.email, currentPassword)
|
||||
|
||||
if (!user) throw new NotFoundError()
|
||||
await authenticateUser(user.email, input.currentPassword)
|
||||
const hashedPassword = await SecurePassword.hash(newPassword.trim())
|
||||
await db.user.update({
|
||||
where: { id: user.id },
|
||||
data: { hashedPassword },
|
||||
})
|
||||
|
||||
const hashedPassword = await SecurePassword.hash(input.newPassword.trim())
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { hashedPassword },
|
||||
})
|
||||
}
|
||||
return true
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { prisma } from "db"
|
||||
import { generateToken, hash256 } from "@blitzjs/auth"
|
||||
import { resolver } from "@blitzjs/rpc"
|
||||
import { db } from "db"
|
||||
import { forgotPasswordMailer } from "mailers/forgotPasswordMailer"
|
||||
import { ForgotPassword } from "../validations"
|
||||
import { Ctx } from "@blitzjs/next"
|
||||
|
||||
const RESET_PASSWORD_TOKEN_EXPIRATION_IN_HOURS = 4
|
||||
|
||||
export default async function forgotPassword(input, ctx: Ctx) {
|
||||
ForgotPassword.parse(input)
|
||||
export default resolver.pipe(resolver.zod(ForgotPassword), async ({ email }) => {
|
||||
// 1. Get the user
|
||||
const user = await prisma.user.findFirst({ where: { email: input.email.toLowerCase() } })
|
||||
const user = await db.user.findFirst({ where: { email: email.toLowerCase() } })
|
||||
|
||||
// 2. Generate the token and expiration date.
|
||||
const token = generateToken()
|
||||
@@ -20,9 +19,9 @@ export default async function forgotPassword(input, ctx: Ctx) {
|
||||
// 3. If user with this email was found
|
||||
if (user) {
|
||||
// 4. Delete any existing password reset tokens
|
||||
await prisma.token.deleteMany({ where: { type: "RESET_PASSWORD", userId: user.id } })
|
||||
await db.token.deleteMany({ where: { type: "RESET_PASSWORD", userId: user.id } })
|
||||
// 5. Save this new token in the database.
|
||||
await prisma.token.create({
|
||||
await db.token.create({
|
||||
data: {
|
||||
user: { connect: { id: user.id } },
|
||||
type: "RESET_PASSWORD",
|
||||
@@ -40,4 +39,4 @@ export default async function forgotPassword(input, ctx: Ctx) {
|
||||
|
||||
// 8. Return the same result whether a password reset email was sent or not
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { AuthenticationError } from "blitz"
|
||||
import { prisma } from "db"
|
||||
import { Login } from "../validations"
|
||||
import { SecurePassword } from "@blitzjs/auth"
|
||||
import { resolver } from "@blitzjs/rpc"
|
||||
import { AuthenticationError } from "blitz"
|
||||
import { db } from "db"
|
||||
import { Role } from "types"
|
||||
import { Login } from "../validations"
|
||||
|
||||
export const authenticateUser = async (rawEmail: string, rawPassword: string) => {
|
||||
const { email, password } = Login.parse({ email: rawEmail, password: rawPassword })
|
||||
const user = await prisma.user.findFirst({ where: { email } })
|
||||
const user = await db.user.findFirst({ where: { email } })
|
||||
if (!user) throw new AuthenticationError()
|
||||
|
||||
const result = await SecurePassword.verify(user.hashedPassword, password)
|
||||
@@ -13,16 +15,18 @@ export const authenticateUser = async (rawEmail: string, rawPassword: string) =>
|
||||
if (result === SecurePassword.VALID_NEEDS_REHASH) {
|
||||
// Upgrade hashed password with a more secure hash
|
||||
const improvedHash = await SecurePassword.hash(password)
|
||||
await prisma.user.update({ where: { id: user.id }, data: { hashedPassword: improvedHash } })
|
||||
await db.user.update({ where: { id: user.id }, data: { hashedPassword: improvedHash } })
|
||||
}
|
||||
|
||||
const { hashedPassword, ...rest } = user
|
||||
return rest
|
||||
}
|
||||
|
||||
export default async function login(input, ctx) {
|
||||
const user = await authenticateUser(input.email, input.password)
|
||||
await ctx.session.$create({ userId: user.id, role: user.role })
|
||||
export default resolver.pipe(resolver.zod(Login), async ({ email, password }, ctx) => {
|
||||
// This throws an error if credentials are invalid
|
||||
const user = await authenticateUser(email, password)
|
||||
|
||||
await ctx.session.$create({ userId: user.id, role: user.role as Role })
|
||||
|
||||
return user
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { SecurePassword, hash256 } from "@blitzjs/auth"
|
||||
import { prisma } from "db"
|
||||
import { db } from "db"
|
||||
import { ResetPassword } from "../validations"
|
||||
import login from "./login"
|
||||
|
||||
@@ -12,7 +12,7 @@ export default async function resetPassword(input, ctx) {
|
||||
ResetPassword.parse(input)
|
||||
// 1. Try to find this token in the database
|
||||
const hashedToken = hash256(input.token)
|
||||
const possibleToken = await prisma.token.findFirst({
|
||||
const possibleToken = await db.token.findFirst({
|
||||
where: { hashedToken, type: "RESET_PASSWORD" },
|
||||
include: { user: true },
|
||||
})
|
||||
@@ -24,7 +24,7 @@ export default async function resetPassword(input, ctx) {
|
||||
const savedToken = possibleToken
|
||||
|
||||
// 3. Delete token so it can't be used again
|
||||
await prisma.token.delete({ where: { id: savedToken.id } })
|
||||
await db.token.delete({ where: { id: savedToken.id } })
|
||||
|
||||
// 4. If token has expired, error
|
||||
if (savedToken.expiresAt < new Date()) {
|
||||
@@ -33,13 +33,13 @@ export default async function resetPassword(input, ctx) {
|
||||
|
||||
// 5. Since token is valid, now we can update the user's password
|
||||
const hashedPassword = await SecurePassword.hash(input.password.trim())
|
||||
const user = await prisma.user.update({
|
||||
const user = await db.user.update({
|
||||
where: { id: savedToken.userId },
|
||||
data: { hashedPassword },
|
||||
})
|
||||
|
||||
// 6. Revoke all existing login sessions for this user
|
||||
await prisma.session.deleteMany({ where: { userId: user.id } })
|
||||
await db.session.deleteMany({ where: { userId: user.id } })
|
||||
|
||||
// 7. Now log the user in with the new credentials
|
||||
await login({ email: user.email, password: input.password }, ctx)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { prisma } from "db"
|
||||
import { db } from "db"
|
||||
import { SecurePassword } from "@blitzjs/auth"
|
||||
|
||||
export default async function signup(input, ctx) {
|
||||
@@ -6,7 +6,7 @@ export default async function signup(input, ctx) {
|
||||
|
||||
const hashedPassword = await SecurePassword.hash((input.password as string) || "test-password")
|
||||
const email = (input.email as string) || "test" + Math.random() + "@test.com"
|
||||
const user = await prisma.user.create({
|
||||
const user = await db.user.create({
|
||||
data: { email, hashedPassword, role: "user" },
|
||||
select: { id: true, name: true, email: true, role: true },
|
||||
})
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { AuthClientPlugin } from "@blitzjs/auth"
|
||||
import { setupClient } from "@blitzjs/next"
|
||||
import { setupBlitzClient } from "@blitzjs/next"
|
||||
import { BlitzRpcPlugin } from "@blitzjs/rpc"
|
||||
|
||||
const { withBlitz } = setupClient({
|
||||
export const { withBlitz } = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "web-cookie-prefix",
|
||||
@@ -16,5 +16,3 @@ const { withBlitz } = setupClient({
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
export { withBlitz }
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { setupBlitz } from "@blitzjs/next"
|
||||
import { setupBlitzServer } from "@blitzjs/next"
|
||||
import { AuthServerPlugin, PrismaStorage } from "@blitzjs/auth"
|
||||
import { prisma as db } from "../db/index"
|
||||
import { db } from "db"
|
||||
import { simpleRolesIsAuthorized } from "@blitzjs/auth"
|
||||
|
||||
const { gSSP, gSP, api } = setupBlitz({
|
||||
const { gSSP, gSP, api } = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "web-cookie-prefix",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Ctx } from "blitz"
|
||||
import { prisma } from "db"
|
||||
import { db } from "db"
|
||||
|
||||
export default async function getCurrentUser(_ = null, { session }: Ctx) {
|
||||
if (!session.userId) return null
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
const user = await db.user.findFirst({
|
||||
where: { id: session.userId as number },
|
||||
select: { id: true, name: true, email: true, role: true },
|
||||
})
|
||||
|
||||
@@ -4,5 +4,5 @@ import { PrismaClient } from "@prisma/client"
|
||||
const EnhancedPrisma = enhancePrisma(PrismaClient)
|
||||
|
||||
export * from "@prisma/client"
|
||||
const prisma = new EnhancedPrisma()
|
||||
export { prisma }
|
||||
const db = new EnhancedPrisma()
|
||||
export { db }
|
||||
|
||||
47
apps/toolkit-app/db/migrations/20220427214932_/migration.sql
Normal file
47
apps/toolkit-app/db/migrations/20220427214932_/migration.sql
Normal file
@@ -0,0 +1,47 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "User" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
"name" TEXT,
|
||||
"email" TEXT NOT NULL,
|
||||
"hashedPassword" TEXT,
|
||||
"role" TEXT NOT NULL DEFAULT 'USER'
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Session" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
"expiresAt" DATETIME,
|
||||
"handle" TEXT NOT NULL,
|
||||
"hashedSessionToken" TEXT,
|
||||
"antiCSRFToken" TEXT,
|
||||
"publicData" TEXT,
|
||||
"privateData" TEXT,
|
||||
"userId" INTEGER,
|
||||
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Token" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
"hashedToken" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL,
|
||||
"expiresAt" DATETIME NOT NULL,
|
||||
"sentTo" TEXT NOT NULL,
|
||||
"userId" INTEGER NOT NULL,
|
||||
CONSTRAINT "Token_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Session_handle_key" ON "Session"("handle");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Token_hashedToken_type_key" ON "Token"("hashedToken", "type");
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "toolkit-app",
|
||||
"version": "1.0.1-alpha.0",
|
||||
"version": "1.0.1-alpha.16",
|
||||
"scripts": {
|
||||
"start:dev": "pnpm run prisma:start && next dev",
|
||||
"buildapp": "prisma generate && next build",
|
||||
"buildapp": "pnpm i && pnpm prisma generate && next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"prisma:start": "prisma generate && prisma migrate deploy",
|
||||
@@ -29,8 +29,8 @@
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@hookform/resolvers": "2.8.8",
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:2.0.0-alpha.5",
|
||||
"next": "12.1.1",
|
||||
"blitz": "workspace:2.0.0-alpha.21",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useRouter } from "next/router"
|
||||
import Layout from "app/core/layouts/Layout"
|
||||
import { SignupForm } from "app/auth/components/SignupForm"
|
||||
import { Routes } from "@blitzjs/next"
|
||||
|
||||
const SignupPage = () => {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<Layout title="Sign Up">
|
||||
<SignupForm onSuccess={() => router.push("/")} />
|
||||
<SignupForm onSuccess={() => router.push(Routes.Home())} />
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useCurrentUser } from "app/core/hooks/useCurrentUser"
|
||||
import logout from "app/auth/mutations/logout"
|
||||
import logo from "public/logo.png"
|
||||
import { useMutation } from "@blitzjs/rpc"
|
||||
import { Routes } from "@blitzjs/next"
|
||||
|
||||
/*
|
||||
* This file is just for a pleasant getting started page for your new app.
|
||||
@@ -37,12 +38,12 @@ const UserInfo = () => {
|
||||
} else {
|
||||
return (
|
||||
<>
|
||||
<Link href="/auth/signup" passHref>
|
||||
<Link href={Routes.SignupPage()} passHref>
|
||||
<a className="button small">
|
||||
<strong>Sign Up</strong>
|
||||
</a>
|
||||
</Link>
|
||||
<Link href="/auth/login" passHref>
|
||||
<Link href={Routes.LoginPage()} passHref>
|
||||
<a className="button small">
|
||||
<strong>Login</strong>
|
||||
</a>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"baseUrl": "./",
|
||||
"baseUrl": ".",
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": false,
|
||||
@@ -20,5 +20,5 @@
|
||||
"tsBuildInfoFile": ".tsbuildinfo"
|
||||
},
|
||||
"exclude": ["node_modules", "**/*.e2e.ts", "cypress"],
|
||||
"include": ["blitz-env.d.ts", "**/*.ts", "**/*.tsx"]
|
||||
"include": ["blitz-env.d.ts", "**/*.ts", "**/*.tsx", "types"]
|
||||
}
|
||||
|
||||
15
apps/toolkit-app/types.ts
Normal file
15
apps/toolkit-app/types.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { SimpleRolesIsAuthorized } from "@blitzjs/auth"
|
||||
import { User } from "db"
|
||||
|
||||
export type Role = "ADMIN" | "USER"
|
||||
|
||||
declare module "@blitzjs/auth" {
|
||||
export interface Session {
|
||||
isAuthorized: SimpleRolesIsAuthorized<Role>
|
||||
PublicData: {
|
||||
userId: User["id"]
|
||||
role: Role
|
||||
views?: number
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import {AuthClientPlugin} from "@blitzjs/auth"
|
||||
import {setupClient} from "@blitzjs/next"
|
||||
import {setupBlitzClient} from "@blitzjs/next"
|
||||
import {BlitzRpcPlugin} from "@blitzjs/rpc"
|
||||
|
||||
const {withBlitz} = setupClient({
|
||||
const {withBlitz} = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "webapp-cookie-prefix",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {setupBlitz} from "@blitzjs/next"
|
||||
import {setupBlitzServer} from "@blitzjs/next"
|
||||
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
|
||||
import {prisma as db} from "../prisma/index"
|
||||
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
|
||||
|
||||
const {gSSP, gSP, api} = setupBlitz({
|
||||
const {gSSP, gSP, api} = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "webapp-cookie-prefix",
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
"@types/jest": "27.4.1",
|
||||
"blitz": "workspace:*",
|
||||
"jest": "27.5.1",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import {gSP} from "app/blitz-server"
|
||||
|
||||
export const getStaticProps = gSP(async ({ctx}) => {
|
||||
export const getStaticProps = gSP<{data: {test: string}}>(async ({ctx}) => {
|
||||
return {
|
||||
props: {
|
||||
data: {
|
||||
// userId: ctx?.session.userId,
|
||||
// session: {
|
||||
// id: session.userId,
|
||||
// publicData: session.$publicData,
|
||||
// },
|
||||
test: "hello",
|
||||
date: new Date(),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ export const getServerSideProps = gSSP<Props>(async ({ctx}) => {
|
||||
props: {
|
||||
userId: session.userId,
|
||||
publicData: session.$publicData,
|
||||
publishedAt: new Date(0),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {AuthClientPlugin} from "@blitzjs/auth"
|
||||
import {setupClient} from "@blitzjs/next"
|
||||
import {setupBlitzClient} from "@blitzjs/next"
|
||||
|
||||
const {withBlitz} = setupClient({
|
||||
const {withBlitz} = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "auth-tests-cookie-prefix",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {setupBlitz} from "@blitzjs/next"
|
||||
import {setupBlitzServer} from "@blitzjs/next"
|
||||
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
|
||||
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
|
||||
import {prisma as db} from "../prisma/index"
|
||||
|
||||
const {gSSP, gSP, api} = setupBlitz({
|
||||
const {gSSP, gSP, api} = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "auth-tests-cookie-prefix",
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:*",
|
||||
"lowdb": "3.0.0",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0"
|
||||
|
||||
1
integration-tests/qm/.eslintrc.js
Normal file
1
integration-tests/qm/.eslintrc.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("@blitzjs/config/eslint")
|
||||
3
integration-tests/qm/.gitignore
vendored
Normal file
3
integration-tests/qm/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
# Keep environment variables out of version control
|
||||
*.sqlite
|
||||
5
integration-tests/qm/next-env.d.ts
vendored
Normal file
5
integration-tests/qm/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
||||
4
integration-tests/qm/next.config.js
Normal file
4
integration-tests/qm/next.config.js
Normal file
@@ -0,0 +1,4 @@
|
||||
const {withBlitz} = require("@blitzjs/next")
|
||||
module.exports = withBlitz({
|
||||
// update me
|
||||
})
|
||||
34
integration-tests/qm/package.json
Normal file
34
integration-tests/qm/package.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "test-qm",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test-watch": "vitest",
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules"
|
||||
},
|
||||
"dependencies": {
|
||||
"@blitzjs/auth": "workspace:*",
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@blitzjs/next": "workspace:*",
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:*",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"react-query": "3.21.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/react": "13.0.0",
|
||||
"@types/react": "17.0.43",
|
||||
"@vitejs/plugin-react": "1.3.0",
|
||||
"delay": "5.0.0",
|
||||
"eslint": "7.32.0",
|
||||
"eslint-config-next": "latest",
|
||||
"eslint-plugin-testing-library": "5.0.1",
|
||||
"jsdom": "^19.0.0",
|
||||
"typescript": "^4.5.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Vitest Snapshot v1
|
||||
|
||||
exports[`useMutation > useMutation calls the resolver with the argument > shouldn't work with query function 1`] = `"\\"useMutation\\" was expected to be called with a mutation but was called with a \\"query\\""`;
|
||||
|
||||
exports[`useMutation > useMutation calls the resolver with the argument > shouldn't work with regular functions 1`] = `"Either the file path to your resolver is incorrect (must be in a \\"queries\\" or \\"mutations\\" folder that isn't nested inside \\"pages\\" or \\"api\\") or you are trying to use Blitz's useQuery to fetch from third-party APIs (to do that, import useQuery directly from \\"react-query\\")"`;
|
||||
@@ -0,0 +1,5 @@
|
||||
// Vitest Snapshot v1
|
||||
|
||||
exports[`useQuery > a "query" that converts the string parameter to uppercase > shouldn't work with mutation function 1`] = `"Cannot read properties of null (reading 'isReady')"`;
|
||||
|
||||
exports[`useQuery > a "query" that converts the string parameter to uppercase > shouldn't work with regular functions 1`] = `"Cannot read properties of null (reading 'isReady')"`;
|
||||
55
integration-tests/qm/test/use-mutation.test.tsx
Normal file
55
integration-tests/qm/test/use-mutation.test.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import {describe, it, expect, beforeAll, vi} from "vitest"
|
||||
import {act, screen} from "@testing-library/react"
|
||||
import {useMutation} from "@blitzjs/rpc"
|
||||
import React from "react"
|
||||
import {buildMutationRpc, buildQueryRpc, render} from "../../utils/blitz-test-utils"
|
||||
|
||||
beforeAll(() => {
|
||||
globalThis.__BLITZ_SESSION_COOKIE_PREFIX = "qm-test-cookie-prefix"
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
describe("useMutation", () => {
|
||||
const setupHook = (resolver: (...args: any) => Promise<any>): [{mutate?: Function}, Function] => {
|
||||
let res = {}
|
||||
|
||||
function TestHarness() {
|
||||
const [mutate, {isSuccess}] = useMutation(resolver)
|
||||
|
||||
Object.assign(res, {mutate})
|
||||
return <div id="harness">{isSuccess ? "Sent" : "Waiting"}</div>
|
||||
}
|
||||
|
||||
const ui = () => <TestHarness />
|
||||
|
||||
const {rerender} = render(ui())
|
||||
return [res, () => rerender(ui())]
|
||||
}
|
||||
|
||||
describe("useMutation calls the resolver with the argument", () => {
|
||||
// eslint-disable-next-line require-await
|
||||
const mutateFn = vi.fn()
|
||||
it("should work with Blitz mutations", async () => {
|
||||
const [res] = setupHook(buildMutationRpc(mutateFn))
|
||||
await act(async () => {
|
||||
await res.mutate!("data")
|
||||
})
|
||||
|
||||
await screen.findByText("Sent")
|
||||
expect(mutateFn).toHaveBeenCalledTimes(1)
|
||||
expect(mutateFn).toHaveBeenCalledWith("data", {fromQueryHook: true})
|
||||
})
|
||||
|
||||
it("shouldn't work with regular functions", () => {
|
||||
console.error = vi.fn()
|
||||
expect(() => setupHook(mutateFn)).toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
|
||||
it("shouldn't work with query function", () => {
|
||||
console.error = vi.fn()
|
||||
const mutationFn = vi.fn()
|
||||
|
||||
expect(() => setupHook(buildQueryRpc(mutationFn))).toThrowErrorMatchingSnapshot()
|
||||
})
|
||||
})
|
||||
})
|
||||
166
integration-tests/qm/test/use-query.test.tsx
Normal file
166
integration-tests/qm/test/use-query.test.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import {describe, it, expect, beforeAll, vi} from "vitest"
|
||||
import {act, screen, waitForElementToBeRemoved, waitFor} from "@testing-library/react"
|
||||
import {useQuery, useInfiniteQuery} from "@blitzjs/rpc"
|
||||
import React from "react"
|
||||
import delay from "delay"
|
||||
import {buildMutationRpc, buildQueryRpc, render} from "../../utils/blitz-test-utils"
|
||||
|
||||
describe("useQuery", () => {
|
||||
it("Placeholder", async () => {
|
||||
console.log("placeholder")
|
||||
})
|
||||
})
|
||||
// beforeAll(() => {
|
||||
// globalThis.__BLITZ_SESSION_COOKIE_PREFIX = "qm-test-cookie-prefix"
|
||||
// globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
// })
|
||||
|
||||
// describe("useQuery", () => {
|
||||
// const setupHook = (
|
||||
// params: any,
|
||||
// queryFn: (...args: any) => any,
|
||||
// options: Parameters<typeof useQuery>[2] = {} as any,
|
||||
// ): [{data?: any; setQueryData?: any}, Function] => {
|
||||
// let res = {}
|
||||
// function TestHarness() {
|
||||
// const [data, {setQueryData}] = useQuery(queryFn, params, {
|
||||
// suspense: true,
|
||||
// ...options,
|
||||
// } as any)
|
||||
// Object.assign(res, {data, setQueryData})
|
||||
// return (
|
||||
// <div id="harness">
|
||||
// <span>{data ? "Ready" : "No data"}</span>
|
||||
// <span>{data}</span>
|
||||
// </div>
|
||||
// )
|
||||
// }
|
||||
|
||||
// const ui = () => (
|
||||
// <React.Suspense fallback="Loading...">
|
||||
// <TestHarness />
|
||||
// </React.Suspense>
|
||||
// )
|
||||
|
||||
// const {rerender} = render(ui())
|
||||
// return [res, () => rerender(ui())]
|
||||
// }
|
||||
|
||||
// describe('a "query" that converts the string parameter to uppercase', () => {
|
||||
// const upcase = async (args: string) => {
|
||||
// await delay(1000)
|
||||
// return args.toUpperCase()
|
||||
// }
|
||||
// it("should work with Blitz queries", async () => {
|
||||
// const [res] = setupHook("test", buildQueryRpc(upcase))
|
||||
// await waitForElementToBeRemoved(() => screen.getByText("Loading..."))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("Ready")
|
||||
// expect(res.data).toBe("TEST")
|
||||
// })
|
||||
// })
|
||||
|
||||
// it("should be able to change the data with setQueryData", async () => {
|
||||
// const [res] = setupHook("test", buildQueryRpc(upcase))
|
||||
// await waitForElementToBeRemoved(() => screen.getByText("Loading..."))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("Ready")
|
||||
// expect(res.data).toBe("TEST")
|
||||
// res.setQueryData((p: string) => p.substr(1, 2), {refetch: false})
|
||||
// await waitFor(() => screen.getByText("ES"))
|
||||
// })
|
||||
// })
|
||||
|
||||
// it("shouldn't work with regular functions", () => {
|
||||
// console.error = vi.fn()
|
||||
// expect(() => setupHook("test", upcase)).toThrowErrorMatchingSnapshot()
|
||||
// })
|
||||
|
||||
// it("shouldn't work with mutation function", () => {
|
||||
// console.error = vi.fn()
|
||||
// expect(() => setupHook("test", buildMutationRpc(upcase))).toThrowErrorMatchingSnapshot()
|
||||
// })
|
||||
|
||||
// it("suspense disabled if enabled is false", async () => {
|
||||
// setupHook("test", buildQueryRpc(upcase), {enabled: false})
|
||||
// await screen.findByText("No data")
|
||||
// })
|
||||
|
||||
// it("suspense disabled if enabled is undefined", async () => {
|
||||
// setupHook("test", buildQueryRpc(upcase), {enabled: undefined})
|
||||
// await screen.findByText("No data")
|
||||
// })
|
||||
|
||||
// it("suspense disabled if enabled is false and suspense set", async () => {
|
||||
// setupHook("test", buildQueryRpc(upcase), {
|
||||
// enabled: false,
|
||||
// suspense: true,
|
||||
// })
|
||||
// await screen.findByText("No data")
|
||||
// })
|
||||
// })
|
||||
|
||||
// // it("works with options other than enabled & suspense without type error", () => {
|
||||
// // const queryFn = ((() => true) as unknown) as () => Promise<boolean>
|
||||
// // useQuery(queryFn, undefined, {refetchInterval: 10000})
|
||||
// // })
|
||||
// })
|
||||
|
||||
// describe("useInfiniteQuery", () => {
|
||||
// const setupHook = (
|
||||
// params: (arg?: any) => any,
|
||||
// queryFn: (...args: any) => any,
|
||||
// ): [{data?: any; setQueryData?: any}, Function] => {
|
||||
// let res = {}
|
||||
// function TestHarness() {
|
||||
// // TODO - fix typing
|
||||
// //@ts-ignore
|
||||
// const [groupedData] = useInfiniteQuery(queryFn, params, {
|
||||
// suspense: true,
|
||||
// getNextPageParam: () => {},
|
||||
// })
|
||||
// Object.assign(res, {groupedData})
|
||||
// return (
|
||||
// <div id="harness">
|
||||
// <span>{groupedData ? "Ready" : "No data"}</span>
|
||||
// <div>
|
||||
// {groupedData.map((data: any, i) => (
|
||||
// <div key={i}>{data}</div>
|
||||
// ))}
|
||||
// </div>
|
||||
// </div>
|
||||
// )
|
||||
// }
|
||||
|
||||
// const ui = () => (
|
||||
// <React.Suspense fallback="Loading...">
|
||||
// <TestHarness />
|
||||
// </React.Suspense>
|
||||
// )
|
||||
|
||||
// const {rerender} = render(ui())
|
||||
// return [res, () => rerender(ui())]
|
||||
// }
|
||||
|
||||
// const getItems = ({id}: {id: number}) => {
|
||||
// if (id === 1) {
|
||||
// return "item1"
|
||||
// } else if (id === 2) {
|
||||
// return "item2"
|
||||
// } else {
|
||||
// throw new Error("No item for this id")
|
||||
// }
|
||||
// }
|
||||
// it("should work", async () => {
|
||||
// setupHook(() => ({id: 1}), buildQueryRpc(getItems))
|
||||
// await waitForElementToBeRemoved(() => screen.getByText("Loading..."))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("item1")
|
||||
// })
|
||||
|
||||
// setupHook(() => ({id: 2}), buildQueryRpc(getItems))
|
||||
// await act(async () => {
|
||||
// await screen.findByText("item2")
|
||||
// })
|
||||
// })
|
||||
// })
|
||||
13
integration-tests/qm/tsconfig.json
Normal file
13
integration-tests/qm/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "@blitzjs/config/tsconfig.nextjs.json",
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "../utils/blitz-test-utils.tsx"],
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"paths": {
|
||||
"react": ["./node_modules/@types/react"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"baseUrl": "."
|
||||
}
|
||||
12
integration-tests/qm/vitest.config.ts
Normal file
12
integration-tests/qm/vitest.config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/// <reference types="vitest" />
|
||||
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
},
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
const {withBlitz} = require("@blitzjs/next")
|
||||
module.exports = withBlitz({
|
||||
// update me
|
||||
target: 'experimental-serverless-trace',
|
||||
})
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"@blitzjs/next": "workspace:*",
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"blitz": "workspace:*",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0"
|
||||
},
|
||||
|
||||
123
integration-tests/utils/blitz-test-utils.tsx
Normal file
123
integration-tests/utils/blitz-test-utils.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import {render as defaultRender} from "@testing-library/react"
|
||||
import {NextRouter} from "next/router"
|
||||
import {vi} from "vitest"
|
||||
import {QueryClient, QueryClientProvider} from "react-query"
|
||||
import React from "react"
|
||||
import {BlitzRpcPlugin} from "@blitzjs/rpc"
|
||||
|
||||
const mockRouter: NextRouter = {
|
||||
basePath: "",
|
||||
pathname: "/",
|
||||
route: "/",
|
||||
asPath: "/",
|
||||
query: {},
|
||||
isReady: true,
|
||||
isLocaleDomain: false,
|
||||
isPreview: false,
|
||||
push: vi.fn(),
|
||||
replace: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
back: vi.fn(),
|
||||
prefetch: vi.fn(),
|
||||
beforePopState: vi.fn(),
|
||||
events: {
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
},
|
||||
isFallback: false,
|
||||
}
|
||||
|
||||
type DefaultParams = Parameters<typeof defaultRender>
|
||||
type RenderUI = DefaultParams[0]
|
||||
type RenderOptions = DefaultParams[1] & {
|
||||
router?: Partial<NextRouter>
|
||||
}
|
||||
export type BlitzProviderProps = {
|
||||
client?: QueryClient
|
||||
contextSharing?: boolean
|
||||
}
|
||||
|
||||
const BlitzProvider = ({
|
||||
client,
|
||||
contextSharing = false,
|
||||
children,
|
||||
}: BlitzProviderProps & {children: JSX.Element}) => {
|
||||
if (globalThis.queryClient) {
|
||||
return (
|
||||
<QueryClientProvider
|
||||
client={client || globalThis.queryClient}
|
||||
contextSharing={contextSharing}
|
||||
>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return children
|
||||
}
|
||||
export const RouterContext = React.createContext(null as any)
|
||||
RouterContext.displayName = "RouterContext"
|
||||
const compose =
|
||||
(...rest) =>
|
||||
(x: React.ComponentType<any>) =>
|
||||
rest.reduceRight((y, f) => f(y), x)
|
||||
|
||||
const BlitzWrapper = ({plugins, children}) => {
|
||||
const providers = plugins.reduce((acc, plugin) => {
|
||||
return plugin.withProvider ? acc.concat(plugin.withProvider) : acc
|
||||
}, [])
|
||||
const withPlugins = compose(...providers)
|
||||
const component = React.useMemo(() => withPlugins(children), [children])
|
||||
|
||||
return (
|
||||
<BlitzProvider>
|
||||
<RouterContext.Provider value={{...mockRouter}}>{component}</RouterContext.Provider>
|
||||
</BlitzProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export function render(ui: RenderUI, {wrapper, router, ...options}: RenderOptions = {}) {
|
||||
if (!wrapper) {
|
||||
wrapper = ({children}) => {
|
||||
return (
|
||||
<BlitzWrapper
|
||||
plugins={[
|
||||
BlitzRpcPlugin({
|
||||
reactQueryOptions: {
|
||||
queries: {
|
||||
staleTime: 7000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
]}
|
||||
>
|
||||
{children}
|
||||
</BlitzWrapper>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return defaultRender(ui, {wrapper, ...options})
|
||||
}
|
||||
|
||||
// This enhance fn does what buildRpcFunction does during build time
|
||||
export function buildQueryRpc(fn: any) {
|
||||
const newFn = (...args: any) => {
|
||||
const [data, ...rest] = args
|
||||
return fn(data, ...rest)
|
||||
}
|
||||
newFn._isRpcClient = true
|
||||
newFn._resolverType = "query"
|
||||
newFn._routePath = "/api/test/url/" + Math.random()
|
||||
return newFn
|
||||
}
|
||||
|
||||
// This enhance fn does what buildRpcFunction does during build time
|
||||
export function buildMutationRpc(fn: any) {
|
||||
const newFn = (...args: any) => fn(...args)
|
||||
newFn._isRpcClient = true
|
||||
newFn._resolverType = "mutation"
|
||||
newFn._routePath = "/api/test/url"
|
||||
return newFn
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export function waitFor(millis) {
|
||||
return new Promise((resolve) => setTimeout(resolve, millis))
|
||||
}
|
||||
|
||||
export {By}
|
||||
|
||||
const {
|
||||
BROWSER_NAME: browserName = "chrome",
|
||||
BROWSERSTACK,
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace: *",
|
||||
"@blitzjs/rpc": "workspace: *",
|
||||
"@testing-library/react": "13.0.0",
|
||||
"@types/express": "4.17.13",
|
||||
"@types/fs-extra": "9.0.13",
|
||||
"@types/node-fetch": "2.6.1",
|
||||
@@ -16,6 +19,9 @@
|
||||
"fs-extra": "10.0.1",
|
||||
"get-port": "6.1.2",
|
||||
"node-fetch": "3.2.3",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"react-query": "3.21.1",
|
||||
"rimraf": "3.0.2",
|
||||
"selenium-webdriver": "4.1.1",
|
||||
"tree-kill": "1.2.2",
|
||||
|
||||
13
integration-tests/utils/tsconfig.json
Normal file
13
integration-tests/utils/tsconfig.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "@blitzjs/config/tsconfig.nextjs.json",
|
||||
"include": ["*.ts", "*.tsx"],
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"paths": {
|
||||
"react": ["./node_modules/@types/react"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"baseUrl": "."
|
||||
}
|
||||
@@ -88,6 +88,10 @@ export default class Chain {
|
||||
return this.updateChain(() => this.browser.findElements(By.css(sel)))
|
||||
}
|
||||
|
||||
elementsById(sel) {
|
||||
return this.updateChain(() => this.browser.findElements(By.id(sel)))
|
||||
}
|
||||
|
||||
waitForElementByCss(sel, timeout) {
|
||||
return this.updateChain(() => this.browser.wait(until.elementLocated(By.css(sel), timeout)))
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
"test": "turbo run test",
|
||||
"clean": "turbo run clean && rm -rf node_modules",
|
||||
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
|
||||
"pre-publish": "pnpm i && pnpm build && changeset add && changeset version && git add . && git commit -v",
|
||||
"pre-publish": "pnpm i && changeset add && changeset version && pnpm build && git add . && git commit -v",
|
||||
"publish-release": "changeset publish && git push --follow-tags"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -25,9 +25,9 @@
|
||||
"@changesets/cli": "2.22.0",
|
||||
"eslint": "7.32.0",
|
||||
"husky": "7.0.4",
|
||||
"jsdom": "19.0.0",
|
||||
"jsdom": "^19.0.0",
|
||||
"lint-staged": "12.1.7",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"only-allow": "1.1.0",
|
||||
"patch-package": "6.4.7",
|
||||
"prettier": "^2.5.1",
|
||||
|
||||
@@ -1,5 +1,113 @@
|
||||
# @blitzjs/auth
|
||||
|
||||
## 2.0.0-alpha.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.21
|
||||
|
||||
## 2.0.0-alpha.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- testing set dist-tag
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.20
|
||||
|
||||
## 2.0.0-alpha.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.19
|
||||
|
||||
## 2.0.0-alpha.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.18
|
||||
|
||||
## 2.0.0-alpha.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.17
|
||||
|
||||
## 2.0.0-alpha.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.16
|
||||
|
||||
## 2.0.0-alpha.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.15
|
||||
|
||||
## 2.0.0-alpha.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.14
|
||||
|
||||
## 2.0.0-alpha.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.13
|
||||
|
||||
## 2.0.0-alpha.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.12
|
||||
|
||||
## 2.0.0-alpha.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.11
|
||||
|
||||
## 2.0.0-alpha.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.10
|
||||
|
||||
## 2.0.0-alpha.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.9
|
||||
|
||||
## 2.0.0-alpha.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.8
|
||||
|
||||
## 2.0.0-alpha.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.7
|
||||
|
||||
## 2.0.0-alpha.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fix route manifest codegen
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.6
|
||||
|
||||
## 2.0.0-alpha.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@blitzjs/auth",
|
||||
"version": "2.0.0-alpha.5",
|
||||
"version": "2.0.0-alpha.21",
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"predev": "wait-on -d 250 ../blitz/dist/index-server.d.ts",
|
||||
@@ -24,7 +24,7 @@
|
||||
"@types/secure-password": "3.1.1",
|
||||
"b64-lite": "1.4.0",
|
||||
"bad-behavior": "1.0.1",
|
||||
"blitz": "workspace:*",
|
||||
"blitz": "2.0.0-alpha.21",
|
||||
"cookie": "0.4.1",
|
||||
"debug": "4.3.3",
|
||||
"http": "0.0.1-security",
|
||||
@@ -35,7 +35,7 @@
|
||||
"url": "0.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.21",
|
||||
"@testing-library/react": "13.0.0",
|
||||
"@testing-library/react-hooks": "7.0.2",
|
||||
"@types/cookie": "0.4.1",
|
||||
|
||||
@@ -138,7 +138,10 @@ export const useSession = (options: UseSessionOptions = {}): ClientSession => {
|
||||
initialState = {...options.initialPublicData, isLoading: false}
|
||||
} else if (suspense) {
|
||||
if (isServer) {
|
||||
throw new Promise((_) => {})
|
||||
const e = new Error()
|
||||
e.name = "Rendering Suspense fallback..."
|
||||
delete e.stack
|
||||
throw e
|
||||
} else {
|
||||
initialState = {...getPublicDataStore().getData(), isLoading: false}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,4 @@ import "./global"
|
||||
|
||||
export * from "./client"
|
||||
export * from "./shared/constants"
|
||||
export type {
|
||||
SessionContextBase,
|
||||
SessionContext,
|
||||
AuthenticatedSessionContext,
|
||||
ClientSession,
|
||||
AuthenticatedClientSession,
|
||||
} from "./shared/types"
|
||||
export * from "./shared/types"
|
||||
|
||||
@@ -1,5 +1,109 @@
|
||||
# @blitzjs/next
|
||||
|
||||
## 2.0.0-alpha.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.21
|
||||
|
||||
## 2.0.0-alpha.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- testing set dist-tag
|
||||
- Updated dependencies
|
||||
- @blitzjs/rpc@2.0.0-alpha.20
|
||||
|
||||
## 2.0.0-alpha.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- added superjson
|
||||
- 2150dcc3: Setup SuperJson for GSSP and GSP
|
||||
- @blitzjs/rpc@2.0.0-alpha.19
|
||||
|
||||
## 2.0.0-alpha.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.18
|
||||
|
||||
## 2.0.0-alpha.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.17
|
||||
|
||||
## 2.0.0-alpha.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.16
|
||||
|
||||
## 2.0.0-alpha.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.15
|
||||
|
||||
## 2.0.0-alpha.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.14
|
||||
|
||||
## 2.0.0-alpha.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix codegen and postinstall to make work with pnpm
|
||||
- @blitzjs/rpc@2.0.0-alpha.13
|
||||
|
||||
## 2.0.0-alpha.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.12
|
||||
|
||||
## 2.0.0-alpha.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix postinstall script not being found
|
||||
- @blitzjs/rpc@2.0.0-alpha.11
|
||||
|
||||
## 2.0.0-alpha.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.10
|
||||
|
||||
## 2.0.0-alpha.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.9
|
||||
|
||||
## 2.0.0-alpha.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.8
|
||||
|
||||
## 2.0.0-alpha.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.7
|
||||
|
||||
## 2.0.0-alpha.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fix route manifest codegen
|
||||
- Updated dependencies
|
||||
- @blitzjs/rpc@2.0.0-alpha.6
|
||||
|
||||
## 2.0.0-alpha.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -2,7 +2,7 @@ import {BuildConfig} from "unbuild"
|
||||
|
||||
const config: BuildConfig = {
|
||||
entries: ["./src/index-browser", "./src/index-server"],
|
||||
externals: ["index-browser.cjs", "index-browser.mjs", "blitz"],
|
||||
externals: ["index-browser.cjs", "index-browser.mjs", "blitz", ".blitz"],
|
||||
declaration: true,
|
||||
rollup: {
|
||||
emitCJS: true,
|
||||
|
||||
29
packages/blitz-next/eslint.js
Normal file
29
packages/blitz-next/eslint.js
Normal file
@@ -0,0 +1,29 @@
|
||||
module.exports = {
|
||||
extends: ["eslint-config-next", "prettier"],
|
||||
ignorePatterns: ["*.d.ts"],
|
||||
settings: {
|
||||
next: {
|
||||
rootDir: ["./apps/*/", "./packages/*/"],
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"@next/next/no-html-link-for-pages": "off",
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["**/*.ts?(x)"],
|
||||
plugins: ["@typescript-eslint"],
|
||||
parserOptions: {
|
||||
project: "./tsconfig.json",
|
||||
},
|
||||
rules: {
|
||||
"@typescript-eslint/no-floating-promises": "error",
|
||||
"no-use-before-define": "off",
|
||||
"@typescript-eslint/no-use-before-define": ["off"],
|
||||
"no-redeclare": "off",
|
||||
"@typescript-eslint/no-redeclare": ["error"],
|
||||
"react/display-name": "off",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@blitzjs/next",
|
||||
"version": "2.0.0-alpha.5",
|
||||
"version": "2.0.0-alpha.21",
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"dev": "pnpm predev && pnpm watch unbuild src --wait=0.2",
|
||||
@@ -8,7 +8,8 @@
|
||||
"lint": "eslint . --fix",
|
||||
"test": "vitest run",
|
||||
"test-watch": "vitest",
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
|
||||
"postinstall": "node scripts/postinstall.js"
|
||||
},
|
||||
"main": "./dist/index-server.cjs",
|
||||
"module": "./dist/index-server.mjs",
|
||||
@@ -17,16 +18,21 @@
|
||||
"sideEffects": false,
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"dist/**"
|
||||
"dist/**",
|
||||
"scripts/**",
|
||||
"eslint.js"
|
||||
],
|
||||
"dependencies": {
|
||||
"@blitzjs/rpc": "2.0.0-alpha.5",
|
||||
"@blitzjs/rpc": "2.0.0-alpha.21",
|
||||
"@types/hoist-non-react-statics": "3.3.1",
|
||||
"debug": "4.3.3",
|
||||
"fs-extra": "10.0.1",
|
||||
"react-query": "3.21.1"
|
||||
"hoist-non-react-statics": "3.3.2",
|
||||
"react-query": "3.21.1",
|
||||
"superjson": "1.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.21",
|
||||
"@testing-library/dom": "8.13.0",
|
||||
"@testing-library/jest-dom": "5.16.3",
|
||||
"@testing-library/react": "13.0.0",
|
||||
@@ -37,11 +43,14 @@
|
||||
"@types/react": "17.0.43",
|
||||
"@types/react-dom": "17.0.14",
|
||||
"@types/testing-library__react-hooks": "4.0.0",
|
||||
"blitz": "workspace:*",
|
||||
"blitz": "2.0.0-alpha.21",
|
||||
"cross-spawn": "7.0.3",
|
||||
"find-up": "4.1.0",
|
||||
"lodash.frompairs": "4.0.1",
|
||||
"next": "12.1.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"resolve-from": "5.0.0",
|
||||
"ts-jest": "27.1.4",
|
||||
"typescript": "^4.5.3",
|
||||
"unbuild": "0.6.9",
|
||||
|
||||
3
packages/blitz-next/scripts/default-index-browser.js
Normal file
3
packages/blitz-next/scripts/default-index-browser.js
Normal file
@@ -0,0 +1,3 @@
|
||||
exports.Routes = {
|
||||
ThisFileHasNotYetBeenGeneratedPleaseRunBlitzCodeGen: (query) => ({pathname: "⚡️", query}),
|
||||
}
|
||||
6
packages/blitz-next/scripts/default-index.d.ts
vendored
Normal file
6
packages/blitz-next/scripts/default-index.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type {ParsedUrlQueryInput} from "querystring"
|
||||
import type {UrlObject} from "url"
|
||||
|
||||
export const Routes: {
|
||||
ThisFileHasNotYetBeenGeneratedPleaseRunBlitzCodeGen(query?: ParsedUrlQueryInput): UrlObject
|
||||
}
|
||||
3
packages/blitz-next/scripts/default-index.js
Normal file
3
packages/blitz-next/scripts/default-index.js
Normal file
@@ -0,0 +1,3 @@
|
||||
exports.Routes = {
|
||||
ThisFileHasNotYetBeenGeneratedPleaseRunBlitzCodeGen: (query) => ({pathname: "⚡️", query}),
|
||||
}
|
||||
342
packages/blitz-next/scripts/postinstall.js
Normal file
342
packages/blitz-next/scripts/postinstall.js
Normal file
@@ -0,0 +1,342 @@
|
||||
const childProcess = require("cross-spawn")
|
||||
const {promisify} = require("util")
|
||||
const fs = require("fs")
|
||||
const path = require("path")
|
||||
const resolveFrom = require("resolve-from")
|
||||
const findUp = require("find-up")
|
||||
|
||||
const copyFile = promisify(fs.copyFile)
|
||||
const mkdir = promisify(fs.mkdir)
|
||||
const stat = promisify(fs.stat)
|
||||
|
||||
const debug = require("debug")("blitz:postinstall")
|
||||
|
||||
const isInBlitzMonorepo = fs.existsSync(path.join(__dirname, "../../blitz-next"))
|
||||
let isInstalledGlobally = isInBlitzMonorepo ? false : true // default
|
||||
|
||||
try {
|
||||
const maybeGlobalBlitzPath = resolveFrom(__dirname, "blitz")
|
||||
const localBlitzPath = resolveFrom.silent(process.cwd(), "blitz/dist/index.cjs")
|
||||
isInstalledGlobally = maybeGlobalBlitzPath !== localBlitzPath
|
||||
} catch (error) {
|
||||
// noop
|
||||
}
|
||||
|
||||
// todo: we should reuse `findNodeModulesRoot` from /nextjs/packages/next/build/routes.ts
|
||||
async function findNodeModulesRoot(src) {
|
||||
let root
|
||||
if (isInBlitzMonorepo) {
|
||||
root = path.join(src, "node_modules")
|
||||
} else if (src.includes(".pnpm")) {
|
||||
const blitzPkgLocation = path.dirname(
|
||||
(await findUp("package.json", {
|
||||
cwd: resolveFrom(src, "blitz"),
|
||||
})) || "",
|
||||
)
|
||||
if (!blitzPkgLocation) {
|
||||
throw new Error("Internal Blitz Error: unable to find 'blitz' package location")
|
||||
}
|
||||
root = path.join(blitzPkgLocation, "../../../../")
|
||||
} else {
|
||||
const blitzPkgLocation = path.dirname(
|
||||
(await findUp("package.json", {
|
||||
cwd: resolveFrom(src, "blitz"),
|
||||
})) || "",
|
||||
)
|
||||
if (!blitzPkgLocation) {
|
||||
throw new Error("Internal Blitz Error: unable to find 'blitz' package location")
|
||||
}
|
||||
|
||||
root = path.join(blitzPkgLocation, "../")
|
||||
}
|
||||
return path.join(root, ".blitz")
|
||||
}
|
||||
|
||||
/*
|
||||
Adapted from https://github.com/prisma/prisma/blob/974cbeff4a7f616137ce540d0ec88a2a86365892/src/packages/client/scripts/postinstall.js
|
||||
*/
|
||||
function codegen() {
|
||||
async function main() {
|
||||
if (process.env.INIT_CWD) {
|
||||
process.chdir(process.env.INIT_CWD) // necessary, because npm chooses __dirname as process.cwd()
|
||||
// in the postinstall hook
|
||||
}
|
||||
await ensureEmptyDotBlitz()
|
||||
|
||||
const localPath = getLocalPackagePath()
|
||||
|
||||
// Only execute if !localpath
|
||||
const installedGlobally = localPath ? undefined : await isInstalledGlobally()
|
||||
|
||||
debug({
|
||||
localPath,
|
||||
installedGlobally,
|
||||
init_cwd: process.env.INIT_CWD,
|
||||
})
|
||||
try {
|
||||
if (localPath) {
|
||||
await run("node", [
|
||||
localPath,
|
||||
"codegen",
|
||||
"--postinstall",
|
||||
doubleQuote(getPostInstallTrigger()),
|
||||
])
|
||||
return
|
||||
}
|
||||
|
||||
if (installedGlobally) {
|
||||
await run("blitz", ["codegen", "--postinstall", doubleQuote(getPostInstallTrigger())])
|
||||
return
|
||||
}
|
||||
} catch (e) {
|
||||
// if exit code = 1 do not print
|
||||
if (e && e !== 1) {
|
||||
console.error(e)
|
||||
}
|
||||
debug(e)
|
||||
}
|
||||
|
||||
if (!localPath && !installedGlobally) {
|
||||
console.error(`Please install Blitz CLI. You can install it with "npm add -D blitz".`)
|
||||
}
|
||||
}
|
||||
|
||||
function getLocalPackagePath() {
|
||||
try {
|
||||
const packagePath = require.resolve("blitz/package.json")
|
||||
if (packagePath) {
|
||||
const blitzPkg = require.resolve("blitz/dist/index.cjs")
|
||||
if (blitzPkg.includes(".pnpm")) {
|
||||
return path.join(blitzPkg, "../../../../../../blitz/dist/index.cjs")
|
||||
} else {
|
||||
return path.join(blitzPkg)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
//
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function isInstalledGlobally() {
|
||||
try {
|
||||
await run("blitz", ["-v"], process.cwd(), ["ignore"])
|
||||
return true
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (!process.env.BLITZ_SKIP_POSTINSTALL_GENERATE) {
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e)
|
||||
process.exit(0)
|
||||
})
|
||||
.finally(() => {
|
||||
debug(`postinstall trigger: ${getPostInstallTrigger()}`)
|
||||
})
|
||||
}
|
||||
|
||||
function run(cmd, params, cwd = process.cwd(), stdio = ["pipe", "inherit", "inherit"]) {
|
||||
const child = childProcess.spawn(cmd, params, {
|
||||
stdio,
|
||||
cwd,
|
||||
})
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
child.on("close", () => {
|
||||
resolve()
|
||||
})
|
||||
child.on("exit", (code) => {
|
||||
if (code === 0) {
|
||||
resolve()
|
||||
} else {
|
||||
reject(code)
|
||||
}
|
||||
})
|
||||
child.on("error", () => {
|
||||
reject()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function ensureEmptyDotBlitz() {
|
||||
try {
|
||||
const dotBlitzDir = isInBlitzMonorepo
|
||||
? path.join(process.cwd(), "node_modules/.blitz")
|
||||
: await findNodeModulesRoot(__dirname)
|
||||
|
||||
await makeDir(dotBlitzDir)
|
||||
const defaultIndexJsPath = path.join(dotBlitzDir, "index.js")
|
||||
const defaultIndexBrowserJSPath = path.join(dotBlitzDir, "index-browser.js")
|
||||
const defaultIndexDTSPath = path.join(dotBlitzDir, "index.d.ts")
|
||||
|
||||
if (!fs.existsSync(defaultIndexJsPath)) {
|
||||
await copyFile(path.join(__dirname, "default-index.js"), defaultIndexJsPath)
|
||||
}
|
||||
if (!fs.existsSync(defaultIndexBrowserJSPath)) {
|
||||
await copyFile(path.join(__dirname, "default-index-browser.js"), defaultIndexBrowserJSPath)
|
||||
}
|
||||
|
||||
if (!fs.existsSync(defaultIndexDTSPath)) {
|
||||
await copyFile(path.join(__dirname, "default-index.d.ts"), defaultIndexDTSPath)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
async function makeDir(input) {
|
||||
const make = async (pth) => {
|
||||
try {
|
||||
await mkdir(pth)
|
||||
|
||||
return pth
|
||||
} catch (error) {
|
||||
if (error.code === "EPERM") {
|
||||
throw error
|
||||
}
|
||||
|
||||
if (error.code === "ENOENT") {
|
||||
if (path.dirname(pth) === pth) {
|
||||
throw new Error(`operation not permitted, mkdir '${pth}'`)
|
||||
}
|
||||
|
||||
if (error.message.includes("null bytes")) {
|
||||
throw error
|
||||
}
|
||||
|
||||
await make(path.dirname(pth))
|
||||
|
||||
return make(pth)
|
||||
}
|
||||
|
||||
try {
|
||||
const stats = await stat(pth)
|
||||
if (!stats.isDirectory()) {
|
||||
throw new Error("The path is not a directory")
|
||||
}
|
||||
} catch (_) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return pth
|
||||
}
|
||||
}
|
||||
|
||||
return await make(path.resolve(input))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the command that triggered this postinstall script being run. If there is
|
||||
* an error while attempting to get this value then the string constant
|
||||
* 'ERROR_WHILE_FINDING_POSTINSTALL_TRIGGER' is returned.
|
||||
* This information is just necessary for telemetry.
|
||||
* This get's passed in to Generate, which then automatically get's propagated to telemetry.
|
||||
*/
|
||||
function getPostInstallTrigger() {
|
||||
/*
|
||||
npm_config_argv` is not officially documented so here are our (Prisma's) research notes
|
||||
`npm_config_argv` is available to the postinstall script when the containing package has been installed by npm into some project.
|
||||
An example of its value:
|
||||
```
|
||||
npm_config_argv: '{"remain":["../test"],"cooked":["add","../test"],"original":["add","../test"]}',
|
||||
```
|
||||
We are interesting in the data contained in the "original" field.
|
||||
Trivia/Note: `npm_config_argv` is not available when running e.g. `npm install` on the containing package itself (e.g. when working on it)
|
||||
Yarn mimics this data and environment variable. Here is an example following `yarn add` for the same package:
|
||||
```
|
||||
npm_config_argv: '{"remain":[],"cooked":["add"],"original":["add","../test"]}'
|
||||
```
|
||||
Other package managers like `pnpm` have not been tested.
|
||||
*/
|
||||
|
||||
const maybe_npm_config_argv_string = process.env.npm_config_argv
|
||||
|
||||
if (maybe_npm_config_argv_string === undefined) {
|
||||
return UNABLE_TO_FIND_POSTINSTALL_TRIGGER__ENVAR_MISSING
|
||||
}
|
||||
|
||||
let npm_config_argv
|
||||
try {
|
||||
npm_config_argv = JSON.parse(maybe_npm_config_argv_string)
|
||||
} catch (e) {
|
||||
return `${UNABLE_TO_FIND_POSTINSTALL_TRIGGER_JSON_PARSE_ERROR}: ${maybe_npm_config_argv_string}`
|
||||
}
|
||||
|
||||
if (typeof npm_config_argv !== "object" || npm_config_argv === null) {
|
||||
return `${UNABLE_TO_FIND_POSTINSTALL_TRIGGER_JSON_SCHEMA_ERROR}: ${maybe_npm_config_argv_string}`
|
||||
}
|
||||
|
||||
const npm_config_arv_original_arr = npm_config_argv.original
|
||||
|
||||
if (!Array.isArray(npm_config_arv_original_arr)) {
|
||||
return `${UNABLE_TO_FIND_POSTINSTALL_TRIGGER_JSON_SCHEMA_ERROR}: ${maybe_npm_config_argv_string}`
|
||||
}
|
||||
|
||||
const npm_config_arv_original = npm_config_arv_original_arr
|
||||
.filter((arg) => arg !== "")
|
||||
.join(" ")
|
||||
|
||||
const command =
|
||||
npm_config_arv_original === ""
|
||||
? getPackageManagerName()
|
||||
: [getPackageManagerName(), npm_config_arv_original].join(" ")
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap double quotes around the given string.
|
||||
*/
|
||||
function doubleQuote(x) {
|
||||
return `"${x}"`
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the package manager name currently being used. If parsing fails, then the following pattern is returned:
|
||||
* UNKNOWN_NPM_CONFIG_USER_AGENT(<string received>).
|
||||
*/
|
||||
function getPackageManagerName() {
|
||||
const userAgent = process.env.npm_config_user_agent
|
||||
if (!userAgent) return "MISSING_NPM_CONFIG_USER_AGENT"
|
||||
|
||||
const name = parsePackageManagerName(userAgent)
|
||||
if (!name) return `UNKNOWN_NPM_CONFIG_USER_AGENT(${userAgent})`
|
||||
|
||||
return name
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse package manager name from useragent. If parsing fails, `null` is returned.
|
||||
*/
|
||||
function parsePackageManagerName(userAgent) {
|
||||
let packageManager = null
|
||||
|
||||
// example: 'yarn/1.22.4 npm/? node/v13.11.0 darwin x64'
|
||||
// References:
|
||||
// - https://pnpm.js.org/en/3.6/only-allow-pnpm
|
||||
// - https://github.com/cameronhunter/npm-config-user-agent-parser
|
||||
if (userAgent) {
|
||||
const matchResult = userAgent.match(/^([^/]+)\/.+/)
|
||||
if (matchResult) {
|
||||
packageManager = matchResult[1].trim()
|
||||
}
|
||||
}
|
||||
|
||||
return packageManager
|
||||
}
|
||||
|
||||
// prettier-ignore
|
||||
const UNABLE_TO_FIND_POSTINSTALL_TRIGGER__ENVAR_MISSING = 'UNABLE_TO_FIND_POSTINSTALL_TRIGGER__ENVAR_MISSING'
|
||||
// prettier-ignore
|
||||
const UNABLE_TO_FIND_POSTINSTALL_TRIGGER_JSON_PARSE_ERROR = 'UNABLE_TO_FIND_POSTINSTALL_TRIGGER_JSON_PARSE_ERROR'
|
||||
// prettier-ignore
|
||||
const UNABLE_TO_FIND_POSTINSTALL_TRIGGER_JSON_SCHEMA_ERROR = 'UNABLE_TO_FIND_POSTINSTALL_TRIGGER_JSON_SCHEMA_ERROR'
|
||||
}
|
||||
|
||||
// if (!isInstalledGlobally) {
|
||||
codegen()
|
||||
// }
|
||||
@@ -10,9 +10,11 @@ import Head from "next/head"
|
||||
import React from "react"
|
||||
import {QueryClient, QueryClientProvider} from "react-query"
|
||||
import {Hydrate, HydrateOptions} from "react-query/hydration"
|
||||
import {withSuperJSONPage} from "./superjson"
|
||||
|
||||
export * from "./error-boundary"
|
||||
export * from "./error-component"
|
||||
export {Routes} from ".blitz"
|
||||
|
||||
const compose =
|
||||
(...rest: BlitzProviderType[]) =>
|
||||
@@ -46,7 +48,7 @@ const buildWithBlitz = <TPlugins extends readonly ClientPlugin<object>[]>(plugin
|
||||
</BlitzProvider>
|
||||
)
|
||||
}
|
||||
return BlitzOuterRoot
|
||||
return withSuperJSONPage(BlitzOuterRoot)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +90,7 @@ export type PluginsExports<TPlugins extends readonly ClientPlugin<object>[]> = S
|
||||
>
|
||||
>
|
||||
|
||||
const setupClient = <TPlugins extends readonly ClientPlugin<object>[]>({
|
||||
const setupBlitzClient = <TPlugins extends readonly ClientPlugin<object>[]>({
|
||||
plugins,
|
||||
}: {
|
||||
plugins: TPlugins
|
||||
@@ -121,7 +123,7 @@ const setupClient = <TPlugins extends readonly ClientPlugin<object>[]>({
|
||||
}
|
||||
}
|
||||
|
||||
export {setupClient}
|
||||
export {setupBlitzClient}
|
||||
|
||||
const customCSS = `
|
||||
body::before {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {GetServerSideProps, GetStaticProps, NextApiRequest, NextApiResponse} from "next"
|
||||
import type {Ctx as BlitzCtx, BlitzServerPlugin, Middleware, MiddlewareResponse} from "blitz"
|
||||
import {handleRequestWithMiddleware} from "blitz"
|
||||
import {withSuperJSONPropsGsp, withSuperJSONPropsGssp} from "./superjson"
|
||||
|
||||
export * from "./index-browser"
|
||||
|
||||
@@ -27,10 +28,10 @@ export type BlitzGSSPHandler<TProps> = ({
|
||||
...args
|
||||
}: Parameters<GetServerSideProps<TProps>>[0] & {ctx: Ctx}) => ReturnType<GetServerSideProps<TProps>>
|
||||
|
||||
export type BlitzGSPHandler = ({
|
||||
export type BlitzGSPHandler<TProps> = ({
|
||||
ctx,
|
||||
...args
|
||||
}: Parameters<GetStaticProps>[0] & {ctx: Ctx}) => ReturnType<GetServerSideProps>
|
||||
}: Parameters<GetStaticProps<TProps>>[0] & {ctx: Ctx}) => ReturnType<GetStaticProps<TProps>>
|
||||
|
||||
export type BlitzAPIHandler = (
|
||||
req: Parameters<NextApiHandler>[0],
|
||||
@@ -38,27 +39,25 @@ export type BlitzAPIHandler = (
|
||||
ctx: Ctx,
|
||||
) => ReturnType<NextApiHandler>
|
||||
|
||||
export const setupBlitz = ({plugins}: SetupBlitzOptions) => {
|
||||
export const setupBlitzServer = ({plugins}: SetupBlitzOptions) => {
|
||||
const middlewares = plugins.flatMap((p) => p.middlewares)
|
||||
const contextMiddleware = plugins.flatMap((p) => p.contextMiddleware).filter(Boolean)
|
||||
|
||||
const gSSP =
|
||||
<TProps>(handler: BlitzGSSPHandler<TProps>): GetServerSideProps<TProps> =>
|
||||
async ({req, res, ...rest}) => {
|
||||
const gSSP = <TProps>(handler: BlitzGSSPHandler<TProps>): GetServerSideProps<TProps> =>
|
||||
withSuperJSONPropsGssp<TProps>(async ({req, res, ...rest}) => {
|
||||
await handleRequestWithMiddleware(req, res, middlewares)
|
||||
const ctx = contextMiddleware.reduceRight(
|
||||
(y, f) => (f ? f(y) : y),
|
||||
(res as MiddlewareResponse).blitzCtx,
|
||||
)
|
||||
return handler({req, res, ctx, ...rest})
|
||||
}
|
||||
})
|
||||
|
||||
const gSP =
|
||||
(handler: BlitzGSPHandler): GetStaticProps =>
|
||||
async (context) => {
|
||||
const gSP = <TProps>(handler: BlitzGSPHandler<TProps>): GetStaticProps<TProps> =>
|
||||
withSuperJSONPropsGsp<TProps>(async (context) => {
|
||||
const ctx = contextMiddleware.reduceRight((y, f) => (f ? f(y) : y), {} as Ctx)
|
||||
return handler({...context, ctx: ctx})
|
||||
}
|
||||
})
|
||||
|
||||
const api =
|
||||
(handler: BlitzAPIHandler): NextApiHandler =>
|
||||
|
||||
89
packages/blitz-next/src/superjson.tsx
Normal file
89
packages/blitz-next/src/superjson.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import hoistNonReactStatics from "hoist-non-react-statics"
|
||||
import type {
|
||||
GetServerSideProps,
|
||||
GetServerSidePropsResult,
|
||||
GetStaticProps,
|
||||
GetStaticPropsResult,
|
||||
} from "next"
|
||||
import * as React from "react"
|
||||
import SuperJSON from "superjson"
|
||||
|
||||
export type SuperJSONProps<P = any> = P & {
|
||||
_superjson?: any
|
||||
}
|
||||
|
||||
function excludeProps<P>(
|
||||
result: GetServerSidePropsResult<P> | GetStaticPropsResult<P>,
|
||||
exclude: string[] = [],
|
||||
) {
|
||||
if (!("props" in result)) {
|
||||
return result
|
||||
}
|
||||
|
||||
if (!result.props) {
|
||||
return result
|
||||
}
|
||||
|
||||
const excludedPropValues = exclude.map((propKey) => {
|
||||
const value = (result.props as any)[propKey]
|
||||
delete (result.props as any)[propKey]
|
||||
return value
|
||||
})
|
||||
|
||||
const {json, meta} = SuperJSON.serialize(result.props)
|
||||
const props = json as any
|
||||
|
||||
if (meta) {
|
||||
props._superjson = meta
|
||||
}
|
||||
|
||||
exclude.forEach((key, index) => {
|
||||
const excludedPropValue = excludedPropValues[index]
|
||||
if (typeof excludedPropValue !== "undefined") {
|
||||
props[key] = excludedPropValue
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
...result,
|
||||
props,
|
||||
}
|
||||
}
|
||||
|
||||
export function withSuperJSONPropsGssp<P>(
|
||||
handler: GetServerSideProps<P>,
|
||||
exclude: string[] = [],
|
||||
): GetServerSideProps<SuperJSONProps<P>> {
|
||||
return async function withSuperJSON(...args) {
|
||||
const result = await handler(...args)
|
||||
return excludeProps(result, exclude)
|
||||
}
|
||||
}
|
||||
|
||||
export function withSuperJSONPropsGsp<P>(
|
||||
handler: GetStaticProps<P>,
|
||||
exclude: string[] = [],
|
||||
): GetStaticProps<P> {
|
||||
return async function withSuperJSON(...args) {
|
||||
const result = await handler(...args)
|
||||
|
||||
return excludeProps<any>(result, exclude)
|
||||
}
|
||||
}
|
||||
|
||||
export function deserializeProps<P>(serializedProps: SuperJSONProps<P>): P {
|
||||
const {_superjson, ...props} = serializedProps
|
||||
return SuperJSON.deserialize({json: props as any, meta: _superjson})
|
||||
}
|
||||
|
||||
export function withSuperJSONPage<P>(
|
||||
Page: React.ComponentType<P>,
|
||||
): React.ComponentType<SuperJSONProps<P>> {
|
||||
function WithSuperJSON(serializedProps: SuperJSONProps<P>) {
|
||||
return <Page {...deserializeProps<P>(serializedProps)} />
|
||||
}
|
||||
|
||||
hoistNonReactStatics(WithSuperJSON, Page)
|
||||
|
||||
return WithSuperJSON
|
||||
}
|
||||
@@ -1,5 +1,129 @@
|
||||
# @blitzjs/rpc
|
||||
|
||||
## 2.0.0-alpha.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.21
|
||||
- @blitzjs/auth@2.0.0-alpha.21
|
||||
|
||||
## 2.0.0-alpha.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- testing set dist-tag
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.20
|
||||
- @blitzjs/auth@2.0.0-alpha.20
|
||||
|
||||
## 2.0.0-alpha.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.19
|
||||
- @blitzjs/auth@2.0.0-alpha.19
|
||||
|
||||
## 2.0.0-alpha.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.18
|
||||
- @blitzjs/auth@2.0.0-alpha.18
|
||||
|
||||
## 2.0.0-alpha.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.17
|
||||
- @blitzjs/auth@2.0.0-alpha.17
|
||||
|
||||
## 2.0.0-alpha.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.16
|
||||
- @blitzjs/auth@2.0.0-alpha.16
|
||||
|
||||
## 2.0.0-alpha.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.15
|
||||
- @blitzjs/auth@2.0.0-alpha.15
|
||||
|
||||
## 2.0.0-alpha.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.14
|
||||
- @blitzjs/auth@2.0.0-alpha.14
|
||||
|
||||
## 2.0.0-alpha.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.13
|
||||
- @blitzjs/auth@2.0.0-alpha.13
|
||||
|
||||
## 2.0.0-alpha.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.12
|
||||
- @blitzjs/auth@2.0.0-alpha.12
|
||||
|
||||
## 2.0.0-alpha.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/auth@2.0.0-alpha.11
|
||||
- blitz@2.0.0-alpha.11
|
||||
|
||||
## 2.0.0-alpha.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.10
|
||||
- @blitzjs/auth@2.0.0-alpha.10
|
||||
|
||||
## 2.0.0-alpha.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.9
|
||||
- @blitzjs/auth@2.0.0-alpha.9
|
||||
|
||||
## 2.0.0-alpha.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.8
|
||||
- @blitzjs/auth@2.0.0-alpha.8
|
||||
|
||||
## 2.0.0-alpha.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.7
|
||||
- @blitzjs/auth@2.0.0-alpha.7
|
||||
|
||||
## 2.0.0-alpha.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fix route manifest codegen
|
||||
- Updated dependencies
|
||||
- blitz@2.0.0-alpha.6
|
||||
- @blitzjs/auth@2.0.0-alpha.6
|
||||
|
||||
## 2.0.0-alpha.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@blitzjs/rpc",
|
||||
"version": "2.0.0-alpha.5",
|
||||
"version": "2.0.0-alpha.21",
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"predev": "wait-on -d 250 ../blitz/dist/index-server.d.ts && wait-on -d 250 ../blitz-auth/dist/index-browser.d.ts",
|
||||
@@ -20,21 +20,22 @@
|
||||
"dist/**"
|
||||
],
|
||||
"dependencies": {
|
||||
"@blitzjs/auth": "2.0.0-alpha.5",
|
||||
"@blitzjs/auth": "2.0.0-alpha.21",
|
||||
"b64-lite": "1.4.0",
|
||||
"bad-behavior": "1.0.1",
|
||||
"chalk": "^4.1.0",
|
||||
"debug": "4.3.3",
|
||||
"react-query": "3.21.1",
|
||||
"superjson": "1.8.0"
|
||||
"superjson": "1.8.0",
|
||||
"zod": "3.10.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.21",
|
||||
"@types/debug": "4.1.7",
|
||||
"@types/react": "17.0.43",
|
||||
"@types/react-dom": "17.0.14",
|
||||
"blitz": "2.0.0-alpha.5",
|
||||
"next": "12.1.1",
|
||||
"blitz": "2.0.0-alpha.21",
|
||||
"next": "12.1.6-canary.17",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"typescript": "^4.5.3",
|
||||
@@ -42,7 +43,7 @@
|
||||
"watch": "1.0.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"blitz": "2.0.0-alpha.5",
|
||||
"blitz": "2.0.0-alpha.21",
|
||||
"next": "*"
|
||||
},
|
||||
"publishConfig": {
|
||||
|
||||
@@ -99,7 +99,10 @@ export function useQuery<
|
||||
(!options || !("suspense" in options) || options.suspense) &&
|
||||
(!options || !("enabled" in options) || options.enabled)
|
||||
) {
|
||||
throw new Promise(() => {})
|
||||
const e = new Error()
|
||||
e.name = "Rendering Suspense fallback..."
|
||||
delete e.stack
|
||||
throw e
|
||||
}
|
||||
|
||||
const rest = {
|
||||
@@ -182,7 +185,10 @@ export function usePaginatedQuery<
|
||||
(!options || !("suspense" in options) || options.suspense) &&
|
||||
(!options || !("enabled" in options) || options.enabled)
|
||||
) {
|
||||
throw new Promise(() => {})
|
||||
const e = new Error()
|
||||
e.name = "Rendering Suspense fallback..."
|
||||
delete e.stack
|
||||
throw e
|
||||
}
|
||||
|
||||
const rest = {
|
||||
@@ -278,7 +284,10 @@ export function useInfiniteQuery<
|
||||
(!options || !("suspense" in options) || options.suspense) &&
|
||||
(!options || !("enabled" in options) || options.enabled)
|
||||
) {
|
||||
throw new Promise(() => {})
|
||||
const e = new Error()
|
||||
e.name = "Rendering Suspense fallback..."
|
||||
delete e.stack
|
||||
throw e
|
||||
}
|
||||
|
||||
const rest = {
|
||||
|
||||
@@ -6,6 +6,8 @@ import chalk from "chalk"
|
||||
// TODO - optimize end user server bundles by not exporting all client stuff here
|
||||
export * from "./index-browser"
|
||||
|
||||
export * from "./resolver"
|
||||
|
||||
// Mechanism used by Vite/Next/Nuxt plugins for automatically loading query and mutation resolvers
|
||||
function isObject(value: unknown): value is Record<string | symbol, unknown> {
|
||||
return typeof value === "object" && value !== null
|
||||
|
||||
63
packages/blitz-rpc/src/resolver.test.ts
Normal file
63
packages/blitz-rpc/src/resolver.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import {Ctx} from "blitz"
|
||||
import {describe, it, expect} from "vitest"
|
||||
import {z} from "zod"
|
||||
import {ParserType, resolver} from "./resolver"
|
||||
|
||||
describe("resolver", () => {
|
||||
it("should typecheck and pass along value", async () => {
|
||||
await resolverTest({})
|
||||
})
|
||||
it("should typecheck and pass along value if sync resolver is specified", async () => {
|
||||
await resolverTest({type: "sync"})
|
||||
})
|
||||
it("should typecheck and pass along value if async resolver is specified", async () => {
|
||||
await resolverTest({type: "async"})
|
||||
})
|
||||
})
|
||||
|
||||
const syncResolver = resolver.pipe(
|
||||
resolver.zod(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
}),
|
||||
"sync",
|
||||
),
|
||||
resolver.authorize({}),
|
||||
(input) => {
|
||||
return input.email
|
||||
},
|
||||
)
|
||||
|
||||
const asyncResolver = resolver.pipe(
|
||||
resolver.zod(
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
}),
|
||||
"async",
|
||||
),
|
||||
resolver.authorize({}),
|
||||
(input) => {
|
||||
return input.email
|
||||
},
|
||||
)
|
||||
|
||||
const resolverTest = async ({type}: {type?: ParserType}) => {
|
||||
const resolver1 = type === "sync" ? syncResolver : asyncResolver
|
||||
|
||||
const result1 = await resolver1(
|
||||
{email: "test@example.com"},
|
||||
{session: {$authorize: () => undefined} as Ctx},
|
||||
)
|
||||
expect(result1).toBe("test@example.com")
|
||||
|
||||
const resolver2 = resolver.pipe(
|
||||
/*resolver.authorize(), */ (input: {email: string}) => {
|
||||
return input.email
|
||||
},
|
||||
)
|
||||
const result2 = await resolver2(
|
||||
{email: "test@example.com"},
|
||||
{session: {$authorize: () => undefined} as Ctx},
|
||||
)
|
||||
expect(result2).toBe("test@example.com")
|
||||
}
|
||||
321
packages/blitz-rpc/src/resolver.ts
Normal file
321
packages/blitz-rpc/src/resolver.ts
Normal file
@@ -0,0 +1,321 @@
|
||||
import {AuthenticatedSessionContext, SessionContext, SessionContextBase} from "@blitzjs/auth"
|
||||
import {Await, Ctx, EnsurePromise} from "blitz"
|
||||
import type {input as zInput, output as zOutput, ZodTypeAny} from "zod"
|
||||
|
||||
export type ParserType = "sync" | "async"
|
||||
|
||||
interface ResultWithContext<Result = unknown, Context = unknown> {
|
||||
__blitz: true
|
||||
value: Result
|
||||
ctx: Context
|
||||
}
|
||||
function isResultWithContext(x: unknown): x is ResultWithContext {
|
||||
return (
|
||||
typeof x === "object" && x !== null && "ctx" in x && (x as ResultWithContext).__blitz === true
|
||||
)
|
||||
}
|
||||
|
||||
export interface AuthenticatedMiddlewareCtx extends Omit<Ctx, "session"> {
|
||||
session: AuthenticatedSessionContext
|
||||
}
|
||||
|
||||
type PipeFn<Prev, Next, PrevCtx, NextCtx = PrevCtx> = (
|
||||
i: Await<Prev>,
|
||||
c: PrevCtx,
|
||||
) => Next extends ResultWithContext ? never : Next | ResultWithContext<Next, NextCtx>
|
||||
|
||||
function pipe<A, Z>(ab: (i: A, c: Ctx) => Z): (input: A, ctx: Ctx) => EnsurePromise<Z>
|
||||
function pipe<A, B, C, CA = Ctx, CB = CA, CC = CB>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<C>
|
||||
function pipe<A, B, C, D, CA = Ctx, CB = CA, CC = CB, CD = CC>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<D>
|
||||
function pipe<A, B, C, D, E, CA = Ctx, CB = CA, CC = CB, CD = CC, CE = CD>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<E>
|
||||
function pipe<A, B, C, D, E, F, CA = Ctx, CB = CA, CC = CB, CD = CC, CE = CD, CF = CE>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<F>
|
||||
function pipe<A, B, C, D, E, F, G, CA = Ctx, CB = CA, CC = CB, CD = CC, CE = CD, CF = CE, CG = CF>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
fg: PipeFn<F, G, CF, CG>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<CG>
|
||||
function pipe<
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
CA = Ctx,
|
||||
CB = CA,
|
||||
CC = CB,
|
||||
CD = CC,
|
||||
CE = CD,
|
||||
CF = CE,
|
||||
CG = CF,
|
||||
CH = CG,
|
||||
>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
fg: PipeFn<F, G, CF, CG>,
|
||||
gh: PipeFn<G, H, CG, CH>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<H>
|
||||
function pipe<
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
CA = Ctx,
|
||||
CB = CA,
|
||||
CC = CB,
|
||||
CD = CC,
|
||||
CE = CD,
|
||||
CF = CE,
|
||||
CG = CF,
|
||||
CH = CG,
|
||||
CI = CH,
|
||||
>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
fg: PipeFn<F, G, CF, CG>,
|
||||
gh: PipeFn<G, H, CG, CH>,
|
||||
hi: PipeFn<H, I, CH, CI>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<I>
|
||||
function pipe<
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
J,
|
||||
CA = Ctx,
|
||||
CB = CA,
|
||||
CC = CB,
|
||||
CD = CC,
|
||||
CE = CD,
|
||||
CF = CE,
|
||||
CG = CF,
|
||||
CH = CG,
|
||||
CI = CH,
|
||||
CJ = CI,
|
||||
>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
fg: PipeFn<F, G, CF, CG>,
|
||||
gh: PipeFn<G, H, CG, CH>,
|
||||
hi: PipeFn<H, I, CH, CI>,
|
||||
ij: PipeFn<I, J, CI, CJ>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<J>
|
||||
function pipe<
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
J,
|
||||
K,
|
||||
CA = Ctx,
|
||||
CB = CA,
|
||||
CC = CB,
|
||||
CD = CC,
|
||||
CE = CD,
|
||||
CF = CE,
|
||||
CG = CF,
|
||||
CH = CG,
|
||||
CI = CH,
|
||||
CJ = CI,
|
||||
CK = CJ,
|
||||
>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
fg: PipeFn<F, G, CF, CG>,
|
||||
gh: PipeFn<G, H, CG, CH>,
|
||||
hi: PipeFn<H, I, CH, CI>,
|
||||
ij: PipeFn<I, J, CI, CJ>,
|
||||
jk: PipeFn<J, K, CJ, CK>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<K>
|
||||
function pipe<
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
J,
|
||||
K,
|
||||
L,
|
||||
CA = Ctx,
|
||||
CB = CA,
|
||||
CC = CB,
|
||||
CD = CC,
|
||||
CE = CD,
|
||||
CF = CE,
|
||||
CG = CF,
|
||||
CH = CG,
|
||||
CI = CH,
|
||||
CJ = CI,
|
||||
CK = CJ,
|
||||
CL = CK,
|
||||
>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
fg: PipeFn<F, G, CF, CG>,
|
||||
gh: PipeFn<G, H, CG, CH>,
|
||||
hi: PipeFn<H, I, CH, CI>,
|
||||
ij: PipeFn<I, J, CI, CJ>,
|
||||
jk: PipeFn<J, K, CJ, CK>,
|
||||
kl: PipeFn<K, L, CK, CL>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<L>
|
||||
function pipe<
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
J,
|
||||
K,
|
||||
L,
|
||||
M,
|
||||
CA = Ctx,
|
||||
CB = CA,
|
||||
CC = CB,
|
||||
CD = CC,
|
||||
CE = CD,
|
||||
CF = CE,
|
||||
CG = CF,
|
||||
CH = CG,
|
||||
CI = CH,
|
||||
CJ = CI,
|
||||
CK = CJ,
|
||||
CL = CK,
|
||||
CM = CL,
|
||||
>(
|
||||
ab: PipeFn<A, B, CA, CB>,
|
||||
bc: PipeFn<B, C, CB, CC>,
|
||||
cd: PipeFn<C, D, CC, CD>,
|
||||
de: PipeFn<D, E, CD, CE>,
|
||||
ef: PipeFn<E, F, CE, CF>,
|
||||
fg: PipeFn<F, G, CF, CG>,
|
||||
gh: PipeFn<G, H, CG, CH>,
|
||||
hi: PipeFn<H, I, CH, CI>,
|
||||
ij: PipeFn<I, J, CI, CJ>,
|
||||
jk: PipeFn<J, K, CJ, CK>,
|
||||
kl: PipeFn<K, L, CK, CL>,
|
||||
lm: PipeFn<L, M, CL, CM>,
|
||||
): (input: A, ctx: CA) => EnsurePromise<M>
|
||||
function pipe(...args: unknown[]): unknown {
|
||||
const functions = args as PipeFn<unknown, unknown, Ctx>[]
|
||||
|
||||
return async function (input: unknown, ctx: Ctx) {
|
||||
let lastResult = input
|
||||
for (let fn of functions) {
|
||||
lastResult = await fn(lastResult, ctx)
|
||||
if (isResultWithContext(lastResult)) {
|
||||
ctx = lastResult.ctx as Ctx
|
||||
lastResult = lastResult.value
|
||||
}
|
||||
}
|
||||
return lastResult
|
||||
}
|
||||
}
|
||||
|
||||
interface ResolverAuthorize {
|
||||
<T, C = Ctx>(...args: Parameters<SessionContextBase["$authorize"]>): (
|
||||
input: T,
|
||||
ctx: C,
|
||||
) => ResultWithContext<T, AuthenticatedMiddlewareCtx>
|
||||
}
|
||||
|
||||
const authorize: ResolverAuthorize = (...args) => {
|
||||
return function _innerAuthorize(input, ctx) {
|
||||
const session: SessionContext = (ctx as any).session
|
||||
session.$authorize(...args)
|
||||
return {
|
||||
__blitz: true,
|
||||
value: input,
|
||||
// we could use {...ctx, session} instead of `as any` just for TypeScript's sake
|
||||
ctx: ctx as any,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function zod<Schema extends ZodTypeAny, InputType = zInput<Schema>, OutputType = zOutput<Schema>>(
|
||||
schema: Schema,
|
||||
parserType: "sync",
|
||||
): (input: InputType) => OutputType
|
||||
function zod<Schema extends ZodTypeAny, InputType = zInput<Schema>, OutputType = zOutput<Schema>>(
|
||||
schema: Schema,
|
||||
parserType: "async",
|
||||
): (input: InputType) => Promise<OutputType>
|
||||
function zod<Schema extends ZodTypeAny, InputType = zInput<Schema>, OutputType = zOutput<Schema>>(
|
||||
schema: Schema,
|
||||
): (input: InputType) => Promise<OutputType>
|
||||
function zod<Schema extends ZodTypeAny, InputType = zInput<Schema>, OutputType = zOutput<Schema>>(
|
||||
schema: Schema,
|
||||
parserType: ParserType = "async",
|
||||
) {
|
||||
if (parserType === "sync") {
|
||||
return (input: InputType): OutputType => schema.parse(input)
|
||||
} else {
|
||||
return (input: InputType): Promise<OutputType> => schema.parseAsync(input)
|
||||
}
|
||||
}
|
||||
|
||||
export const resolver = {
|
||||
pipe,
|
||||
zod,
|
||||
authorize,
|
||||
}
|
||||
20
packages/blitz-rpc/test/blitz-test-utils.ts
Normal file
20
packages/blitz-rpc/test/blitz-test-utils.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
// This enhance fn does what buildRpcFunction does during build time
|
||||
export function buildQueryRpc(fn: any) {
|
||||
const newFn = (...args: any) => {
|
||||
const [data, ...rest] = args
|
||||
return fn(data, ...rest)
|
||||
}
|
||||
newFn._isRpcClient = true
|
||||
newFn._resolverType = "query"
|
||||
newFn._routePath = "/api/test/url/" + Math.random()
|
||||
return newFn
|
||||
}
|
||||
|
||||
// This enhance fn does what buildRpcFunction does during build time
|
||||
export function buildMutationRpc(fn: any) {
|
||||
const newFn = (...args: any) => fn(...args)
|
||||
newFn._isRpcClient = true
|
||||
newFn._resolverType = "mutation"
|
||||
newFn._routePath = "/api/test/url"
|
||||
return newFn
|
||||
}
|
||||
98
packages/blitz-rpc/test/unit/react-query-utils.unit.test.ts
Normal file
98
packages/blitz-rpc/test/unit/react-query-utils.unit.test.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import {assert, expect, test, beforeEach, describe, spyOn, it} from "vitest"
|
||||
|
||||
import {queryClient, invalidateQuery, setQueryData} from "../../src/data-client"
|
||||
|
||||
import {getQueryCacheFunctions} from "../../src/data-client/react-query-utils"
|
||||
import {buildQueryRpc} from "../blitz-test-utils"
|
||||
|
||||
// eslint-disable-next-line require-await
|
||||
const isEmpty = async (arg: string): Promise<boolean> => {
|
||||
return Boolean(arg)
|
||||
}
|
||||
|
||||
describe("getQueryCacheFunctions", () => {
|
||||
const spyRefetchQueries = spyOn(queryClient, "invalidateQueries")
|
||||
|
||||
beforeEach(() => {
|
||||
spyRefetchQueries.mockReset()
|
||||
})
|
||||
|
||||
it("returns a setQueryData function with working options", async () => {
|
||||
window.requestIdleCallback = undefined as any
|
||||
|
||||
const {setQueryData} = getQueryCacheFunctions(buildQueryRpc(isEmpty), "a")
|
||||
expect(setQueryData).toBeTruthy()
|
||||
await setQueryData(true)
|
||||
expect(spyRefetchQueries).toBeCalledTimes(1)
|
||||
await setQueryData(true, {refetch: false})
|
||||
expect(spyRefetchQueries).toBeCalledTimes(1)
|
||||
await setQueryData(true, {refetch: true})
|
||||
expect(spyRefetchQueries).toBeCalledTimes(2)
|
||||
})
|
||||
|
||||
it("works even when requestIdleCallback is undefined", async () => {
|
||||
window.requestIdleCallback = undefined as any
|
||||
const {setQueryData} = getQueryCacheFunctions(buildQueryRpc(isEmpty), "a")
|
||||
expect(setQueryData).toBeTruthy()
|
||||
await setQueryData(true)
|
||||
expect(spyRefetchQueries).toBeCalledTimes(1)
|
||||
await setQueryData(true, {refetch: false})
|
||||
expect(spyRefetchQueries).toBeCalledTimes(1)
|
||||
await setQueryData(true, {refetch: true})
|
||||
expect(spyRefetchQueries).toBeCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe("invalidateQuery", () => {
|
||||
const spyRefetchQueries = spyOn(queryClient, "invalidateQueries")
|
||||
|
||||
beforeEach(() => {
|
||||
spyRefetchQueries.mockReset()
|
||||
})
|
||||
|
||||
it("invalidates a query given resolver and params", async () => {
|
||||
await invalidateQuery(buildQueryRpc(isEmpty), "a")
|
||||
expect(spyRefetchQueries).toBeCalledTimes(1)
|
||||
const calledWith = spyRefetchQueries.mock.calls[0][0] as any
|
||||
// json of the queryKey is "a"
|
||||
expect(calledWith[1].json).toEqual("a")
|
||||
})
|
||||
})
|
||||
|
||||
describe("setQueryData", () => {
|
||||
const spyRefetchQueries = spyOn(queryClient, "invalidateQueries")
|
||||
const spySetQueryData = spyOn(queryClient, "setQueryData")
|
||||
|
||||
beforeEach(() => {
|
||||
spyRefetchQueries.mockReset()
|
||||
spySetQueryData.mockReset()
|
||||
})
|
||||
|
||||
it("without refetch will not invalidate queries", async () => {
|
||||
await setQueryData(buildQueryRpc(isEmpty), "params", "newValue", {
|
||||
refetch: false,
|
||||
})
|
||||
expect(spyRefetchQueries).toBeCalledTimes(0)
|
||||
expect(spySetQueryData).toBeCalledTimes(1)
|
||||
|
||||
const calledWith = spySetQueryData.mock.calls[0] as Array<any>
|
||||
expect(calledWith[0][1].json).toEqual("params")
|
||||
expect(calledWith[1]).toEqual("newValue")
|
||||
})
|
||||
|
||||
it("will invalidate queries by default", async () => {
|
||||
await setQueryData(buildQueryRpc(isEmpty), "params", "newValue")
|
||||
expect(spyRefetchQueries).toBeCalledTimes(1)
|
||||
expect(spySetQueryData).toBeCalledTimes(1)
|
||||
|
||||
const invalidateCalledWith = spyRefetchQueries.mock.calls[0][0] as any
|
||||
expect(invalidateCalledWith[1].json).toEqual("params")
|
||||
|
||||
const calledWith = spySetQueryData.mock.calls[0] as Array<any>
|
||||
expect(calledWith[0][1].json).toEqual("params")
|
||||
expect(calledWith[1]).toEqual("newValue")
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,119 @@
|
||||
# blitz
|
||||
|
||||
## 2.0.0-alpha.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/generator@2.0.0-alpha.21
|
||||
|
||||
## 2.0.0-alpha.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- testing set dist-tag
|
||||
- @blitzjs/generator@2.0.0-alpha.20
|
||||
|
||||
## 2.0.0-alpha.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [63605961]
|
||||
- @blitzjs/generator@2.0.0-alpha.19
|
||||
|
||||
## 2.0.0-alpha.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fix generate cli command
|
||||
- @blitzjs/generator@2.0.0-alpha.18
|
||||
|
||||
## 2.0.0-alpha.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/generator@2.0.0-alpha.17
|
||||
|
||||
## 2.0.0-alpha.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- remove console logs inside onPostInstall in the new cli command
|
||||
- @blitzjs/generator@2.0.0-alpha.16
|
||||
|
||||
## 2.0.0-alpha.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/generator@2.0.0-alpha.15
|
||||
|
||||
## 2.0.0-alpha.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- set default enviornment variable to development unless build and start command
|
||||
- @blitzjs/generator@2.0.0-alpha.14
|
||||
|
||||
## 2.0.0-alpha.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix codegen and postinstall to make work with pnpm
|
||||
- Updated dependencies
|
||||
- @blitzjs/generator@2.0.0-alpha.13
|
||||
|
||||
## 2.0.0-alpha.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Use alpha version for blitz dependency, fix package manager selection
|
||||
- Updated dependencies
|
||||
- @blitzjs/generator@2.0.0-alpha.12
|
||||
|
||||
## 2.0.0-alpha.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/generator@2.0.0-alpha.11
|
||||
|
||||
## 2.0.0-alpha.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies
|
||||
- @blitzjs/generator@2.0.0-alpha.10
|
||||
|
||||
## 2.0.0-alpha.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- add @blitzjs/generator as external
|
||||
- @blitzjs/generator@2.0.0-alpha.9
|
||||
|
||||
## 2.0.0-alpha.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fix broken cli versioning
|
||||
- @blitzjs/generator@2.0.0-alpha.8
|
||||
|
||||
## 2.0.0-alpha.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- added index.cjs to blitz externals
|
||||
- @blitzjs/generator@2.0.0-alpha.7
|
||||
|
||||
## 2.0.0-alpha.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fix route manifest codegen
|
||||
- Updated dependencies
|
||||
- @blitzjs/generator@2.0.0-alpha.6
|
||||
|
||||
## 2.0.0-alpha.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -2,7 +2,7 @@ import {BuildConfig} from "unbuild"
|
||||
|
||||
const config: BuildConfig = {
|
||||
entries: ["./src/index-browser", "./src/index-server", "./src/cli/index"],
|
||||
externals: ["index-browser.cjs", "index-browser.mjs", "zod"],
|
||||
externals: ["index-browser.cjs", "index-browser.mjs", "index.cjs", "zod"],
|
||||
declaration: true,
|
||||
rollup: {
|
||||
emitCJS: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "blitz",
|
||||
"version": "2.0.0-alpha.5",
|
||||
"version": "2.0.0-alpha.21",
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"dev": "watch unbuild src --wait=0.2",
|
||||
@@ -23,7 +23,7 @@
|
||||
"blitz": "bin/blitz"
|
||||
},
|
||||
"dependencies": {
|
||||
"@blitzjs/generator": "workspace:*",
|
||||
"@blitzjs/generator": "2.0.0-alpha.21",
|
||||
"arg": "5.0.1",
|
||||
"chalk": "^4.1.0",
|
||||
"console-table-printer": "2.10.0",
|
||||
@@ -33,6 +33,7 @@
|
||||
"dotenv": "16.0.0",
|
||||
"dotenv-expand": "8.0.3",
|
||||
"esbuild": "0.14.34",
|
||||
"find-up": "4.1.0",
|
||||
"fs-extra": "10.0.1",
|
||||
"hasbin": "1.2.3",
|
||||
"npm-which": "3.0.1",
|
||||
@@ -41,11 +42,12 @@
|
||||
"pkg-dir": "5.0.0",
|
||||
"prompts": "2.4.2",
|
||||
"resolve-cwd": "3.0.0",
|
||||
"resolve-from": "5.0.0",
|
||||
"superjson": "1.8.0",
|
||||
"tslog": "3.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.21",
|
||||
"@types/cookie": "0.4.1",
|
||||
"@types/cross-spawn": "6.0.2",
|
||||
"@types/debug": "4.1.7",
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import {CliCommand} from "../index"
|
||||
|
||||
const dev: CliCommand = (argv) => {
|
||||
console.log("dev hit")
|
||||
}
|
||||
|
||||
export {dev}
|
||||
@@ -74,6 +74,13 @@ const args = arg(
|
||||
"--parent": String,
|
||||
"--dry-run": Boolean,
|
||||
"--env": String,
|
||||
|
||||
// Aliases
|
||||
"-e": "--env",
|
||||
"-n": "--name",
|
||||
"-t": "--type",
|
||||
"-c": "--context",
|
||||
"-p": "--dry-run",
|
||||
},
|
||||
{
|
||||
permissive: true,
|
||||
@@ -126,8 +133,9 @@ const validateModelName = (modelName: string): void => {
|
||||
|
||||
const determineType = async () => {
|
||||
if (
|
||||
!args["--type"] ||
|
||||
(args["--type"] && !Object.keys(generatorMap).includes(args["--type"].toLowerCase()))
|
||||
!args["_"].slice(1)[0] ||
|
||||
(args["_"].slice(1)[0] &&
|
||||
!Object.keys(generatorMap).includes(args["_"].slice(1)[0]?.toLowerCase() as string))
|
||||
) {
|
||||
const res = await prompts({
|
||||
type: "select",
|
||||
@@ -141,12 +149,12 @@ const determineType = async () => {
|
||||
|
||||
selectedType = res.type
|
||||
} else {
|
||||
selectedType = args["--type"]
|
||||
selectedType = args["_"].slice(1)[0]?.toLowerCase() as string
|
||||
}
|
||||
}
|
||||
|
||||
const determineName = async () => {
|
||||
if (!args["--name"]) {
|
||||
if (!args["_"].slice(1)[1]) {
|
||||
const res = await prompts({
|
||||
type: "text",
|
||||
name: "model",
|
||||
@@ -157,7 +165,7 @@ const determineName = async () => {
|
||||
selectedModelName = model
|
||||
selectedContext = context
|
||||
} else {
|
||||
const {model, context} = getModelNameAndContext(args["--name"])
|
||||
const {model, context} = getModelNameAndContext(args["_"].slice(1)[1]!)
|
||||
selectedModelName = model
|
||||
selectedContext = context
|
||||
}
|
||||
@@ -242,7 +250,7 @@ const generate: CliCommand = async (argv) => {
|
||||
const generator = new GeneratorClass({
|
||||
destinationRoot: require("path").resolve(),
|
||||
// templateDir: blitzConfig.codegen?.templateDir,
|
||||
extraArgs: args["_"].slice(1) as string[],
|
||||
extraArgs: args["_"].slice(3) as string[],
|
||||
modelName: singularRootContext,
|
||||
modelNames: modelNames(singularRootContext),
|
||||
ModelName: ModelName(singularRootContext),
|
||||
|
||||
@@ -48,7 +48,6 @@ const PREFERABLE_PKG_MANAGER: TPkgManager = IS_PNPM_INSTALLED
|
||||
const args = arg(
|
||||
{
|
||||
// Types
|
||||
"--name": String,
|
||||
"--npm": Boolean,
|
||||
"--yarn": Boolean,
|
||||
"--pnpm": Boolean,
|
||||
@@ -59,6 +58,8 @@ const args = arg(
|
||||
"--dry-run": Boolean,
|
||||
"--no-git": Boolean,
|
||||
"--skip-upgrade": Boolean,
|
||||
|
||||
// Aliases
|
||||
},
|
||||
{
|
||||
permissive: true,
|
||||
@@ -74,7 +75,7 @@ let projectPkgManger: TPkgManager = PREFERABLE_PKG_MANAGER
|
||||
let shouldInstallDeps: boolean = true
|
||||
|
||||
const determineProjectName = async () => {
|
||||
if (!args["--name"]) {
|
||||
if (args._.slice(1).length < 1) {
|
||||
const res = await prompts({
|
||||
type: "text",
|
||||
name: "name",
|
||||
@@ -85,7 +86,7 @@ const determineProjectName = async () => {
|
||||
projectName = res.name.trim().replaceAll(" ", "-")
|
||||
projectPath = path.resolve(projectName)
|
||||
} else {
|
||||
projectName = args["--name"]
|
||||
projectName = args._.slice(1)[0] as string
|
||||
projectPath = path.resolve(projectName)
|
||||
}
|
||||
}
|
||||
@@ -192,13 +193,15 @@ const determinePkgManagerToInstallDeps = async () => {
|
||||
message: "Install dependencies?",
|
||||
initial: 0,
|
||||
choices: [
|
||||
{title: "npm"},
|
||||
{title: "yarn", disabled: !IS_YARN_INSTALLED},
|
||||
{title: "pnpm", disabled: !IS_PNPM_INSTALLED},
|
||||
{title: "npm", value: "npm"},
|
||||
{title: "yarn", value: "yarn", disabled: !IS_YARN_INSTALLED},
|
||||
{title: "pnpm", value: "pnpm", disabled: !IS_PNPM_INSTALLED},
|
||||
{title: "skip"},
|
||||
],
|
||||
})
|
||||
|
||||
projectPkgManger = res.pkgManager
|
||||
|
||||
if (res.pkgManager === "skip") {
|
||||
shouldInstallDeps = false
|
||||
} else {
|
||||
@@ -233,7 +236,7 @@ const newApp: CliCommand = async (argv) => {
|
||||
try {
|
||||
const latestBlitzVersion = (await getLatestVersion("blitz")).value
|
||||
const requireManualInstall = args["--dry-run"] || !shouldInstallDeps
|
||||
const postInstallSteps = args["--name"] === "." ? [] : [`cd ${projectName}`]
|
||||
const postInstallSteps = projectName === "." ? [] : [`cd ${projectName}`]
|
||||
|
||||
const generatorOpts: AppGeneratorOptions = {
|
||||
template: projectTemplate,
|
||||
@@ -261,7 +264,6 @@ const newApp: CliCommand = async (argv) => {
|
||||
{ignoreCache: true},
|
||||
)
|
||||
const result = await runPrisma(["migrate", "dev", "--name", "Initial migration"], true)
|
||||
console.log("primsa result", result)
|
||||
if (!result.success) throw new Error()
|
||||
} catch (error) {
|
||||
postInstallSteps.push(
|
||||
|
||||
56
packages/blitz/src/cli/commands/prisma.ts
Normal file
56
packages/blitz/src/cli/commands/prisma.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import {Readable} from "stream"
|
||||
import {getCommandBin} from "../utils/config"
|
||||
import {CliCommand} from "../index"
|
||||
import arg from "arg"
|
||||
|
||||
let prismaBin: string
|
||||
|
||||
export const runPrisma = async (args: string[], silent = false) => {
|
||||
if (!prismaBin) {
|
||||
try {
|
||||
prismaBin = await getCommandBin("prisma")
|
||||
} catch (err) {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
const cp = require("cross-spawn").spawn(prismaBin, args, {
|
||||
stdio: silent ? "pipe" : "inherit",
|
||||
env: process.env,
|
||||
})
|
||||
|
||||
const cp_stderr: string[] = []
|
||||
if (silent) {
|
||||
cp.stderr.on("data", (chunk: Readable) => {
|
||||
cp_stderr.push(chunk.toString())
|
||||
})
|
||||
}
|
||||
|
||||
const code = await require("p-event")(cp, "exit", {rejectionEvents: []})
|
||||
|
||||
return {
|
||||
success: code === 0,
|
||||
stderr: silent ? cp_stderr.join("") : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export const runPrismaExitOnError = async (...args: Parameters<typeof runPrisma>) => {
|
||||
const result = await runPrisma(...args)
|
||||
|
||||
if (!result.success) {
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
const prisma: CliCommand = async () => {
|
||||
const args = arg(
|
||||
{},
|
||||
{
|
||||
permissive: true,
|
||||
},
|
||||
)
|
||||
|
||||
await runPrismaExitOnError(args._.slice(1))
|
||||
}
|
||||
|
||||
export {prisma}
|
||||
@@ -2,6 +2,8 @@ import {NON_STANDARD_NODE_ENV} from "./utils/constants"
|
||||
import arg from "arg"
|
||||
import packageJson from "../../package.json"
|
||||
import {loadEnvConfig} from "../env-utils"
|
||||
import {getCommandBin} from "./utils/config"
|
||||
import spawn from "cross-spawn"
|
||||
|
||||
const commonArgs = {
|
||||
// Types
|
||||
@@ -22,13 +24,6 @@ const commands: {[command: string]: () => Promise<CliCommand>} = {
|
||||
dev: () => import("./commands/next/dev").then((i) => i.dev),
|
||||
build: () => import("./commands/next/build").then((i) => i.build),
|
||||
start: () => import("./commands/next/start").then((i) => i.start),
|
||||
next: async () => (argv) => {
|
||||
if (argv?.[0] && ["dev", "start", "build"].includes(argv[0])) {
|
||||
const command = argv[0] as "dev" | "start" | "build"
|
||||
return import("./commands/next").then((i) => i[command]())
|
||||
}
|
||||
console.error(`Invalid command provided: "blitz next ${argv?.[0]}".`)
|
||||
},
|
||||
new: () => import("./commands/new").then((i) => i.newApp),
|
||||
generate: () => import("./commands/generate").then((i) => i.generate),
|
||||
codegen: () => import("./commands/codegen").then((i) => i.codegen),
|
||||
@@ -52,8 +47,46 @@ if (args["--version"]) {
|
||||
|
||||
const foundCommand = Boolean(commands[args._[0] as string])
|
||||
|
||||
if (!foundCommand && args["--help"]) {
|
||||
console.log(`
|
||||
const command = foundCommand ? (args._[0] as string) : defaultCommand
|
||||
const forwardedArgs = foundCommand ? args._.slice(1) : args._
|
||||
|
||||
if (args["--env"]) {
|
||||
process.env.APP_ENV = args["--env"]
|
||||
}
|
||||
|
||||
if (args["--help"]) {
|
||||
forwardedArgs.push("--help")
|
||||
}
|
||||
|
||||
// env variable should default to dev unless the command is build or start
|
||||
const defaultEnv = command === "build" || command === "start" ? "production" : "development"
|
||||
|
||||
const standardEnv = ["production", "development", "test"]
|
||||
if (process.env.NODE_ENV && !standardEnv.includes(process.env.NODE_ENV)) {
|
||||
console.warn(NON_STANDARD_NODE_ENV)
|
||||
}
|
||||
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
|
||||
|
||||
// Make sure commands gracefully respect termination signals (e.g. from Docker)
|
||||
process.on("SIGTERM", () => process.exit(0))
|
||||
process.on("SIGINT", () => process.exit(0))
|
||||
|
||||
if (foundCommand) {
|
||||
commands[command]?.()
|
||||
.then((exec: any) => exec(forwardedArgs))
|
||||
.then(() => {
|
||||
if (command === "build") {
|
||||
// ensure process exits after build completes so open handles/connections
|
||||
// don't cause process to hang
|
||||
process.exit(0)
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err)
|
||||
})
|
||||
} else {
|
||||
if (args["--help"] && args._.length === 0) {
|
||||
console.log(`
|
||||
Usage
|
||||
$ blitz <command>
|
||||
|
||||
@@ -68,41 +101,26 @@ if (!foundCommand && args["--help"]) {
|
||||
For more information run a command with the --help flag
|
||||
$ blitz build --help
|
||||
`)
|
||||
process.exit(0)
|
||||
process.exit(0)
|
||||
} else {
|
||||
// If the command is not found, we assume it is a command from the bin
|
||||
void runCommandFromBin()
|
||||
}
|
||||
}
|
||||
|
||||
const command = foundCommand ? (args._[0] as string) : defaultCommand
|
||||
const forwardedArgs = foundCommand ? args._.slice(1) : args._
|
||||
async function runCommandFromBin() {
|
||||
const command = args._[0] as string
|
||||
let commandBin: string | null = null
|
||||
try {
|
||||
commandBin = await getCommandBin(command)
|
||||
} catch (e: any) {
|
||||
console.error(`Error: ${e.message}`)
|
||||
}
|
||||
|
||||
if (args["--help"]) {
|
||||
forwardedArgs.push("--help")
|
||||
if (!commandBin) {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const result = spawn.sync(commandBin, process.argv.slice(3), {stdio: "inherit"})
|
||||
process.exit(result.status || 0)
|
||||
}
|
||||
|
||||
if (args["--env"]) {
|
||||
process.env.APP_ENV = args["--env"]
|
||||
}
|
||||
|
||||
const defaultEnv = command === "dev" ? "development" : "production"
|
||||
|
||||
const standardEnv = ["production", "development", "test"]
|
||||
if (process.env.NODE_ENV && !standardEnv.includes(process.env.NODE_ENV)) {
|
||||
console.warn(NON_STANDARD_NODE_ENV)
|
||||
}
|
||||
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
|
||||
|
||||
// Make sure commands gracefully respect termination signals (e.g. from Docker)
|
||||
process.on("SIGTERM", () => process.exit(0))
|
||||
process.on("SIGINT", () => process.exit(0))
|
||||
|
||||
commands[command]?.()
|
||||
.then((exec: any) => exec(forwardedArgs))
|
||||
.then(() => {
|
||||
if (command === "build") {
|
||||
// ensure process exits after build completes so open handles/connections
|
||||
// don't cause process to hang
|
||||
process.exit(0)
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err)
|
||||
})
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user