Compare commits
36 Commits
@blitzjs/a
...
@blitzjs/c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17f70e65ef | ||
|
|
0ddc5a8169 | ||
|
|
e6fb09d494 | ||
|
|
d846fc6be9 | ||
|
|
f5e80e3835 | ||
|
|
17ce29e5e4 | ||
|
|
46d9f81adf | ||
|
|
994cfc6292 | ||
|
|
7811748526 | ||
|
|
ce45368334 | ||
|
|
4e9c1f60b6 | ||
|
|
508682c8f8 | ||
|
|
962eb58af6 | ||
|
|
17669b3af8 | ||
|
|
ec6299c36a | ||
|
|
6ac2d3412a | ||
|
|
85f9959d1f | ||
|
|
354f0440d6 | ||
|
|
ac365a0656 | ||
|
|
0729291099 | ||
|
|
9cf924ee86 | ||
|
|
b545a38b87 | ||
|
|
1463a20471 | ||
|
|
0e762fb557 | ||
|
|
6fe860512c | ||
|
|
adfe8ff919 | ||
|
|
980869fbc8 | ||
|
|
00f6d5576a | ||
|
|
1945d85db2 | ||
|
|
b0c21b0706 | ||
|
|
931156c352 | ||
|
|
1436e76180 | ||
|
|
c3bb5cd95b | ||
|
|
8b08fe4e38 | ||
|
|
604dc3b345 | ||
|
|
20fb3b9427 |
5
.changeset/cool-doors-invent.md
Normal file
5
.changeset/cool-doors-invent.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/rpc": patch
|
||||
---
|
||||
|
||||
Add invokeWithCtx function
|
||||
5
.changeset/famous-kings-explain.md
Normal file
5
.changeset/famous-kings-explain.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
updated nextjs version in generator & npmrc file
|
||||
5
.changeset/fast-trainers-kneel.md
Normal file
5
.changeset/fast-trainers-kneel.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
Export Zod utils from blitz core package
|
||||
5
.changeset/four-meals-fry.md
Normal file
5
.changeset/four-meals-fry.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
export BlitzPage & BlitzLayout types from @blitzjs/next
|
||||
5
.changeset/healthy-rice-shout.md
Normal file
5
.changeset/healthy-rice-shout.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"blitz": patch
|
||||
---
|
||||
|
||||
detailed print env info
|
||||
5
.changeset/olive-bees-buy.md
Normal file
5
.changeset/olive-bees-buy.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/codemod": patch
|
||||
---
|
||||
|
||||
Fix templates source in RPC codemod step
|
||||
5
.changeset/olive-feet-rhyme.md
Normal file
5
.changeset/olive-feet-rhyme.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/codemod": patch
|
||||
---
|
||||
|
||||
Add codemod to upgrade from legacy framework to the Blitz Toolkit
|
||||
@@ -12,39 +12,56 @@
|
||||
"@blitzjs/rpc": "2.0.0-alpha.0",
|
||||
"@blitzjs/config": "0.0.0",
|
||||
"@blitzjs/generator": "2.0.0-alpha.0",
|
||||
"@blitzjs/codemod": "2.0.0-alpha.0",
|
||||
"template": "0.0.0",
|
||||
"toolkit-app": "1.0.0",
|
||||
"test-qm": "0.0.0"
|
||||
"test-qm": "0.0.0",
|
||||
"test-no-suspense": "0.0.0",
|
||||
"test-trailing-slash": "0.0.0"
|
||||
},
|
||||
"changesets": [
|
||||
"big-phones-bow",
|
||||
"breezy-cameras-double",
|
||||
"cool-doors-invent",
|
||||
"dirty-monkeys-greet",
|
||||
"empty-berries-rule",
|
||||
"fair-wombats-sneeze",
|
||||
"famous-kings-explain",
|
||||
"fast-trainers-kneel",
|
||||
"flat-bees-approve",
|
||||
"four-meals-fry",
|
||||
"great-months-train",
|
||||
"healthy-rice-shout",
|
||||
"hot-drinks-approve",
|
||||
"lovely-colts-share",
|
||||
"modern-cameras-pull",
|
||||
"moody-squids-cheer",
|
||||
"nice-starfishes-live",
|
||||
"nine-onions-admire",
|
||||
"ninety-pets-heal",
|
||||
"olive-bees-buy",
|
||||
"olive-feet-rhyme",
|
||||
"plenty-bottles-swim",
|
||||
"poor-peas-lick",
|
||||
"poor-penguins-look",
|
||||
"poor-shrimps-think",
|
||||
"quiet-feet-travel",
|
||||
"rich-chairs-invent",
|
||||
"sharp-falcons-begin",
|
||||
"shy-olives-hang",
|
||||
"silent-colts-reply",
|
||||
"small-socks-confess",
|
||||
"stupid-walls-sell",
|
||||
"swift-drinks-dress",
|
||||
"tasty-news-collect",
|
||||
"ten-rivers-burn",
|
||||
"tender-pianos-check",
|
||||
"thirty-countries-build",
|
||||
"twenty-beans-pump",
|
||||
"two-kiwis-help",
|
||||
"unlucky-papayas-sleep",
|
||||
"violet-bags-leave",
|
||||
"weak-suns-shave",
|
||||
"wicked-ghosts-cough",
|
||||
"wise-frogs-give"
|
||||
]
|
||||
|
||||
5
.changeset/rich-chairs-invent.md
Normal file
5
.changeset/rich-chairs-invent.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
Rename prefetchBlitzQuery to prefetchQuery, add prefetchInfiniteQuery
|
||||
6
.changeset/shy-olives-hang.md
Normal file
6
.changeset/shy-olives-hang.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"@blitzjs/rpc": patch
|
||||
"@blitzjs/generator": patch
|
||||
---
|
||||
|
||||
Update RPC plugin setup in templates
|
||||
5
.changeset/small-socks-confess.md
Normal file
5
.changeset/small-socks-confess.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/auth": patch
|
||||
---
|
||||
|
||||
Add passport adapter to @blitzjs/auth
|
||||
6
.changeset/tasty-news-collect.md
Normal file
6
.changeset/tasty-news-collect.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"blitz": patch
|
||||
"@blitzjs/codemod": patch
|
||||
---
|
||||
|
||||
init codemod generator
|
||||
5
.changeset/violet-bags-leave.md
Normal file
5
.changeset/violet-bags-leave.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/codemod": patch
|
||||
---
|
||||
|
||||
Update templates directory for codemod
|
||||
5
.changeset/weak-suns-shave.md
Normal file
5
.changeset/weak-suns-shave.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@blitzjs/next": patch
|
||||
---
|
||||
|
||||
Move blitz config to next.config.js
|
||||
11
.github/workflows/release.yml
vendored
11
.github/workflows/release.yml
vendored
@@ -20,18 +20,25 @@ jobs:
|
||||
with:
|
||||
node-version: 16.x
|
||||
|
||||
- name: Creating .npmrc
|
||||
run: |
|
||||
cat << EOF > "$HOME/.npmrc"
|
||||
//registry.npmjs.org/:_authToken=$NPM_TOKEN
|
||||
EOF
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- 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
|
||||
publish: pnpm release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
1
.npmrc
1
.npmrc
@@ -1,4 +1,5 @@
|
||||
save-exact=true
|
||||
strict-peer-dependencies=false
|
||||
|
||||
public-hoist-pattern[]=secure-password
|
||||
public-hoist-pattern[]=*types*
|
||||
|
||||
@@ -7,12 +7,6 @@ export const { withBlitz } = setupBlitzClient({
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "web-cookie-prefix",
|
||||
}),
|
||||
BlitzRpcPlugin({
|
||||
reactQueryOptions: {
|
||||
queries: {
|
||||
staleTime: 7000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
BlitzRpcPlugin({}),
|
||||
],
|
||||
})
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"version": "1.0.1-alpha.16",
|
||||
"scripts": {
|
||||
"start:dev": "pnpm run prisma:start && next dev",
|
||||
"buildapp": "pnpm i && pnpm prisma generate && next build",
|
||||
"buildapp": "NODE_ENV=production pnpm blitz codegen && pnpm prisma generate && next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"prisma:start": "prisma generate && prisma migrate deploy",
|
||||
@@ -29,7 +29,7 @@
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@hookform/resolvers": "2.8.8",
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:2.0.0-alpha.23",
|
||||
"blitz": "workspace:2.0.0-alpha.32",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ErrorFallbackProps, ErrorComponent, ErrorBoundary } from "@blitzjs/next"
|
||||
import { ErrorFallbackProps, ErrorComponent, ErrorBoundary, AppProps } from "@blitzjs/next"
|
||||
import { AuthenticationError, AuthorizationError } from "blitz"
|
||||
import type { AppProps } from "next/app"
|
||||
import React from "react"
|
||||
import { withBlitz } from "app/blitz-client"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {setupBlitzServer} from "@blitzjs/next"
|
||||
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
|
||||
import {prisma as db} from "../prisma/index"
|
||||
import db from "db"
|
||||
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
|
||||
|
||||
const {gSSP, gSP, api} = setupBlitzServer({
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {Ctx} from "blitz"
|
||||
import {prisma} from "../../prisma"
|
||||
import {User} from "prisma"
|
||||
import db, {User} from "db"
|
||||
|
||||
export default async function createUser(
|
||||
input: {name: string; email: string},
|
||||
@@ -8,7 +7,7 @@ export default async function createUser(
|
||||
): Promise<User> {
|
||||
ctx.session.$authorize()
|
||||
|
||||
const user = await prisma.user.create({data: {name: input.name, email: input.email}})
|
||||
const user = await db.user.create({data: {name: input.name, email: input.email}})
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
27
apps/web/app/queries/getInfiniteUsers.ts
Normal file
27
apps/web/app/queries/getInfiniteUsers.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import {resolver} from "@blitzjs/rpc"
|
||||
import {paginate} from "blitz"
|
||||
import db, {Prisma} from "db"
|
||||
|
||||
interface GetUsersInput
|
||||
extends Pick<Prisma.UserFindManyArgs, "where" | "orderBy" | "skip" | "take"> {}
|
||||
|
||||
export default resolver.pipe(async ({where, orderBy, skip = 0, take = 100}: GetUsersInput) => {
|
||||
const {
|
||||
items: users,
|
||||
hasMore,
|
||||
nextPage,
|
||||
count,
|
||||
} = await paginate({
|
||||
skip,
|
||||
take,
|
||||
count: () => db.user.count({where}),
|
||||
query: (paginateArgs) => db.user.findMany({...paginateArgs, where, orderBy}),
|
||||
})
|
||||
|
||||
return {
|
||||
users,
|
||||
nextPage,
|
||||
hasMore,
|
||||
count,
|
||||
}
|
||||
})
|
||||
@@ -1,11 +1,10 @@
|
||||
import {Ctx} from "blitz"
|
||||
import {prisma} from "../../prisma"
|
||||
import {User} from "prisma"
|
||||
import db, {User} from "db"
|
||||
|
||||
export default async function getUsers(_input: {}, ctx: Ctx): Promise<User[]> {
|
||||
ctx.session.$authorize()
|
||||
|
||||
const users = await prisma.user.findMany()
|
||||
const users = await db.user.findMany()
|
||||
|
||||
return users
|
||||
}
|
||||
|
||||
8
apps/web/app/queries/getUsersAuth.ts
Normal file
8
apps/web/app/queries/getUsersAuth.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import {resolver} from "@blitzjs/rpc"
|
||||
import db from "db"
|
||||
|
||||
export default resolver.pipe(resolver.authorize(), async () => {
|
||||
const users = await db.user.findMany()
|
||||
|
||||
return users
|
||||
})
|
||||
8
apps/web/db/index.ts
Normal file
8
apps/web/db/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import {enhancePrisma} from "blitz"
|
||||
import {PrismaClient} from "@prisma/client"
|
||||
|
||||
const EnhancedPrisma = enhancePrisma(PrismaClient)
|
||||
|
||||
export * from "@prisma/client"
|
||||
const prisma = new EnhancedPrisma()
|
||||
export default prisma
|
||||
@@ -6,5 +6,10 @@ const {withBlitz} = require("@blitzjs/next")
|
||||
module.exports = withBlitz(
|
||||
withBundleAnalyzer({
|
||||
reactStrictMode: true,
|
||||
blitz: {
|
||||
customServer: {
|
||||
hotReload: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
"prisma:studio": "prisma studio",
|
||||
"test": "jest"
|
||||
},
|
||||
"prisma": {
|
||||
"schema": "./db/schema.prisma"
|
||||
},
|
||||
"dependencies": {
|
||||
"@blitzjs/auth": "workspace:*",
|
||||
"@blitzjs/config": "workspace:*",
|
||||
@@ -19,9 +22,12 @@
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@prisma/client": "3.9.0",
|
||||
"@types/jest": "27.4.1",
|
||||
"@types/passport-twitter": "1.0.37",
|
||||
"blitz": "workspace:*",
|
||||
"jest": "27.5.1",
|
||||
"next": "12.1.6-canary.17",
|
||||
"passport-mock-strategy": "2.0.0",
|
||||
"passport-twitter": "1.0.4",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {ErrorFallbackProps, ErrorComponent, ErrorBoundary} from "@blitzjs/next"
|
||||
import {ErrorFallbackProps, ErrorComponent, ErrorBoundary, AppProps} from "@blitzjs/next"
|
||||
import {AuthenticationError, AuthorizationError} from "blitz"
|
||||
import type {AppProps} from "next/app"
|
||||
import React from "react"
|
||||
import {withBlitz} from "app/blitz-client"
|
||||
|
||||
|
||||
44
apps/web/pages/api/auth/[...auth].ts
Normal file
44
apps/web/pages/api/auth/[...auth].ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import {passportAuth} from "@blitzjs/auth"
|
||||
import {api} from "app/blitz-server"
|
||||
import db from "db"
|
||||
import {Strategy as TwitterStrategy} from "passport-twitter"
|
||||
|
||||
export default api(
|
||||
passportAuth({
|
||||
successRedirectUrl: "/",
|
||||
errorRedirectUrl: "/",
|
||||
strategies: [
|
||||
{
|
||||
strategy: new TwitterStrategy(
|
||||
{
|
||||
consumerKey: process.env.TWITTER_CONSUMER_KEY as string,
|
||||
consumerSecret: process.env.TWITTER_CONSUMER_SECRET as string,
|
||||
accessTokenURL: "https://api.twitter.com/oauth/access_token",
|
||||
callbackURL: "http://127.0.0.1:3000/api/auth/twitter/callback",
|
||||
includeEmail: true,
|
||||
},
|
||||
async function (_token, _tokenSecret, profile, done) {
|
||||
const email = profile.emails?.[0]?.value ?? "blitz@test.com"
|
||||
|
||||
const user = await db.user.upsert({
|
||||
where: {email},
|
||||
create: {
|
||||
email,
|
||||
name: profile.displayName,
|
||||
},
|
||||
update: {email},
|
||||
})
|
||||
|
||||
const publicData = {
|
||||
userId: user.id,
|
||||
roles: [user.role],
|
||||
source: "twitter",
|
||||
}
|
||||
|
||||
done(undefined, {publicData})
|
||||
},
|
||||
),
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
@@ -1,14 +1,13 @@
|
||||
import {api} from "app/blitz-server"
|
||||
import {SessionContext} from "@blitzjs/auth"
|
||||
import {prisma} from "../../prisma/index"
|
||||
import db from "db"
|
||||
|
||||
export default api(async (_req, res, ctx) => {
|
||||
const blitzContext = ctx
|
||||
|
||||
const publicData = blitzContext.session.$publicData
|
||||
|
||||
const sessions = await prisma.session.findMany({})
|
||||
const sessionsCount = await prisma.session.count({})
|
||||
const sessions = await db.session.findMany({})
|
||||
const sessionsCount = await db.session.count({})
|
||||
|
||||
res.status(200).json({
|
||||
userId: blitzContext.session.userId,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {NextApiRequest, NextApiResponse} from "next"
|
||||
import {prisma} from "../../prisma/index"
|
||||
import db from "db"
|
||||
|
||||
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
|
||||
const session = await prisma.session.findFirst({
|
||||
const session = await db.session.findFirst({
|
||||
where: {
|
||||
handle: "test",
|
||||
},
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {api} from "app/blitz-server"
|
||||
import {prisma} from "../../prisma/index"
|
||||
import db from "db"
|
||||
|
||||
export default api(async (_req, res) => {
|
||||
const sessions = await prisma.session.deleteMany()
|
||||
const sessionsCount = await prisma.session.count()
|
||||
const sessions = await db.session.deleteMany()
|
||||
const sessionsCount = await db.session.count()
|
||||
|
||||
res.status(200).json({
|
||||
activeSessions: sessions,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import {setPublicDataForUser} from "@blitzjs/auth"
|
||||
import {api} from "app/blitz-server"
|
||||
import {prisma} from "../../prisma/index"
|
||||
import db from "db"
|
||||
|
||||
export default api(async (req, res, ctx) => {
|
||||
if (ctx.session.$thisIsAuthorized()) {
|
||||
ctx.session.$publicData
|
||||
|
||||
await prisma.user.update({
|
||||
await db.user.update({
|
||||
where: {id: ctx.session.userId as number},
|
||||
data: {role: req.query.role as string},
|
||||
})
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {api} from "app/blitz-server"
|
||||
import {prisma} from "../../prisma/index"
|
||||
import db from "db"
|
||||
import {SecurePassword} from "@blitzjs/auth"
|
||||
|
||||
export const authenticateUser = async (email: string, password: string) => {
|
||||
const user = await prisma.user.findFirst({where: {email}})
|
||||
const user = await db.user.findFirst({where: {email}})
|
||||
if (!user) throw new Error("Authentication Error")
|
||||
|
||||
const result = await SecurePassword.verify(user.hashedPassword, password)
|
||||
@@ -11,7 +11,7 @@ export const authenticateUser = async (email: string, password: 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
|
||||
@@ -25,6 +25,7 @@ export default api(async (req, res, ctx) => {
|
||||
|
||||
await blitzContext.session.$create({
|
||||
userId: user.id,
|
||||
role: "USER",
|
||||
})
|
||||
|
||||
res.status(200).json({email: req.query.email, userId: blitzContext.session.userId})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {api} from "app/blitz-server"
|
||||
import {prisma} from "../../prisma/index"
|
||||
import db from "db"
|
||||
import {SecurePassword} from "@blitzjs/auth"
|
||||
|
||||
export default api(async (req, res, ctx) => {
|
||||
@@ -9,13 +9,14 @@ export default api(async (req, res, ctx) => {
|
||||
(req.query.password as string) || "test-password",
|
||||
)
|
||||
const email = (req.query.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},
|
||||
})
|
||||
|
||||
await blitzContext.session.$create({
|
||||
userId: user.id,
|
||||
role: "USER",
|
||||
})
|
||||
|
||||
res.status(200).json({userId: blitzContext.session.userId, ...user, email: req.query.email})
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import {useState} from "react"
|
||||
import {SessionContext} from "@blitzjs/auth"
|
||||
import {useMutation} from "@blitzjs/rpc"
|
||||
import createUser from "app/mutations/createUser"
|
||||
import {User} from "prisma"
|
||||
import {User} from "db"
|
||||
|
||||
function Page() {
|
||||
const [name, setName] = useState("")
|
||||
|
||||
32
apps/web/pages/page-with-inf-prefetch.tsx
Normal file
32
apps/web/pages/page-with-inf-prefetch.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import {useInfiniteQuery} from "@blitzjs/rpc"
|
||||
import {gSSP} from "app/blitz-server"
|
||||
import getInfiniteUsers from "app/queries/getInfiniteUsers"
|
||||
|
||||
export const getServerSideProps = gSSP(async ({ctx}) => {
|
||||
const {prefetchInfiniteQuery} = ctx
|
||||
|
||||
await prefetchInfiniteQuery(getInfiniteUsers, {}, {})
|
||||
return {props: {}}
|
||||
})
|
||||
|
||||
function PageWithPrefetchInfiniteQuery(props) {
|
||||
const [usersPages] = useInfiniteQuery(getInfiniteUsers, (page = {take: 3, skip: 0}) => page, {
|
||||
getNextPageParam: (lastPage) => lastPage.nextPage,
|
||||
})
|
||||
return (
|
||||
<div>
|
||||
{usersPages.map((usersPage) =>
|
||||
usersPage?.users.map((u) => (
|
||||
<div key={u.createdAt.toDateString()}>
|
||||
<p>name: {u.name}</p>
|
||||
<p>role: {u.role}</p>
|
||||
<p>email: {u.email}</p>
|
||||
<hr />
|
||||
</div>
|
||||
)),
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PageWithPrefetchInfiniteQuery
|
||||
31
apps/web/pages/page-with-invoke-ctx.tsx
Normal file
31
apps/web/pages/page-with-invoke-ctx.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import {SessionContext} from "@blitzjs/auth"
|
||||
import {invokeWithCtx} from "@blitzjs/rpc"
|
||||
import {gSSP} from "app/blitz-server"
|
||||
import getUsersAuth from "app/queries/getUsersAuth"
|
||||
|
||||
type Props = {
|
||||
userId: unknown
|
||||
publicData: SessionContext["$publicData"]
|
||||
}
|
||||
|
||||
export const getServerSideProps = gSSP<Props>(async ({ctx}) => {
|
||||
const {session} = ctx
|
||||
|
||||
const users = await invokeWithCtx(getUsersAuth, {}, ctx)
|
||||
|
||||
console.log({users})
|
||||
|
||||
return {
|
||||
props: {
|
||||
userId: session.userId,
|
||||
publicData: session.$publicData,
|
||||
publishedAt: new Date(0),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
function PageWithInvokeCtx(props: Props) {
|
||||
return <div>{JSON.stringify(props, null, 2)}</div>
|
||||
}
|
||||
|
||||
export default PageWithInvokeCtx
|
||||
@@ -3,13 +3,13 @@ import {gSSP} from "app/blitz-server"
|
||||
import getUsers from "app/queries/getUsers"
|
||||
|
||||
export const getServerSideProps = gSSP(async ({ctx}) => {
|
||||
const {prefetchBlitzQuery} = ctx
|
||||
const {prefetchQuery} = ctx
|
||||
|
||||
await prefetchBlitzQuery(getUsers, {})
|
||||
await prefetchQuery(getUsers, {}, {})
|
||||
return {props: {}}
|
||||
})
|
||||
|
||||
function PageWithGssp(props) {
|
||||
function PageWithPrefetch(props) {
|
||||
const [users] = useQuery(getUsers, {})
|
||||
return (
|
||||
<div>
|
||||
@@ -25,4 +25,4 @@ function PageWithGssp(props) {
|
||||
)
|
||||
}
|
||||
|
||||
export default PageWithGssp
|
||||
export default PageWithPrefetch
|
||||
|
||||
15
apps/web/types.ts
Normal file
15
apps/web/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,12 +1,11 @@
|
||||
import {ErrorFallbackProps, ErrorComponent, ErrorBoundary} from "@blitzjs/next"
|
||||
import {ErrorFallbackProps, ErrorComponent, ErrorBoundary, AppProps} from "@blitzjs/next"
|
||||
import {AuthenticationError, AuthorizationError} from "blitz"
|
||||
import type {AppProps} from "next/app"
|
||||
import React from "react"
|
||||
import {withBlitz} from "../app/blitz-client"
|
||||
|
||||
function RootErrorFallback({error}: ErrorFallbackProps) {
|
||||
if (error instanceof AuthenticationError) {
|
||||
return <div>Error: You are not authenticated</div>
|
||||
return <div id="error">Error: You are not authenticated</div>
|
||||
} else if (error instanceof AuthorizationError) {
|
||||
return (
|
||||
<ErrorComponent
|
||||
|
||||
@@ -35,20 +35,24 @@ const runTests = (mode?: string) => {
|
||||
"should render error for protected query",
|
||||
async () => {
|
||||
const browser = await webdriver(appPort, "/authenticated-page")
|
||||
let errorMsg = await browser.elementByXpath(`//*[@id="__next"]/div`)
|
||||
let errorMsg = await browser.elementById(`error`).text()
|
||||
expect(errorMsg).toMatch(/Error: You are not authenticated/)
|
||||
if (browser) browser.close()
|
||||
},
|
||||
5000 * 60 * 2,
|
||||
)
|
||||
|
||||
it("should render result for open query", async () => {
|
||||
const res = await fetch(`http://localhost:${appPort}/api/noauth`, {
|
||||
method: "GET",
|
||||
headers: {"Content-Type": "application/json; charset=utf-8"},
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
it(
|
||||
"should render result for open query",
|
||||
async () => {
|
||||
const res = await fetch(`http://localhost:${appPort}/api/noauth`, {
|
||||
method: "GET",
|
||||
headers: {"Content-Type": "application/json; charset=utf-8"},
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
},
|
||||
5000 * 60 * 2,
|
||||
)
|
||||
|
||||
it("sets correct cookie", async () => {
|
||||
const res = await fetch(`http://localhost:${appPort}/api/noauth`, {
|
||||
@@ -118,31 +122,33 @@ const runTests = (mode?: string) => {
|
||||
})
|
||||
}
|
||||
|
||||
describe("dev mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
appPort = await findPort()
|
||||
app = await launchApp(appDir, appPort, {})
|
||||
await seed()
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
runTests()
|
||||
})
|
||||
describe("Auth Tests", () => {
|
||||
describe("dev mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
appPort = await findPort()
|
||||
app = await launchApp(appDir, appPort, {cwd: process.cwd()})
|
||||
await seed()
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
runTests()
|
||||
})
|
||||
|
||||
describe("server mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
appPort = await findPort()
|
||||
await nextBuild(appDir)
|
||||
app = await nextStart(appDir, appPort)
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
describe("server mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
await nextBuild(appDir)
|
||||
appPort = await findPort()
|
||||
app = await nextStart(appDir, appPort, {cwd: process.cwd()})
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
|
||||
runTests()
|
||||
runTests()
|
||||
})
|
||||
})
|
||||
|
||||
2
integration-tests/no-suspense/.env
Normal file
2
integration-tests/no-suspense/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
SESSION_SECRET_KEY=hsdenhJfpLHrGjgdgg3jdF8g2bYD2PaQ
|
||||
HEADLESS=true
|
||||
1
integration-tests/no-suspense/.eslintrc.js
Normal file
1
integration-tests/no-suspense/.eslintrc.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("@blitzjs/config/eslint")
|
||||
3
integration-tests/no-suspense/.gitignore
vendored
Normal file
3
integration-tests/no-suspense/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
# Keep environment variables out of version control
|
||||
*.sqlite
|
||||
14
integration-tests/no-suspense/app/blitz-client.ts
Normal file
14
integration-tests/no-suspense/app/blitz-client.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import {BlitzRpcPlugin} from "@blitzjs/rpc"
|
||||
import {setupBlitzClient} from "@blitzjs/next"
|
||||
import {AuthClientPlugin} from "@blitzjs/auth"
|
||||
|
||||
const {withBlitz} = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "no-suspense-tests-cookie-prefix",
|
||||
}),
|
||||
BlitzRpcPlugin({}),
|
||||
],
|
||||
})
|
||||
|
||||
export {withBlitz}
|
||||
16
integration-tests/no-suspense/app/blitz-server.ts
Normal file
16
integration-tests/no-suspense/app/blitz-server.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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} = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "no-suspense-tests-cookie-prefix",
|
||||
storage: PrismaStorage(db as any),
|
||||
isAuthorized: simpleRolesIsAuthorized,
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
export {gSSP, gSP, api}
|
||||
3
integration-tests/no-suspense/app/queries/getBasic.ts
Normal file
3
integration-tests/no-suspense/app/queries/getBasic.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export default async function getBasic() {
|
||||
return "basic-result"
|
||||
}
|
||||
5
integration-tests/no-suspense/next-env.d.ts
vendored
Normal file
5
integration-tests/no-suspense/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.
|
||||
2
integration-tests/no-suspense/next.config.js
Normal file
2
integration-tests/no-suspense/next.config.js
Normal file
@@ -0,0 +1,2 @@
|
||||
const {withBlitz} = require("@blitzjs/next")
|
||||
module.exports = withBlitz({})
|
||||
41
integration-tests/no-suspense/package.json
Normal file
41
integration-tests/no-suspense/package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "test-no-suspense",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start:dev": "pnpm run prisma:start && next dev",
|
||||
"test": "pnpm run prisma:start && vitest run",
|
||||
"test-watch": "vitest",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",
|
||||
"prisma:start": "prisma generate && prisma migrate deploy",
|
||||
"prisma:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@blitzjs/auth": "workspace:*",
|
||||
"@blitzjs/next": "workspace:*",
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:*",
|
||||
"lowdb": "3.0.0",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@next/bundle-analyzer": "12.0.8",
|
||||
"@types/express": "4.17.13",
|
||||
"@types/fs-extra": "9.0.13",
|
||||
"@types/node-fetch": "2.6.1",
|
||||
"@types/react": "18.0.1",
|
||||
"b64-lite": "1.4.0",
|
||||
"eslint": "7.32.0",
|
||||
"fs-extra": "10.0.1",
|
||||
"get-port": "6.1.2",
|
||||
"node-fetch": "3.2.3",
|
||||
"typescript": "^4.5.3"
|
||||
}
|
||||
}
|
||||
34
integration-tests/no-suspense/pages/_app.tsx
Normal file
34
integration-tests/no-suspense/pages/_app.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import {ErrorFallbackProps, ErrorComponent, ErrorBoundary, AppProps} from "@blitzjs/next"
|
||||
import {AuthenticationError, AuthorizationError} from "blitz"
|
||||
import React from "react"
|
||||
import {withBlitz} from "../app/blitz-client"
|
||||
|
||||
function RootErrorFallback({error}: ErrorFallbackProps) {
|
||||
if (error instanceof AuthenticationError) {
|
||||
return <div>Error: You are not authenticated</div>
|
||||
} else if (error instanceof AuthorizationError) {
|
||||
return (
|
||||
<ErrorComponent
|
||||
statusCode={error.statusCode}
|
||||
title="Sorry, you are not authorized to access this"
|
||||
/>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<ErrorComponent
|
||||
statusCode={(error as any)?.statusCode || 400}
|
||||
title={error.message || error.name}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function MyApp({Component, pageProps}: AppProps) {
|
||||
return (
|
||||
<ErrorBoundary FallbackComponent={RootErrorFallback}>
|
||||
<Component {...pageProps} />
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
export default withBlitz(MyApp)
|
||||
@@ -0,0 +1,4 @@
|
||||
import {rpcHandler} from "@blitzjs/rpc"
|
||||
import {api} from "../../../app/blitz-server"
|
||||
|
||||
export default api(rpcHandler({onError: console.log}))
|
||||
23
integration-tests/no-suspense/pages/use-query.tsx
Normal file
23
integration-tests/no-suspense/pages/use-query.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import getBasic from "../app/queries/getBasic"
|
||||
import {useQuery} from "@blitzjs/rpc"
|
||||
import React from "react"
|
||||
|
||||
function Content() {
|
||||
const [result, {isFetching}] = useQuery(getBasic, undefined)
|
||||
|
||||
if (isFetching) {
|
||||
return <>Loading...</>
|
||||
} else {
|
||||
return <div id="content">{result}</div>
|
||||
}
|
||||
}
|
||||
|
||||
function Page() {
|
||||
return (
|
||||
<div id="page">
|
||||
<Content />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page
|
||||
@@ -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,
|
||||
"userId" INTEGER,
|
||||
"hashedSessionToken" TEXT,
|
||||
"antiCSRFToken" TEXT,
|
||||
"publicData" TEXT,
|
||||
"privateData" TEXT,
|
||||
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");
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "sqlite"
|
||||
50
integration-tests/no-suspense/prisma/schema.prisma
Normal file
50
integration-tests/no-suspense/prisma/schema.prisma
Normal file
@@ -0,0 +1,50 @@
|
||||
datasource sqlite {
|
||||
provider = "sqlite"
|
||||
url = "file:./db.sqlite"
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
name String?
|
||||
email String @unique
|
||||
hashedPassword String?
|
||||
role String @default("user")
|
||||
|
||||
sessions Session[]
|
||||
tokens Token[]
|
||||
}
|
||||
|
||||
model Session {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime?
|
||||
handle String @unique
|
||||
user User? @relation(fields: [userId], references: [id])
|
||||
userId Int?
|
||||
hashedSessionToken String?
|
||||
antiCSRFToken String?
|
||||
publicData String?
|
||||
privateData String?
|
||||
}
|
||||
|
||||
model Token {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
hashedToken String
|
||||
type String
|
||||
expiresAt DateTime
|
||||
sentTo String
|
||||
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
userId Int
|
||||
|
||||
@@unique([hashedToken, type])
|
||||
}
|
||||
7
integration-tests/no-suspense/prisma/seed.ts
Normal file
7
integration-tests/no-suspense/prisma/seed.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import {prisma} from "./index"
|
||||
|
||||
const seed = async () => {
|
||||
await prisma.$reset()
|
||||
}
|
||||
|
||||
export default seed
|
||||
57
integration-tests/no-suspense/test/index.test.ts
Normal file
57
integration-tests/no-suspense/test/index.test.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import {describe, it, expect, beforeAll, afterAll} from "vitest"
|
||||
import {killApp, findPort, launchApp, nextBuild, nextStart} from "../../utils/next-test-utils"
|
||||
import webdriver from "../../utils/next-webdriver"
|
||||
|
||||
import {join} from "path"
|
||||
|
||||
let app: any
|
||||
let appPort: number
|
||||
const appDir = join(__dirname, "../")
|
||||
|
||||
const runTests = (mode?: string) => {
|
||||
describe("useQuery without suspense", () => {
|
||||
it(
|
||||
"should render query result",
|
||||
async () => {
|
||||
const browser = await webdriver(appPort, "/use-query")
|
||||
|
||||
let text
|
||||
browser.waitForElementByCss("#content", 0)
|
||||
text = await browser.elementByCss("#content").text()
|
||||
expect(text).toMatch(/basic-result/)
|
||||
if (browser) await browser.close()
|
||||
},
|
||||
5000 * 60 * 2,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
describe("No Suspense Tests", () => {
|
||||
describe("dev mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
appPort = await findPort()
|
||||
app = await launchApp(appDir, appPort, {cwd: process.cwd()})
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
runTests()
|
||||
})
|
||||
|
||||
describe("server mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
await nextBuild(appDir)
|
||||
appPort = await findPort()
|
||||
app = await nextStart(appDir, appPort, {cwd: process.cwd()})
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
|
||||
runTests()
|
||||
})
|
||||
})
|
||||
11
integration-tests/no-suspense/tsconfig.json
Normal file
11
integration-tests/no-suspense/tsconfig.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "@blitzjs/config/tsconfig.nextjs.json",
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"react": ["./node_modules/@types/react"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"baseUrl": "."
|
||||
}
|
||||
@@ -143,7 +143,7 @@ describe("RPC", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
appPort = await findPort()
|
||||
app = await launchApp(appDir, appPort)
|
||||
app = await launchApp(appDir, appPort, {cwd: process.cwd()})
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
@@ -162,7 +162,7 @@ describe("RPC", () => {
|
||||
await nextBuild(appDir)
|
||||
mode = "server"
|
||||
appPort = await findPort()
|
||||
app = await nextStart(appDir, appPort)
|
||||
app = await nextStart(appDir, appPort, {cwd: process.cwd()})
|
||||
})
|
||||
afterAll(() => killApp(app))
|
||||
|
||||
@@ -185,7 +185,7 @@ describe("RPC", () => {
|
||||
await nextBuild(appDir)
|
||||
mode = "serverless"
|
||||
appPort = await findPort()
|
||||
app = await nextStart(appDir, appPort)
|
||||
app = await nextStart(appDir, appPort, {cwd: process.cwd()})
|
||||
})
|
||||
afterAll(async () => {
|
||||
await killApp(app)
|
||||
|
||||
2
integration-tests/trailing-slash/.env
Normal file
2
integration-tests/trailing-slash/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
SESSION_SECRET_KEY=hsdenhJfpLHrGjgdgg3jdF8g2bYD2PaQ
|
||||
HEADLESS=true
|
||||
1
integration-tests/trailing-slash/.eslintrc.js
Normal file
1
integration-tests/trailing-slash/.eslintrc.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("@blitzjs/config/eslint")
|
||||
3
integration-tests/trailing-slash/.gitignore
vendored
Normal file
3
integration-tests/trailing-slash/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
# Keep environment variables out of version control
|
||||
*.sqlite
|
||||
14
integration-tests/trailing-slash/app/blitz-client.ts
Normal file
14
integration-tests/trailing-slash/app/blitz-client.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import {BlitzRpcPlugin} from "@blitzjs/rpc"
|
||||
import {setupBlitzClient} from "@blitzjs/next"
|
||||
import {AuthClientPlugin} from "@blitzjs/auth"
|
||||
|
||||
const {withBlitz} = setupBlitzClient({
|
||||
plugins: [
|
||||
AuthClientPlugin({
|
||||
cookiePrefix: "trailing-slash-tests-cookie-prefix",
|
||||
}),
|
||||
BlitzRpcPlugin({}),
|
||||
],
|
||||
})
|
||||
|
||||
export {withBlitz}
|
||||
16
integration-tests/trailing-slash/app/blitz-server.ts
Normal file
16
integration-tests/trailing-slash/app/blitz-server.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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} = setupBlitzServer({
|
||||
plugins: [
|
||||
AuthServerPlugin({
|
||||
cookiePrefix: "trailing-slash-tests-cookie-prefix",
|
||||
storage: PrismaStorage(db as any),
|
||||
isAuthorized: simpleRolesIsAuthorized,
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
export {gSSP, gSP, api}
|
||||
3
integration-tests/trailing-slash/app/queries/getBasic.ts
Normal file
3
integration-tests/trailing-slash/app/queries/getBasic.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export default async function getBasic() {
|
||||
return "basic-result"
|
||||
}
|
||||
5
integration-tests/trailing-slash/next-env.d.ts
vendored
Normal file
5
integration-tests/trailing-slash/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/trailing-slash/next.config.js
Normal file
4
integration-tests/trailing-slash/next.config.js
Normal file
@@ -0,0 +1,4 @@
|
||||
const {withBlitz} = require("@blitzjs/next")
|
||||
module.exports = withBlitz({
|
||||
trailingSlash: true,
|
||||
})
|
||||
41
integration-tests/trailing-slash/package.json
Normal file
41
integration-tests/trailing-slash/package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "test-trailing-slash",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start:dev": "pnpm run prisma:start && next dev",
|
||||
"test": "pnpm run prisma:start && vitest run",
|
||||
"test-watch": "vitest",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",
|
||||
"prisma:start": "prisma generate && prisma migrate deploy",
|
||||
"prisma:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@blitzjs/auth": "workspace:*",
|
||||
"@blitzjs/next": "workspace:*",
|
||||
"@blitzjs/rpc": "workspace:*",
|
||||
"@prisma/client": "3.9.0",
|
||||
"blitz": "workspace:*",
|
||||
"lowdb": "3.0.0",
|
||||
"next": "12.1.6-canary.17",
|
||||
"prisma": "3.9.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:*",
|
||||
"@next/bundle-analyzer": "12.0.8",
|
||||
"@types/express": "4.17.13",
|
||||
"@types/fs-extra": "9.0.13",
|
||||
"@types/node-fetch": "2.6.1",
|
||||
"@types/react": "18.0.1",
|
||||
"b64-lite": "1.4.0",
|
||||
"eslint": "7.32.0",
|
||||
"fs-extra": "10.0.1",
|
||||
"get-port": "6.1.2",
|
||||
"node-fetch": "3.2.3",
|
||||
"typescript": "^4.5.3"
|
||||
}
|
||||
}
|
||||
34
integration-tests/trailing-slash/pages/_app.tsx
Normal file
34
integration-tests/trailing-slash/pages/_app.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import {ErrorFallbackProps, ErrorComponent, ErrorBoundary, AppProps} from "@blitzjs/next"
|
||||
import {AuthenticationError, AuthorizationError} from "blitz"
|
||||
import React from "react"
|
||||
import {withBlitz} from "../app/blitz-client"
|
||||
|
||||
function RootErrorFallback({error}: ErrorFallbackProps) {
|
||||
if (error instanceof AuthenticationError) {
|
||||
return <div>Error: You are not authenticated</div>
|
||||
} else if (error instanceof AuthorizationError) {
|
||||
return (
|
||||
<ErrorComponent
|
||||
statusCode={error.statusCode}
|
||||
title="Sorry, you are not authorized to access this"
|
||||
/>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<ErrorComponent
|
||||
statusCode={(error as any)?.statusCode || 400}
|
||||
title={error.message || error.name}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function MyApp({Component, pageProps}: AppProps) {
|
||||
return (
|
||||
<ErrorBoundary FallbackComponent={RootErrorFallback}>
|
||||
<Component {...pageProps} />
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
export default withBlitz(MyApp)
|
||||
@@ -0,0 +1,4 @@
|
||||
import {rpcHandler} from "@blitzjs/rpc"
|
||||
import {api} from "../../../app/blitz-server"
|
||||
|
||||
export default api(rpcHandler({onError: console.log}))
|
||||
20
integration-tests/trailing-slash/pages/use-query.tsx
Normal file
20
integration-tests/trailing-slash/pages/use-query.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import getBasic from "../app/queries/getBasic"
|
||||
import {useQuery} from "@blitzjs/rpc"
|
||||
import {Suspense} from "react"
|
||||
|
||||
function Content() {
|
||||
const [result] = useQuery(getBasic, undefined)
|
||||
return <div id="content">{result}</div>
|
||||
}
|
||||
|
||||
function Page() {
|
||||
return (
|
||||
<div id="page">
|
||||
<Suspense fallback={"Loading..."}>
|
||||
<Content />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Page
|
||||
8
integration-tests/trailing-slash/prisma/index.ts
Normal file
8
integration-tests/trailing-slash/prisma/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import {enhancePrisma} from "blitz"
|
||||
import {PrismaClient} from "@prisma/client"
|
||||
|
||||
const EnhancedPrisma = enhancePrisma(PrismaClient)
|
||||
|
||||
export * from "@prisma/client"
|
||||
const prisma = new EnhancedPrisma()
|
||||
export {prisma}
|
||||
@@ -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,
|
||||
"userId" INTEGER,
|
||||
"hashedSessionToken" TEXT,
|
||||
"antiCSRFToken" TEXT,
|
||||
"publicData" TEXT,
|
||||
"privateData" TEXT,
|
||||
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");
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "sqlite"
|
||||
50
integration-tests/trailing-slash/prisma/schema.prisma
Normal file
50
integration-tests/trailing-slash/prisma/schema.prisma
Normal file
@@ -0,0 +1,50 @@
|
||||
datasource sqlite {
|
||||
provider = "sqlite"
|
||||
url = "file:./db.sqlite"
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
name String?
|
||||
email String @unique
|
||||
hashedPassword String?
|
||||
role String @default("user")
|
||||
|
||||
sessions Session[]
|
||||
tokens Token[]
|
||||
}
|
||||
|
||||
model Session {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime?
|
||||
handle String @unique
|
||||
user User? @relation(fields: [userId], references: [id])
|
||||
userId Int?
|
||||
hashedSessionToken String?
|
||||
antiCSRFToken String?
|
||||
publicData String?
|
||||
privateData String?
|
||||
}
|
||||
|
||||
model Token {
|
||||
id Int @id @default(autoincrement())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
hashedToken String
|
||||
type String
|
||||
expiresAt DateTime
|
||||
sentTo String
|
||||
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
userId Int
|
||||
|
||||
@@unique([hashedToken, type])
|
||||
}
|
||||
7
integration-tests/trailing-slash/prisma/seed.ts
Normal file
7
integration-tests/trailing-slash/prisma/seed.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import {prisma} from "./index"
|
||||
|
||||
const seed = async () => {
|
||||
await prisma.$reset()
|
||||
}
|
||||
|
||||
export default seed
|
||||
56
integration-tests/trailing-slash/test/index.test.ts
Normal file
56
integration-tests/trailing-slash/test/index.test.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import {describe, it, expect, beforeAll, afterAll} from "vitest"
|
||||
import {killApp, findPort, launchApp, nextBuild, nextStart} from "../../utils/next-test-utils"
|
||||
import webdriver from "../../utils/next-webdriver"
|
||||
|
||||
import {join} from "path"
|
||||
|
||||
let app: any
|
||||
let appPort: number
|
||||
const appDir = join(__dirname, "../")
|
||||
|
||||
const runTests = (mode?: string) => {
|
||||
describe("Trailing Slash", () => {
|
||||
it(
|
||||
"should render query result",
|
||||
async () => {
|
||||
const browser = await webdriver(appPort, "/use-query")
|
||||
let text = await browser.elementByCss("#page").text()
|
||||
expect(text).toMatch(/Loading/)
|
||||
await browser.waitForElementByCss("#content", 0)
|
||||
text = await browser.elementByCss("#content").text()
|
||||
expect(text).toMatch(/basic-result/)
|
||||
if (browser) await browser.close()
|
||||
},
|
||||
5000 * 60 * 2,
|
||||
)
|
||||
})
|
||||
}
|
||||
describe("Trailing Slash Tests", () => {
|
||||
describe("dev mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
appPort = await findPort()
|
||||
app = await launchApp(appDir, appPort, {cwd: process.cwd()})
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
runTests()
|
||||
})
|
||||
|
||||
describe("server mode", () => {
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
await nextBuild(appDir)
|
||||
appPort = await findPort()
|
||||
app = await nextStart(appDir, appPort, {cwd: process.cwd()})
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}, 5000 * 60 * 2)
|
||||
afterAll(async () => await killApp(app))
|
||||
|
||||
runTests()
|
||||
})
|
||||
})
|
||||
11
integration-tests/trailing-slash/tsconfig.json
Normal file
11
integration-tests/trailing-slash/tsconfig.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "@blitzjs/config/tsconfig.nextjs.json",
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"react": ["./node_modules/@types/react"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules"],
|
||||
"baseUrl": "."
|
||||
}
|
||||
@@ -80,21 +80,7 @@ const BlitzWrapper = ({plugins, children}) => {
|
||||
export function render(ui: RenderUI, {wrapper, router, ...options}: RenderOptions = {}) {
|
||||
if (!wrapper) {
|
||||
wrapper = ({children}) => {
|
||||
return (
|
||||
<BlitzWrapper
|
||||
plugins={[
|
||||
BlitzRpcPlugin({
|
||||
reactQueryOptions: {
|
||||
queries: {
|
||||
staleTime: 7000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
]}
|
||||
>
|
||||
{children}
|
||||
</BlitzWrapper>
|
||||
)
|
||||
return <BlitzWrapper plugins={[BlitzRpcPlugin({})]}>{children}</BlitzWrapper>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
100
integration-tests/utils/browsers/base.ts
Normal file
100
integration-tests/utils/browsers/base.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
export type Event = "request"
|
||||
|
||||
// This is the base Browser interface all browser
|
||||
// classes should build off of, it is the bare
|
||||
// methods we aim to support across tests
|
||||
export class BrowserInterface {
|
||||
private promise: any
|
||||
private then: any
|
||||
private catch: any
|
||||
|
||||
protected chain(nextCall: any): BrowserInterface {
|
||||
if (!this.promise) {
|
||||
this.promise = Promise.resolve(this)
|
||||
}
|
||||
this.promise = this.promise.then(nextCall)
|
||||
this.then = (...args) => this.promise.then(...args)
|
||||
this.catch = (...args) => this.promise.catch(...args)
|
||||
return this
|
||||
}
|
||||
|
||||
async setup(browserName: string, locale?: string): Promise<void> {}
|
||||
async close(): Promise<void> {}
|
||||
async quit(): Promise<void> {}
|
||||
|
||||
elementsByCss(selector: string): BrowserInterface[] {
|
||||
return [this]
|
||||
}
|
||||
elementByCss(selector: string): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
elementById(selector: string): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
click(opts?: {modifierKey?: boolean}): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
keydown(key: string): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
keyup(key: string): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
focusPage(): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
type(text: string): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
waitForElementByCss(selector: string, timeout?: number): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
waitForCondition(snippet: string, timeout?: number): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
back(): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
forward(): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
refresh(): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
setDimensions(opts: {height: number; width: number}): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
addCookie(opts: {name: string; value: string}): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
deleteCookies(): BrowserInterface {
|
||||
return this
|
||||
}
|
||||
on(event: Event, cb: (...args: any[]) => void) {}
|
||||
off(event: Event, cb: (...args: any[]) => void) {}
|
||||
async loadPage(url: string, {disableCache: boolean, beforePageLoad: Function}): Promise<void> {}
|
||||
async get(url: string): Promise<void> {}
|
||||
|
||||
async getValue(): Promise<any> {}
|
||||
async getAttribute(name: string): Promise<any> {}
|
||||
async eval(snippet: string | Function): Promise<any> {}
|
||||
async evalAsync(snippet: string | Function): Promise<any> {}
|
||||
async text(): Promise<string> {
|
||||
return ""
|
||||
}
|
||||
async getComputedCss(prop: string): Promise<string> {
|
||||
return ""
|
||||
}
|
||||
async hasElementByCssSelector(selector: string): Promise<boolean> {
|
||||
return false
|
||||
}
|
||||
async log(): Promise<any[]> {
|
||||
return []
|
||||
}
|
||||
async websocketFrames(): Promise<any[]> {
|
||||
return []
|
||||
}
|
||||
async url(): Promise<string> {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
312
integration-tests/utils/browsers/playwright.ts
Normal file
312
integration-tests/utils/browsers/playwright.ts
Normal file
@@ -0,0 +1,312 @@
|
||||
import {BrowserInterface, Event} from "./base"
|
||||
import {
|
||||
chromium,
|
||||
webkit,
|
||||
firefox,
|
||||
Browser,
|
||||
BrowserContext,
|
||||
Page,
|
||||
ElementHandle,
|
||||
} from "playwright-chromium"
|
||||
|
||||
let page: Page
|
||||
let browser: Browser | undefined
|
||||
let context: BrowserContext | undefined
|
||||
let pageLogs: Array<{source: string; message: string}> = []
|
||||
let websocketFrames: Array<{payload: string | Buffer}> = []
|
||||
|
||||
export async function quit() {
|
||||
await context?.close()
|
||||
await browser?.close()
|
||||
context = undefined
|
||||
browser = undefined
|
||||
}
|
||||
|
||||
class Playwright extends BrowserInterface {
|
||||
private eventCallbacks: Record<Event, Set<(...args: any[]) => void>> = {
|
||||
request: new Set(),
|
||||
}
|
||||
|
||||
on(event: Event, cb: (...args: any[]) => void) {
|
||||
if (!this.eventCallbacks[event]) {
|
||||
throw new Error(
|
||||
`Invalid event passed to browser.on, received ${event}. Valid events are ${Object.keys(
|
||||
event,
|
||||
)}`,
|
||||
)
|
||||
}
|
||||
this.eventCallbacks[event]?.add(cb)
|
||||
}
|
||||
off(event: Event, cb: (...args: any[]) => void) {
|
||||
this.eventCallbacks[event]?.delete(cb)
|
||||
}
|
||||
|
||||
async setup(browserName: string, locale?: string) {
|
||||
if (browser) return
|
||||
const headless = !!process.env.HEADLESS || true
|
||||
|
||||
if (browserName === "safari") {
|
||||
browser = await webkit.launch({headless})
|
||||
} else if (browserName === "firefox") {
|
||||
browser = await firefox.launch({headless})
|
||||
} else {
|
||||
browser = await chromium.launch({headless, devtools: !headless})
|
||||
}
|
||||
context = await browser.newContext({locale})
|
||||
}
|
||||
|
||||
async get(url: string): Promise<void> {
|
||||
return page.goto(url) as any
|
||||
}
|
||||
|
||||
async loadPage(
|
||||
url: string,
|
||||
opts?: {disableCache: boolean; beforePageLoad?: (...args: any[]) => void},
|
||||
) {
|
||||
// clean-up existing pages
|
||||
for (const oldPage of context!.pages()) {
|
||||
await oldPage.close()
|
||||
}
|
||||
page = await context!.newPage()
|
||||
pageLogs = []
|
||||
websocketFrames = []
|
||||
|
||||
page.on("console", (msg) => {
|
||||
console.log("browser log:", msg)
|
||||
pageLogs.push({source: msg.type(), message: msg.text()})
|
||||
})
|
||||
page.on("crash", (page) => {
|
||||
console.error("page crashed")
|
||||
})
|
||||
page.on("pageerror", (error) => {
|
||||
console.error("page error", error)
|
||||
})
|
||||
page.on("request", (req) => {
|
||||
this.eventCallbacks.request.forEach((cb) => cb(req))
|
||||
})
|
||||
|
||||
if (opts?.disableCache) {
|
||||
// TODO: this doesn't seem to work (dev tools does not check the box as expected)
|
||||
const session = await context!.newCDPSession(page)
|
||||
session.send("Network.setCacheDisabled", {cacheDisabled: true})
|
||||
}
|
||||
|
||||
page.on("websocket", (ws) => {
|
||||
ws.on("framereceived", (frame) => {
|
||||
websocketFrames.push({payload: frame.payload})
|
||||
})
|
||||
})
|
||||
|
||||
opts?.beforePageLoad?.(page)
|
||||
|
||||
await page.goto(url, {waitUntil: "load"})
|
||||
}
|
||||
|
||||
back(): BrowserInterface {
|
||||
return this.chain(() => {
|
||||
return page.goBack()
|
||||
})
|
||||
}
|
||||
forward(): BrowserInterface {
|
||||
return this.chain(() => {
|
||||
return page.goForward()
|
||||
})
|
||||
}
|
||||
refresh(): BrowserInterface {
|
||||
return this.chain(() => {
|
||||
return page.reload()
|
||||
})
|
||||
}
|
||||
setDimensions({width, height}: {height: number; width: number}): BrowserInterface {
|
||||
return this.chain(() => page.setViewportSize({width, height}))
|
||||
}
|
||||
addCookie(opts: {name: string; value: string}): BrowserInterface {
|
||||
return this.chain(async () =>
|
||||
context!.addCookies([
|
||||
{
|
||||
path: "/",
|
||||
domain: await page.evaluate("window.location.hostname"),
|
||||
...opts,
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
deleteCookies(): BrowserInterface {
|
||||
return this.chain(async () => context!.clearCookies())
|
||||
}
|
||||
|
||||
focusPage() {
|
||||
return this.chain(() => page.bringToFront())
|
||||
}
|
||||
|
||||
private wrapElement(el: ElementHandle, selector: string) {
|
||||
;(el as any).selector = selector
|
||||
;(el as any).text = () => el.innerText()
|
||||
;(el as any).getComputedCss = (prop) =>
|
||||
page.evaluate(
|
||||
function (args) {
|
||||
return (
|
||||
getComputedStyle(document.querySelector(args.selector) as Element)[args.prop] || null
|
||||
)
|
||||
},
|
||||
{selector, prop},
|
||||
)
|
||||
;(el as any).getCssValue = (el as any).getComputedCss
|
||||
;(el as any).getValue = () =>
|
||||
page.evaluate(
|
||||
function (args) {
|
||||
return (document.querySelector(args.selector) as any).value
|
||||
},
|
||||
{selector},
|
||||
)
|
||||
return el
|
||||
}
|
||||
|
||||
elementByCss(selector: string) {
|
||||
return this.waitForElementByCss(selector)
|
||||
}
|
||||
|
||||
elementById(sel) {
|
||||
return this.elementByCss(`#${sel}`)
|
||||
}
|
||||
|
||||
getValue() {
|
||||
return this.chain((el) =>
|
||||
page.evaluate(
|
||||
function (args) {
|
||||
return document.querySelector(args.selector).value
|
||||
},
|
||||
{selector: el.selector},
|
||||
),
|
||||
) as any
|
||||
}
|
||||
|
||||
text() {
|
||||
return this.chain((el) => el.text()) as any
|
||||
}
|
||||
|
||||
type(text) {
|
||||
return this.chain((el) => el.type(text))
|
||||
}
|
||||
|
||||
moveTo() {
|
||||
return this.chain((el) => {
|
||||
return page.hover(el.selector).then(() => el)
|
||||
})
|
||||
}
|
||||
|
||||
async getComputedCss(prop: string) {
|
||||
return this.chain((el) => {
|
||||
return el.getCssValue(prop)
|
||||
}) as any
|
||||
}
|
||||
|
||||
async getAttribute(attr) {
|
||||
return this.chain((el) => el.getAttribute(attr))
|
||||
}
|
||||
|
||||
async hasElementByCssSelector(selector: string) {
|
||||
return this.eval(`!!document.querySelector('${selector}')`) as any
|
||||
}
|
||||
|
||||
keydown(key: string): BrowserInterface {
|
||||
return this.chain((el) => {
|
||||
return page.keyboard.down(key).then(() => el)
|
||||
})
|
||||
}
|
||||
|
||||
keyup(key: string): BrowserInterface {
|
||||
return this.chain((el) => {
|
||||
return page.keyboard.up(key).then(() => el)
|
||||
})
|
||||
}
|
||||
|
||||
click() {
|
||||
return this.chain((el) => {
|
||||
return el.click().then(() => el)
|
||||
})
|
||||
}
|
||||
|
||||
elementsByCss(sel) {
|
||||
return this.chain(() =>
|
||||
page.$$(sel).then((els) => {
|
||||
return els.map((el) => {
|
||||
const origGetAttribute = el.getAttribute.bind(el)
|
||||
el.getAttribute = (name) => {
|
||||
// ensure getAttribute defaults to empty string to
|
||||
// match selenium
|
||||
return origGetAttribute(name).then((val) => val || "")
|
||||
}
|
||||
return el
|
||||
})
|
||||
}),
|
||||
) as any as BrowserInterface[]
|
||||
}
|
||||
|
||||
waitForElementByCss(selector, timeout?: number) {
|
||||
return this.chain(() => {
|
||||
return page.waitForSelector(selector, {timeout, state: "attached"}).then(async (el) => {
|
||||
// it seems selenium waits longer and tests rely on this behavior
|
||||
// so we wait for the load event fire before returning
|
||||
await page.waitForLoadState()
|
||||
return this.wrapElement(el, selector)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
waitForCondition(condition, timeout) {
|
||||
return this.chain(() => {
|
||||
return page.waitForFunction(condition, {timeout})
|
||||
})
|
||||
}
|
||||
|
||||
async eval(snippet) {
|
||||
// TODO: should this and evalAsync be chained? Might lead
|
||||
// to bad chains
|
||||
return page
|
||||
.evaluate(snippet)
|
||||
.catch((err) => {
|
||||
console.error("eval error:", err)
|
||||
return null
|
||||
})
|
||||
.then(async (val) => {
|
||||
await page.waitForLoadState()
|
||||
return val
|
||||
})
|
||||
}
|
||||
|
||||
async evalAsync(snippet) {
|
||||
if (typeof snippet === "function") {
|
||||
snippet = snippet.toString()
|
||||
}
|
||||
|
||||
if (snippet.includes(`var callback = arguments[arguments.length - 1]`)) {
|
||||
snippet = `(function() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const origFunc = ${snippet}
|
||||
try {
|
||||
origFunc(resolve)
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
})()`
|
||||
}
|
||||
|
||||
return page.evaluate(snippet).catch(() => null)
|
||||
}
|
||||
|
||||
async log() {
|
||||
return this.chain(() => pageLogs) as any
|
||||
}
|
||||
|
||||
async websocketFrames() {
|
||||
return this.chain(() => websocketFrames) as any
|
||||
}
|
||||
|
||||
async url() {
|
||||
return this.chain(() => page.evaluate("window.location.href")) as any
|
||||
}
|
||||
}
|
||||
|
||||
export default Playwright
|
||||
331
integration-tests/utils/browsers/selenium.ts
Normal file
331
integration-tests/utils/browsers/selenium.ts
Normal file
@@ -0,0 +1,331 @@
|
||||
import path from "path"
|
||||
import resolveFrom from "resolve-from"
|
||||
import {execSync} from "child_process"
|
||||
import {Options as ChromeOptions} from "selenium-webdriver/chrome"
|
||||
import {Options as SafariOptions} from "selenium-webdriver/safari"
|
||||
import {Options as FireFoxOptions} from "selenium-webdriver/firefox"
|
||||
import {Builder, By, ThenableWebDriver, until} from "selenium-webdriver"
|
||||
|
||||
import {BrowserInterface} from "./base"
|
||||
|
||||
const {
|
||||
BROWSERSTACK,
|
||||
BROWSERSTACK_USERNAME,
|
||||
BROWSERSTACK_ACCESS_KEY,
|
||||
HEADLESS,
|
||||
CHROME_BIN,
|
||||
LEGACY_SAFARI,
|
||||
SKIP_LOCAL_SELENIUM_SERVER,
|
||||
} = process.env
|
||||
|
||||
if (process.env.ChromeWebDriver) {
|
||||
process.env.PATH = `${process.env.ChromeWebDriver}${path.delimiter}${process.env.PATH}`
|
||||
}
|
||||
|
||||
let seleniumServer: any
|
||||
let browserStackLocal: any
|
||||
let browser: ThenableWebDriver
|
||||
|
||||
export async function quit() {
|
||||
await Promise.all([
|
||||
browser?.quit(),
|
||||
new Promise<void>((resolve) => {
|
||||
browserStackLocal ? browserStackLocal.killAllProcesses(() => resolve()) : resolve()
|
||||
}),
|
||||
])
|
||||
seleniumServer?.kill()
|
||||
|
||||
browser = undefined
|
||||
browserStackLocal = undefined
|
||||
seleniumServer = undefined
|
||||
}
|
||||
|
||||
class Selenium extends BrowserInterface {
|
||||
private browserName: string
|
||||
|
||||
// TODO: support setting locale
|
||||
async setup(browserName: string, locale?: string) {
|
||||
if (browser) return
|
||||
this.browserName = browserName
|
||||
|
||||
let capabilities = {}
|
||||
const isSafari = browserName === "safari"
|
||||
const isFirefox = browserName === "firefox"
|
||||
const isIE = browserName === "internet explorer"
|
||||
const isBrowserStack = BROWSERSTACK
|
||||
const localSeleniumServer = SKIP_LOCAL_SELENIUM_SERVER !== "true"
|
||||
|
||||
// install conditional packages globally so the entire
|
||||
// monorepo doesn't need to rebuild when testing
|
||||
let globalNodeModules: string
|
||||
|
||||
if (isBrowserStack || localSeleniumServer) {
|
||||
globalNodeModules = execSync("npm root -g").toString().trim()
|
||||
}
|
||||
|
||||
if (isBrowserStack) {
|
||||
const {Local} = require(resolveFrom(globalNodeModules, "browserstack-local"))
|
||||
browserStackLocal = new Local()
|
||||
|
||||
const localBrowserStackOpts = {
|
||||
key: process.env.BROWSERSTACK_ACCESS_KEY,
|
||||
// Add a unique local identifier to run parallel tests
|
||||
// on BrowserStack
|
||||
localIdentifier: new Date().getTime(),
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
browserStackLocal.start(localBrowserStackOpts, (err) => {
|
||||
if (err) return reject(err)
|
||||
console.log("Started BrowserStackLocal", browserStackLocal.isRunning())
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
|
||||
const safariOpts = {
|
||||
os: "OS X",
|
||||
os_version: "Mojave",
|
||||
browser: "Safari",
|
||||
}
|
||||
const safariLegacyOpts = {
|
||||
os: "OS X",
|
||||
os_version: "Sierra",
|
||||
browserName: "Safari",
|
||||
browser_version: "10.1",
|
||||
}
|
||||
const ieOpts = {
|
||||
os: "Windows",
|
||||
os_version: "10",
|
||||
browser: "IE",
|
||||
}
|
||||
const firefoxOpts = {
|
||||
os: "Windows",
|
||||
os_version: "10",
|
||||
browser: "Firefox",
|
||||
}
|
||||
const sharedOpts = {
|
||||
"browserstack.local": true,
|
||||
"browserstack.video": false,
|
||||
"browserstack.user": BROWSERSTACK_USERNAME,
|
||||
"browserstack.key": BROWSERSTACK_ACCESS_KEY,
|
||||
"browserstack.localIdentifier": localBrowserStackOpts.localIdentifier,
|
||||
}
|
||||
|
||||
capabilities = {
|
||||
...capabilities,
|
||||
...sharedOpts,
|
||||
|
||||
...(isIE ? ieOpts : {}),
|
||||
...(isSafari ? (LEGACY_SAFARI ? safariLegacyOpts : safariOpts) : {}),
|
||||
...(isFirefox ? firefoxOpts : {}),
|
||||
}
|
||||
} else if (localSeleniumServer) {
|
||||
console.log("Installing selenium server")
|
||||
const seleniumServerMod = require(resolveFrom(globalNodeModules, "selenium-standalone"))
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
seleniumServerMod.install((err) => {
|
||||
if (err) return reject(err)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
|
||||
console.log("Starting selenium server")
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
seleniumServerMod.start((err, child) => {
|
||||
if (err) return reject(err)
|
||||
seleniumServer = child
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
console.log("Started selenium server")
|
||||
}
|
||||
|
||||
let chromeOptions = new ChromeOptions()
|
||||
let firefoxOptions = new FireFoxOptions()
|
||||
let safariOptions = new SafariOptions()
|
||||
|
||||
if (HEADLESS) {
|
||||
const screenSize = {width: 1280, height: 720}
|
||||
chromeOptions = chromeOptions.headless().windowSize(screenSize) as any
|
||||
firefoxOptions = firefoxOptions.headless().windowSize(screenSize)
|
||||
}
|
||||
|
||||
if (CHROME_BIN) {
|
||||
chromeOptions = chromeOptions.setChromeBinaryPath(path.resolve(CHROME_BIN))
|
||||
}
|
||||
|
||||
let seleniumServerUrl
|
||||
|
||||
if (isBrowserStack) {
|
||||
seleniumServerUrl = "http://hub-cloud.browserstack.com/wd/hub"
|
||||
} else if (localSeleniumServer) {
|
||||
seleniumServerUrl = `http://localhost:4444/wd/hub`
|
||||
}
|
||||
|
||||
browser = new Builder()
|
||||
.usingServer(seleniumServerUrl)
|
||||
.withCapabilities(capabilities)
|
||||
.forBrowser(browserName)
|
||||
.setChromeOptions(chromeOptions)
|
||||
.setFirefoxOptions(firefoxOptions)
|
||||
.setSafariOptions(safariOptions)
|
||||
.build()
|
||||
}
|
||||
|
||||
async get(url: string): Promise<void> {
|
||||
return browser.get(url)
|
||||
}
|
||||
|
||||
async loadPage(url: string) {
|
||||
// in chrome we use a new tab for testing
|
||||
if (this.browserName === "chrome") {
|
||||
const initialHandle = await browser.getWindowHandle()
|
||||
|
||||
await browser.switchTo().newWindow("tab")
|
||||
const newHandle = await browser.getWindowHandle()
|
||||
|
||||
await browser.switchTo().window(initialHandle)
|
||||
await browser.close()
|
||||
await browser.switchTo().window(newHandle)
|
||||
|
||||
// clean-up extra windows created from links and such
|
||||
for (const handle of await browser.getAllWindowHandles()) {
|
||||
if (handle !== newHandle) {
|
||||
await browser.switchTo().window(handle)
|
||||
await browser.close()
|
||||
}
|
||||
}
|
||||
await browser.switchTo().window(newHandle)
|
||||
} else {
|
||||
await browser.get("about:blank")
|
||||
}
|
||||
return browser.get(url)
|
||||
}
|
||||
|
||||
back(): BrowserInterface {
|
||||
return this.chain(() => {
|
||||
return browser.navigate().back()
|
||||
})
|
||||
}
|
||||
forward(): BrowserInterface {
|
||||
return this.chain(() => {
|
||||
return browser.navigate().forward()
|
||||
})
|
||||
}
|
||||
refresh(): BrowserInterface {
|
||||
return this.chain(() => {
|
||||
return browser.navigate().refresh()
|
||||
})
|
||||
}
|
||||
setDimensions({width, height}: {height: number; width: number}): BrowserInterface {
|
||||
return this.chain(() => browser.manage().window().setRect({width, height, x: 0, y: 0}))
|
||||
}
|
||||
addCookie(opts: {name: string; value: string}): BrowserInterface {
|
||||
return this.chain(() => browser.manage().addCookie(opts))
|
||||
}
|
||||
deleteCookies(): BrowserInterface {
|
||||
return this.chain(() => browser.manage().deleteAllCookies())
|
||||
}
|
||||
|
||||
elementByCss(selector: string) {
|
||||
return this.chain(() => {
|
||||
return browser.findElement(By.css(selector)).then((el: any) => {
|
||||
el.selector = selector
|
||||
el.text = () => el.getText()
|
||||
el.getComputedCss = (prop) => el.getCssValue(prop)
|
||||
el.type = (text) => el.sendKeys(text)
|
||||
el.getValue = () =>
|
||||
browser.executeScript(`return document.querySelector('${selector}').value`)
|
||||
return el
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
elementById(sel) {
|
||||
return this.elementByCss(`#${sel}`)
|
||||
}
|
||||
|
||||
getValue() {
|
||||
return this.chain((el) =>
|
||||
browser.executeScript(`return document.querySelector('${el.selector}').value`),
|
||||
) as any
|
||||
}
|
||||
|
||||
text() {
|
||||
return this.chain((el) => el.getText()) as any
|
||||
}
|
||||
|
||||
type(text) {
|
||||
return this.chain((el) => el.sendKeys(text))
|
||||
}
|
||||
|
||||
moveTo() {
|
||||
return this.chain((el) => {
|
||||
return browser
|
||||
.actions()
|
||||
.move({origin: el})
|
||||
.perform()
|
||||
.then(() => el)
|
||||
})
|
||||
}
|
||||
|
||||
async getComputedCss(prop: string) {
|
||||
return this.chain((el) => {
|
||||
return el.getCssValue(prop)
|
||||
}) as any
|
||||
}
|
||||
|
||||
async getAttribute(attr) {
|
||||
return this.chain((el) => el.getAttribute(attr))
|
||||
}
|
||||
|
||||
async hasElementByCssSelector(selector: string) {
|
||||
return this.eval(`!!document.querySelector('${selector}')`) as any
|
||||
}
|
||||
|
||||
click() {
|
||||
return this.chain((el) => {
|
||||
return el.click().then(() => el)
|
||||
})
|
||||
}
|
||||
|
||||
elementsByCss(sel) {
|
||||
return this.chain(() => browser.findElements(By.css(sel))) as any as BrowserInterface[]
|
||||
}
|
||||
|
||||
waitForElementByCss(sel, timeout) {
|
||||
return this.chain(() => browser.wait(until.elementLocated(By.css(sel)), timeout))
|
||||
}
|
||||
|
||||
waitForCondition(condition, timeout) {
|
||||
return this.chain(() =>
|
||||
browser.wait(async (driver) => {
|
||||
return driver.executeScript("return " + condition).catch(() => false)
|
||||
}, timeout),
|
||||
)
|
||||
}
|
||||
|
||||
async eval(snippet) {
|
||||
if (typeof snippet === "string" && !snippet.startsWith("return")) {
|
||||
snippet = `return ${snippet}`
|
||||
}
|
||||
return browser.executeScript(snippet)
|
||||
}
|
||||
|
||||
async evalAsync(snippet) {
|
||||
if (typeof snippet === "string" && !snippet.startsWith("return")) {
|
||||
snippet = `return ${snippet}`
|
||||
}
|
||||
return browser.executeAsyncScript(snippet)
|
||||
}
|
||||
|
||||
async log() {
|
||||
return this.chain(() => browser.manage().logs().get("browser")) as any
|
||||
}
|
||||
|
||||
async url() {
|
||||
return this.chain(() => browser.getCurrentUrl()) as any
|
||||
}
|
||||
}
|
||||
|
||||
export default Selenium
|
||||
@@ -1,30 +1,33 @@
|
||||
import spawn from "cross-spawn"
|
||||
import {ChildProcess} from "child_process"
|
||||
import express from "express"
|
||||
import {existsSync, readFileSync, unlinkSync, writeFileSync, createReadStream} from "fs"
|
||||
import {existsSync, readFileSync, createReadStream} from "fs"
|
||||
import {writeFile} from "fs-extra"
|
||||
import getPort from "get-port"
|
||||
import http from "http"
|
||||
// `next` here is the symlink in `test/node_modules/next` which points to the root directory.
|
||||
// This is done so that requiring from `next` works.
|
||||
// The reason we don't import the relative path `../../dist/<etc>` is that it would lead to inconsistent module singletons
|
||||
import https from "https"
|
||||
import server from "next/dist/server/next"
|
||||
import _pkg from "next/package.json"
|
||||
import fetch from "node-fetch"
|
||||
import path from "path"
|
||||
import qs from "querystring"
|
||||
import treeKill from "tree-kill"
|
||||
|
||||
import {readJSONSync} from "fs-extra"
|
||||
// import {packageDirectorySync} from "pkg-dir"
|
||||
import pkgDir from "pkg-dir"
|
||||
import resolveCwd from "resolve-cwd"
|
||||
export const nextServer = server
|
||||
|
||||
// polyfill Object.fromEntries for the test/integration/relay-analytics tests
|
||||
// on node 10, this can be removed after we no longer support node 10
|
||||
if (!Object.fromEntries) {
|
||||
Object.fromEntries = require("core-js/features/object/from-entries")
|
||||
}
|
||||
export const pkg = _pkg
|
||||
|
||||
export function initNextServerScript(scriptPath, successRegexp, env, failRegexp, opts) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const instance = spawn("node", ["--no-deprecation", scriptPath], {env})
|
||||
const instance = spawn(
|
||||
"node",
|
||||
[...((opts && opts.nodeArgs) || []), "--no-deprecation", scriptPath],
|
||||
{
|
||||
env,
|
||||
cwd: opts && opts.cwd,
|
||||
},
|
||||
)
|
||||
|
||||
function handleStdout(data) {
|
||||
const message = data.toString()
|
||||
@@ -65,6 +68,27 @@ export function initNextServerScript(scriptPath, successRegexp, env, failRegexp,
|
||||
})
|
||||
}
|
||||
|
||||
export function getFullUrl(appPortOrUrl: string | number, url: string, hostname?: string) {
|
||||
let fullUrl =
|
||||
typeof appPortOrUrl === "string" && appPortOrUrl.startsWith("http")
|
||||
? appPortOrUrl
|
||||
: `http://${hostname ? hostname : "localhost"}:${appPortOrUrl}${url}`
|
||||
|
||||
if (typeof appPortOrUrl === "string" && url) {
|
||||
const parsedUrl = new URL(fullUrl)
|
||||
const parsedPathQuery = new URL(url, fullUrl)
|
||||
|
||||
parsedUrl.search = parsedPathQuery.search
|
||||
parsedUrl.pathname = parsedPathQuery.pathname
|
||||
|
||||
if (hostname && parsedUrl.hostname === "localhost") {
|
||||
parsedUrl.hostname = hostname
|
||||
}
|
||||
fullUrl = parsedUrl.toString()
|
||||
}
|
||||
return fullUrl
|
||||
}
|
||||
|
||||
export function renderViaAPI(app, pathname, query) {
|
||||
const url = `${pathname}${query ? `?${qs.stringify(query)}` : ""}`
|
||||
return app.renderToHTML({url}, {}, pathname, query)
|
||||
@@ -75,40 +99,63 @@ export function renderViaHTTP(appPort, pathname, query, opts) {
|
||||
}
|
||||
|
||||
export function fetchViaHTTP(appPort, pathname, query, opts) {
|
||||
const url = `http://localhost:${appPort}${pathname}${
|
||||
const url = `${pathname}${
|
||||
typeof query === "string" ? query : query ? `?${qs.stringify(query)}` : ""
|
||||
}`
|
||||
return fetch(url, opts)
|
||||
return fetch(getFullUrl(appPort, url), {
|
||||
// in node.js v17 fetch favors IPv6 but Next.js is
|
||||
// listening on IPv4 by default so force IPv4 DNS resolving
|
||||
agent: (parsedUrl) => {
|
||||
if (parsedUrl.protocol === "https:") {
|
||||
return new https.Agent({family: 4})
|
||||
}
|
||||
if (parsedUrl.protocol === "http:") {
|
||||
return new http.Agent({family: 4})
|
||||
}
|
||||
},
|
||||
...opts,
|
||||
})
|
||||
}
|
||||
|
||||
export function findPort() {
|
||||
return getPort()
|
||||
}
|
||||
|
||||
interface RunNextCommandOptions {
|
||||
cwd?: string
|
||||
env?: Record<any, any>
|
||||
spawnOptions?: any
|
||||
instance?: any
|
||||
stderr?: boolean
|
||||
stdout?: boolean
|
||||
ignoreFail?: boolean
|
||||
export function resolveBin(pkg: string, executable = pkg) {
|
||||
const packageDir = pkgDir.sync()!
|
||||
if (!packageDir) throw new Error(`Could not find package.json for '${pkg}'`)
|
||||
const bin = readJSONSync(path.join(packageDir, "package.json"))
|
||||
const binPath = typeof bin === "object" ? bin.dependencies[executable] : bin
|
||||
if (!binPath) throw new Error(`No bin '${executable}' in module '${pkg}'`)
|
||||
|
||||
const fullPath = path.join(packageDir, `node_modules`, `${pkg}`)
|
||||
|
||||
return fullPath
|
||||
}
|
||||
export function getCommandBin(
|
||||
command: string,
|
||||
rootFolder: string = process.cwd(),
|
||||
_usePatched: boolean = false,
|
||||
) {
|
||||
const bin = resolveBin(command)
|
||||
return path.resolve(rootFolder, bin)
|
||||
}
|
||||
|
||||
export function runNextCommand(argv: any[], options: RunNextCommandOptions = {}) {
|
||||
const cwd = options.cwd
|
||||
export function runNextCommand(argv, options: RunNextCommandOptions = {}) {
|
||||
const nextnextbin = getCommandBin("next", options.cwd)
|
||||
const nextBin = path.join(nextnextbin, "dist/bin/next")
|
||||
const cwd = options.cwd || process.cwd()
|
||||
// Let Next.js decide the environment
|
||||
const env = {
|
||||
...process.env,
|
||||
...options.env,
|
||||
NODE_ENV: "",
|
||||
NODE_ENV: "production" as const,
|
||||
__NEXT_TEST_MODE: "true",
|
||||
...options.env,
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log(`Running command "next ${argv.join(" ")}"`)
|
||||
const instance = spawn("pnpm", ["exec", "next", ...argv], {
|
||||
...options.spawnOptions,
|
||||
const instance = spawn("node", [nextBin, ...argv], {
|
||||
cwd,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
@@ -118,22 +165,43 @@ export function runNextCommand(argv: any[], options: RunNextCommandOptions = {})
|
||||
options.instance(instance)
|
||||
}
|
||||
|
||||
let mergedStdio = ""
|
||||
|
||||
let stderrOutput = ""
|
||||
instance.stderr?.on("data", function (chunk) {
|
||||
stderrOutput += chunk
|
||||
})
|
||||
if (options.stderr) {
|
||||
instance.stderr?.on("data", function (chunk) {
|
||||
mergedStdio += chunk
|
||||
stderrOutput += chunk
|
||||
|
||||
if (options.stderr === "log") {
|
||||
console.log(chunk.toString())
|
||||
}
|
||||
})
|
||||
} else {
|
||||
instance.stderr?.on("data", function (chunk) {
|
||||
mergedStdio += chunk
|
||||
})
|
||||
}
|
||||
|
||||
let stdoutOutput = ""
|
||||
if (options.stdout) {
|
||||
instance.stdout?.on("data", function (chunk) {
|
||||
mergedStdio += chunk
|
||||
stdoutOutput += chunk
|
||||
|
||||
if (options.stdout === "log") {
|
||||
console.log(chunk.toString())
|
||||
}
|
||||
})
|
||||
} else {
|
||||
instance.stdout?.on("data", function (chunk) {
|
||||
mergedStdio += chunk
|
||||
})
|
||||
}
|
||||
|
||||
instance.on("close", (code, signal) => {
|
||||
if (!options.stderr && !options.stdout && !options.ignoreFail && code !== 0) {
|
||||
console.log(stderrOutput)
|
||||
return reject(new Error(`command failed with code ${code}`))
|
||||
return reject(new Error(`command failed with code ${code}\n${mergedStdio}`))
|
||||
}
|
||||
|
||||
resolve({
|
||||
@@ -145,7 +213,6 @@ export function runNextCommand(argv: any[], options: RunNextCommandOptions = {})
|
||||
})
|
||||
|
||||
instance.on("error", (err: any) => {
|
||||
console.log(stderrOutput)
|
||||
err.stdout = stdoutOutput
|
||||
err.stderr = stderrOutput
|
||||
reject(err)
|
||||
@@ -153,41 +220,41 @@ export function runNextCommand(argv: any[], options: RunNextCommandOptions = {})
|
||||
})
|
||||
}
|
||||
|
||||
interface RunNextCommandDevOptions {
|
||||
cwd?: string
|
||||
env?: Record<any, any>
|
||||
onStdout?: (stdout: string) => void
|
||||
onStderr?: (stderr: string) => void
|
||||
stderr?: boolean
|
||||
stdout?: boolean
|
||||
nodeArgs?: []
|
||||
bootupMarker?: any
|
||||
nextStart?: boolean
|
||||
}
|
||||
export function runNextCommandDev(argv, stdOut, opts: RunNextCommandDevOptions = {}) {
|
||||
const nextnextbin = getCommandBin("next", opts.cwd)
|
||||
const nextDir = path.resolve(require.resolve("next/package"))
|
||||
const nextBin = path.join(nextnextbin, "dist/bin/next")
|
||||
|
||||
export function runNextCommandDev(argv, opts: RunNextCommandDevOptions = {}) {
|
||||
const cwd = opts.cwd // || nextDir
|
||||
const cwd = opts.cwd || nextDir
|
||||
const env = {
|
||||
...process.env,
|
||||
NODE_ENV: opts.nextStart ? ("production" as const) : ("development" as const),
|
||||
NODE_ENV: undefined,
|
||||
__NEXT_TEST_MODE: "true",
|
||||
...opts.env,
|
||||
}
|
||||
|
||||
return new Promise<void | string | ChildProcess>((resolve, reject) => {
|
||||
const instance = spawn("pnpm", ["exec", "next", ...argv], {
|
||||
const nodeArgs = opts.nodeArgs || []
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const instance = spawn("node", [...nodeArgs, "--no-deprecation", nextBin, ...argv], {
|
||||
cwd,
|
||||
env,
|
||||
})
|
||||
|
||||
} as {})
|
||||
let didResolve = false
|
||||
|
||||
function handleStdout(data) {
|
||||
const message = data.toString()
|
||||
|
||||
if (!didResolve) {
|
||||
didResolve = true
|
||||
resolve(instance)
|
||||
const bootupMarkers = {
|
||||
dev: /compiled .*successfully/i,
|
||||
start: /started server/i,
|
||||
}
|
||||
if (
|
||||
(opts.bootupMarker && opts.bootupMarker.test(message)) ||
|
||||
bootupMarkers[opts.nextStart || stdOut ? "start" : "dev"].test(message)
|
||||
) {
|
||||
if (!didResolve) {
|
||||
didResolve = true
|
||||
resolve(stdOut ? message : instance)
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof opts.onStdout === "function") {
|
||||
@@ -229,43 +296,42 @@ export function runNextCommandDev(argv, opts: RunNextCommandDevOptions = {}) {
|
||||
}
|
||||
|
||||
// Launch the app in dev mode.
|
||||
export function launchApp(dir, port, opts) {
|
||||
return runNextCommandDev(["-p", port], {cwd: dir, ...opts})
|
||||
export function launchApp(dir, port, opts: RunNextCommandDevOptions) {
|
||||
return runNextCommandDev([dir, "-p", port], undefined, opts)
|
||||
}
|
||||
|
||||
export function nextBuild(dir, args = [], opts = {}) {
|
||||
return runNextCommand(["build", ...args], {cwd: dir, ...opts})
|
||||
export function nextBuild(dir, args = [], opts = {}): any {
|
||||
return runNextCommand(["build", dir, ...args], opts)
|
||||
}
|
||||
|
||||
export function nextExport(dir, {outdir}, opts = {}) {
|
||||
return runNextCommand(["export", dir, "--outdir", outdir], {cwd: dir, ...opts})
|
||||
return runNextCommand(["export", dir, "--outdir", outdir], opts)
|
||||
}
|
||||
|
||||
export function nextExportDefault(dir, opts = {}) {
|
||||
return runNextCommand(["export", dir], {cwd: dir, ...opts})
|
||||
return runNextCommand(["export", dir], opts)
|
||||
}
|
||||
|
||||
export function nextLint(dir, args = [], opts = {}) {
|
||||
return runNextCommand(["lint", dir, ...args], {cwd: dir, ...opts})
|
||||
return runNextCommand(["lint", dir, ...args], opts)
|
||||
}
|
||||
|
||||
export function nextStart(dir, port, opts = {}) {
|
||||
return runNextCommandDev(["start", "-p", port], {
|
||||
cwd: dir,
|
||||
return runNextCommandDev(["start", "-p", port, dir], undefined, {
|
||||
...opts,
|
||||
nextStart: true,
|
||||
})
|
||||
}
|
||||
|
||||
export function buildTS(args = [], cwd, env = {NODE_ENV: "production" as const}) {
|
||||
cwd = cwd
|
||||
env = {...process.env, ...env}
|
||||
export function buildTS(args = [], cwd, env = {}) {
|
||||
cwd = cwd || path.dirname(require.resolve("next/package"))
|
||||
env = {...process.env, NODE_ENV: undefined, ...env}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const instance = spawn(
|
||||
"node",
|
||||
["--no-deprecation", require.resolve("typescript/lib/tsc"), ...args],
|
||||
{cwd, env},
|
||||
{cwd, env} as {},
|
||||
)
|
||||
let output = ""
|
||||
|
||||
@@ -285,10 +351,9 @@ export function buildTS(args = [], cwd, env = {NODE_ENV: "production" as const})
|
||||
})
|
||||
}
|
||||
|
||||
// Kill a launched app
|
||||
export async function killApp(instance) {
|
||||
export async function killProcess(pid) {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
treeKill(instance.pid, (err) => {
|
||||
treeKill(pid, (err) => {
|
||||
if (err) {
|
||||
if (
|
||||
process.platform === "win32" &&
|
||||
@@ -311,11 +376,25 @@ export async function killApp(instance) {
|
||||
})
|
||||
}
|
||||
|
||||
export async function startApp(app: any) {
|
||||
// Kill a launched app
|
||||
export async function killApp(instance) {
|
||||
if (instance) {
|
||||
await killProcess(instance.pid)
|
||||
}
|
||||
}
|
||||
|
||||
export async function startApp(app) {
|
||||
// force require usage instead of dynamic import in jest
|
||||
// x-ref: https://github.com/nodejs/node/issues/35889
|
||||
process.env.__NEXT_TEST_MODE = "jest"
|
||||
|
||||
// TODO: tests that use this should be migrated to use
|
||||
// the nextStart test function instead as it tests outside
|
||||
// of jest's context
|
||||
await app.prepare()
|
||||
const handler = app.getRequestHandler()
|
||||
const server = http.createServer(handler)
|
||||
;(server as any).__app = app
|
||||
const server: any = http.createServer(handler)
|
||||
server.__app = app
|
||||
|
||||
await promiseCall(server, "listen")
|
||||
return server
|
||||
@@ -346,7 +425,7 @@ export function waitFor(millis) {
|
||||
return new Promise((resolve) => setTimeout(resolve, millis))
|
||||
}
|
||||
|
||||
export async function startStaticServer(dir, notFoundFile) {
|
||||
export async function startStaticServer(dir, notFoundFile, fixedPort) {
|
||||
const app = express()
|
||||
const server = http.createServer(app)
|
||||
app.use(express.static(dir))
|
||||
@@ -357,7 +436,7 @@ export async function startStaticServer(dir, notFoundFile) {
|
||||
})
|
||||
}
|
||||
|
||||
await promiseCall(server, "listen")
|
||||
await promiseCall(server, "listen", fixedPort)
|
||||
return server
|
||||
}
|
||||
|
||||
@@ -401,55 +480,9 @@ export async function check(contentFn, regex, hardError = true) {
|
||||
return false
|
||||
}
|
||||
|
||||
export class File {
|
||||
path: string
|
||||
originalContent: any
|
||||
constructor(path) {
|
||||
this.path = path
|
||||
this.originalContent = existsSync(this.path) ? readFileSync(this.path, "utf8") : null
|
||||
}
|
||||
|
||||
write(content) {
|
||||
if (!this.originalContent) {
|
||||
this.originalContent = content
|
||||
}
|
||||
writeFileSync(this.path, content, "utf8")
|
||||
}
|
||||
|
||||
replace(pattern, newValue) {
|
||||
const currentContent = readFileSync(this.path, "utf8")
|
||||
if (pattern instanceof RegExp) {
|
||||
if (!pattern.test(currentContent)) {
|
||||
throw new Error(
|
||||
`Failed to replace content.\n\nPattern: ${pattern.toString()}\n\nContent: ${currentContent}`,
|
||||
)
|
||||
}
|
||||
} else if (typeof pattern === "string") {
|
||||
if (!currentContent.includes(pattern)) {
|
||||
throw new Error(
|
||||
`Failed to replace content.\n\nPattern: ${pattern}\n\nContent: ${currentContent}`,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Unknown replacement attempt type: ${pattern}`)
|
||||
}
|
||||
|
||||
const newContent = currentContent.replace(pattern, newValue)
|
||||
this.write(newContent)
|
||||
}
|
||||
|
||||
delete() {
|
||||
unlinkSync(this.path)
|
||||
}
|
||||
|
||||
restore() {
|
||||
this.write(this.originalContent)
|
||||
}
|
||||
}
|
||||
|
||||
export async function evaluate(browser, input) {
|
||||
if (typeof input === "function") {
|
||||
const result = await browser.executeScript(input)
|
||||
const result = await browser.eval(input)
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
return result
|
||||
} else {
|
||||
@@ -479,9 +512,8 @@ export async function retry(fn, duration = 3000, interval = 500, description) {
|
||||
}
|
||||
|
||||
export async function hasRedbox(browser, expected = true) {
|
||||
let attempts = 30
|
||||
do {
|
||||
const has = await evaluate(browser, () => {
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const result = await evaluate(browser, () => {
|
||||
return Boolean(
|
||||
[].slice
|
||||
.call(document.querySelectorAll("nextjs-portal"))
|
||||
@@ -492,15 +524,12 @@ export async function hasRedbox(browser, expected = true) {
|
||||
),
|
||||
)
|
||||
})
|
||||
if (has) {
|
||||
return true
|
||||
}
|
||||
if (--attempts < 0) {
|
||||
break
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||
} while (expected)
|
||||
if (result === expected) {
|
||||
return result
|
||||
}
|
||||
await waitFor(1000)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -544,6 +573,24 @@ export async function getRedboxSource(browser) {
|
||||
)
|
||||
}
|
||||
|
||||
export async function getRedboxDescription(browser) {
|
||||
return retry(
|
||||
() =>
|
||||
evaluate(browser, () => {
|
||||
const portal = [].slice
|
||||
.call(document.querySelectorAll("nextjs-portal"))
|
||||
.find((p) => p.shadowRoot.querySelector("[data-nextjs-dialog-header]"))
|
||||
const root = portal.shadowRoot
|
||||
return root
|
||||
.querySelector("#nextjs__container_errors_desc")
|
||||
.innerText.replace(/__WEBPACK_DEFAULT_EXPORT__/, "Unknown")
|
||||
}),
|
||||
3000,
|
||||
500,
|
||||
"getRedboxDescription",
|
||||
)
|
||||
}
|
||||
|
||||
export function getBrowserBodyText(browser) {
|
||||
return browser.eval('document.getElementsByTagName("body")[0].innerText')
|
||||
}
|
||||
@@ -552,8 +599,8 @@ export function normalizeRegEx(src) {
|
||||
return new RegExp(src).source.replace(/\^\//g, "^\\/")
|
||||
}
|
||||
|
||||
function readJson(path: string) {
|
||||
return JSON.parse(readFileSync(path) as any)
|
||||
function readJson(path) {
|
||||
return JSON.parse(readFileSync(path).toString())
|
||||
}
|
||||
|
||||
export function getBuildManifest(dir) {
|
||||
@@ -614,3 +661,96 @@ export function readNextBuildServerPageFile(appDir, page) {
|
||||
const pageFile = getPageFileFromPagesManifest(appDir, page)
|
||||
return readFileSync(path.join(appDir, ".next", "server", pageFile), "utf8")
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} suiteName
|
||||
* @param {{env: 'prod' | 'dev', appDir: string}} context
|
||||
* @param {{beforeAll?: Function; afterAll?: Function; runTests: Function}} options
|
||||
*/
|
||||
function runSuite(suiteName, context, options) {
|
||||
const {appDir, env} = context
|
||||
describe(`${suiteName} ${env}`, () => {
|
||||
beforeAll(async () => {
|
||||
options.beforeAll?.(env)
|
||||
context.stderr = ""
|
||||
const onStderr = (msg) => {
|
||||
context.stderr += msg
|
||||
}
|
||||
context.stdout = ""
|
||||
const onStdout = (msg) => {
|
||||
context.stdout += msg
|
||||
}
|
||||
if (env === "prod") {
|
||||
context.appPort = await findPort()
|
||||
const {stdout, stderr, code} = await nextBuild(appDir, [], {
|
||||
stderr: true,
|
||||
stdout: true,
|
||||
})
|
||||
context.stdout = stdout
|
||||
context.stderr = stderr
|
||||
context.code = code
|
||||
context.server = await nextStart(context.appDir, context.appPort, {
|
||||
onStderr,
|
||||
onStdout,
|
||||
})
|
||||
} else if (env === "dev") {
|
||||
context.appPort = await findPort()
|
||||
context.server = await launchApp(context.appDir, context.appPort, {
|
||||
onStderr,
|
||||
onStdout,
|
||||
})
|
||||
}
|
||||
})
|
||||
afterAll(async () => {
|
||||
options.afterAll?.(env)
|
||||
if (context.server) {
|
||||
await killApp(context.server)
|
||||
}
|
||||
})
|
||||
options.runTests(context, env)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} suiteName
|
||||
* @param {string} appDir
|
||||
* @param {{beforeAll?: Function; afterAll?: Function; runTests: Function}} options
|
||||
*/
|
||||
export function runDevSuite(suiteName, appDir, options) {
|
||||
return runSuite(suiteName, {appDir, env: "dev"}, options)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} suiteName
|
||||
* @param {string} appDir
|
||||
* @param {{beforeAll?: Function; afterAll?: Function; runTests: Function}} options
|
||||
*/
|
||||
export function runProdSuite(suiteName, appDir, options) {
|
||||
return runSuite(suiteName, {appDir, env: "prod"}, options)
|
||||
}
|
||||
|
||||
interface RunNextCommandOptions {
|
||||
cwd?: string
|
||||
env?: Record<any, any>
|
||||
spawnOptions?: any
|
||||
instance?: any
|
||||
stderr?: string
|
||||
stdout?: string
|
||||
ignoreFail?: boolean
|
||||
nodeArgs?: []
|
||||
}
|
||||
|
||||
interface RunNextCommandDevOptions {
|
||||
cwd?: string
|
||||
env?: Record<any, any>
|
||||
onStdout?: (stdout: string) => void
|
||||
onStderr?: (stderr: string) => void
|
||||
stderr?: string | boolean
|
||||
stdout?: string | boolean
|
||||
nodeArgs?: []
|
||||
bootupMarker?: any
|
||||
nextStart?: boolean
|
||||
}
|
||||
|
||||
@@ -1,236 +1,105 @@
|
||||
/// <reference types="./next-webdriver" />
|
||||
import fetch from "node-fetch"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import {Builder, By} from "selenium-webdriver"
|
||||
import {Options as ChromeOptions} from "selenium-webdriver/chrome"
|
||||
import {Options as FireFoxOptions} from "selenium-webdriver/firefox"
|
||||
import {Options as SafariOptions} from "selenium-webdriver/safari"
|
||||
import Chain from "./wd-chain"
|
||||
import {getFullUrl} from "./next-test-utils"
|
||||
import {BrowserInterface} from "./browsers/base"
|
||||
import browserMod, {quit} from "./browsers/playwright"
|
||||
;(global as any).browserName = process.env.BROWSER_NAME || "chrome"
|
||||
|
||||
export function waitFor(millis) {
|
||||
return new Promise((resolve) => setTimeout(resolve, millis))
|
||||
}
|
||||
let browserQuit
|
||||
|
||||
export {By}
|
||||
|
||||
const {
|
||||
BROWSER_NAME: browserName = "chrome",
|
||||
BROWSERSTACK,
|
||||
BROWSERSTACK_USERNAME,
|
||||
BROWSERSTACK_ACCESS_KEY,
|
||||
HEADLESS,
|
||||
CHROME_BIN,
|
||||
LEGACY_SAFARI,
|
||||
CHROMEWEBDRIVER,
|
||||
} = process.env
|
||||
|
||||
let capabilities = {}
|
||||
|
||||
const isChrome = browserName === "chrome"
|
||||
const isSafari = browserName === "safari"
|
||||
const isFirefox = browserName === "firefox"
|
||||
const isIE = browserName === "internet explorer"
|
||||
|
||||
if (CHROMEWEBDRIVER) {
|
||||
console.log("path", process.env.PATH)
|
||||
console.log("comspec", process.env.COMSPEC)
|
||||
console.log("chromedriver", `${CHROMEWEBDRIVER}${path.delimiter}${process.env.PATH}`)
|
||||
}
|
||||
|
||||
if (process.env.ChromeWebDriver) {
|
||||
process.env.PATH = `${process.env.ChromeWebDriver}${path.delimiter}${process.env.PATH}`
|
||||
}
|
||||
|
||||
const isBrowserStack = BROWSERSTACK && BROWSERSTACK_USERNAME && BROWSERSTACK_ACCESS_KEY
|
||||
|
||||
if (isBrowserStack) {
|
||||
const safariOpts = {
|
||||
os: "OS X",
|
||||
os_version: "Mojave",
|
||||
browser: "Safari",
|
||||
}
|
||||
const safariLegacyOpts = {
|
||||
os: "OS X",
|
||||
os_version: "Sierra",
|
||||
browserName: "Safari",
|
||||
browser_version: "10.1",
|
||||
}
|
||||
const ieOpts = {
|
||||
os: "Windows",
|
||||
os_version: "10",
|
||||
browser: "IE",
|
||||
}
|
||||
const firefoxOpts = {
|
||||
os: "Windows",
|
||||
os_version: "10",
|
||||
browser: "Firefox",
|
||||
}
|
||||
const sharedOpts = {
|
||||
"browserstack.local": true,
|
||||
"browserstack.video": false,
|
||||
"browserstack.user": BROWSERSTACK_USERNAME,
|
||||
"browserstack.key": BROWSERSTACK_ACCESS_KEY,
|
||||
"browserstack.localIdentifier": global.browserStackLocalId,
|
||||
}
|
||||
|
||||
capabilities = {
|
||||
...capabilities,
|
||||
...sharedOpts,
|
||||
|
||||
...(isIE ? ieOpts : {}),
|
||||
...(isSafari ? (LEGACY_SAFARI ? safariLegacyOpts : safariOpts) : {}),
|
||||
...(isFirefox ? firefoxOpts : {}),
|
||||
}
|
||||
}
|
||||
|
||||
let chromeOptions = new ChromeOptions()
|
||||
let firefoxOptions = new FireFoxOptions()
|
||||
let safariOptions = new SafariOptions()
|
||||
|
||||
chromeOptions.addArguments("--remote-debugging-port=9222")
|
||||
chromeOptions.addArguments("--headless")
|
||||
chromeOptions.addArguments("--no-sandbox")
|
||||
chromeOptions.addArguments("--disable-gpu")
|
||||
chromeOptions.addArguments("--disable-dev-shm-usage")
|
||||
|
||||
if (HEADLESS) {
|
||||
const screenSize = {width: 1280, height: 720}
|
||||
chromeOptions = chromeOptions.headless().windowSize(screenSize)
|
||||
firefoxOptions = firefoxOptions.headless().windowSize(screenSize)
|
||||
}
|
||||
|
||||
if (CHROME_BIN) {
|
||||
console.log("chrome bin", CHROME_BIN)
|
||||
chromeOptions.setChromeBinaryPath(path.resolve(CHROME_BIN))
|
||||
}
|
||||
|
||||
let seleniumServer
|
||||
|
||||
if (isBrowserStack) {
|
||||
seleniumServer = "http://hub-cloud.browserstack.com/wd/hub"
|
||||
} else if (global.seleniumServerPort) {
|
||||
seleniumServer = `http://localhost:${global.seleniumServerPort}/wd/hub`
|
||||
}
|
||||
|
||||
let browser = new Builder()
|
||||
.usingServer(seleniumServer)
|
||||
.withCapabilities(capabilities)
|
||||
.forBrowser(browserName)
|
||||
.setChromeOptions(chromeOptions)
|
||||
.setFirefoxOptions(firefoxOptions)
|
||||
.setSafariOptions(safariOptions)
|
||||
.build()
|
||||
|
||||
global.wd = browser
|
||||
|
||||
let initialWindow
|
||||
let deviceIP = "localhost"
|
||||
|
||||
const getDeviceIP = async () => {
|
||||
const networkIntfs = os.networkInterfaces()
|
||||
// find deviceIP to use with BrowserStack
|
||||
for (const intf of Object.keys(networkIntfs)) {
|
||||
const addresses = networkIntfs[intf]
|
||||
|
||||
for (const {internal, address, family} of addresses || []) {
|
||||
if (family !== "IPv4" || internal) continue
|
||||
try {
|
||||
const res = await fetch(`http://${address}:${global._newTabPort}`)
|
||||
if (res.ok) {
|
||||
deviceIP = address
|
||||
break
|
||||
}
|
||||
} catch (_) {}
|
||||
if (typeof afterAll === "function") {
|
||||
afterAll(async () => {
|
||||
if (browserQuit) {
|
||||
await browserQuit()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const closeBrowser = async () => {
|
||||
// First we close all extra windows left over
|
||||
let allWindows = await browser.getAllWindowHandles()
|
||||
|
||||
for (const win of allWindows) {
|
||||
if (win === initialWindow) continue
|
||||
try {
|
||||
await browser.switchTo().window(win)
|
||||
await browser.close()
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const freshWindow = async (appPort) => {
|
||||
// First we close all extra windows left over
|
||||
let allWindows = await browser.getAllWindowHandles()
|
||||
|
||||
for (const win of allWindows) {
|
||||
if (win === initialWindow) continue
|
||||
try {
|
||||
await browser.switchTo().window(win)
|
||||
await browser.close()
|
||||
} catch (_) {}
|
||||
}
|
||||
await browser.switchTo().window(initialWindow)
|
||||
|
||||
// now we open a fresh window
|
||||
await browser.get(`http://${deviceIP}:${global._newTabPort}`)
|
||||
|
||||
// await browser.executeScript(`window.location.href = "http://${deviceIP}:${appPort}"`)
|
||||
|
||||
const newTabLink = await browser.findElement(By.css("#new"))
|
||||
await newTabLink.click()
|
||||
|
||||
allWindows = await browser.getAllWindowHandles()
|
||||
const newWindow = allWindows.find((win) => win !== initialWindow)
|
||||
await browser.switchTo().window(newWindow!)
|
||||
}
|
||||
export const USE_SELENIUM = Boolean(
|
||||
process.env.LEGACY_SAFARI ||
|
||||
process.env.BROWSER_NAME === "internet explorer" ||
|
||||
process.env.SKIP_LOCAL_SELENIUM_SERVER,
|
||||
)
|
||||
|
||||
/**
|
||||
*
|
||||
* @param appPortOrUrl can either be the port or the full URL
|
||||
* @param url the path/query to append when using appPort
|
||||
* @param options.waitHydration whether to wait for react hydration to finish
|
||||
* @param options.retryWaitHydration allow retrying hydration wait if reload occurs
|
||||
* @param options.disableCache disable cache for page load
|
||||
* @param options.beforePageLoad the callback receiving page instance before loading page
|
||||
* @returns thenable browser instance
|
||||
*/
|
||||
export default async function webdriver(
|
||||
appPort,
|
||||
path,
|
||||
waitHydration = true,
|
||||
allowHydrationRetry = false,
|
||||
) {
|
||||
if (!initialWindow) {
|
||||
initialWindow = await browser.getWindowHandle()
|
||||
appPortOrUrl: string | number,
|
||||
url: string,
|
||||
options?: {
|
||||
waitHydration?: boolean
|
||||
retryWaitHydration?: boolean
|
||||
disableCache?: boolean
|
||||
beforePageLoad?: (page: any) => void
|
||||
locale?: string
|
||||
},
|
||||
): Promise<BrowserInterface> {
|
||||
let CurrentInterface: typeof BrowserInterface
|
||||
|
||||
const defaultOptions = {
|
||||
waitHydration: true,
|
||||
retryWaitHydration: false,
|
||||
disableCache: false,
|
||||
}
|
||||
if (isBrowserStack && deviceIP === "localhost" && !LEGACY_SAFARI) {
|
||||
await getDeviceIP()
|
||||
}
|
||||
// browser.switchTo().window() fails with `missing field `handle``
|
||||
// in safari and firefox so disabling freshWindow since our
|
||||
// tests shouldn't rely on it
|
||||
// if (isChrome) {
|
||||
// await freshWindow(appPort)
|
||||
options = Object.assign(defaultOptions, options)
|
||||
const {waitHydration, retryWaitHydration, disableCache, beforePageLoad, locale} = options
|
||||
|
||||
// we import only the needed interface
|
||||
// if (USE_SELENIUM) {
|
||||
// const browserMod = require('browsers/selenium')
|
||||
// CurrentInterface = browserMod.default
|
||||
// browserQuit = browserMod.quit
|
||||
// } else {
|
||||
// const browserMod = require('./browsers/playwright')
|
||||
// CurrentInterface = browserMod.default
|
||||
// browserQuit = browserMod.quit
|
||||
// }
|
||||
|
||||
const url = `http://${deviceIP}:${appPort}${path}`
|
||||
;(browser as any).initUrl = url
|
||||
console.log(`> Loading browser with ${url}`)
|
||||
CurrentInterface = browserMod
|
||||
browserQuit = quit
|
||||
|
||||
await browser.get(url)
|
||||
console.log(`> Loaded browser with ${url}`)
|
||||
const browser = new CurrentInterface()
|
||||
const browserName = process.env.BROWSER_NAME || "chrome"
|
||||
await browser.setup(browserName, locale)
|
||||
;(global as any).browserName = browserName
|
||||
|
||||
const fullUrl = getFullUrl(appPortOrUrl, url, "localhost")
|
||||
|
||||
console.log(`\n> Loading browser with ${fullUrl}\n`)
|
||||
|
||||
await browser.loadPage(fullUrl, {disableCache, beforePageLoad})
|
||||
console.log(`\n> Loaded browser with ${fullUrl}\n`)
|
||||
|
||||
// Wait for application to hydrate
|
||||
if (waitHydration) {
|
||||
// console.log(`\n> Waiting hydration for ${url}\n`)
|
||||
console.log(`\n> Waiting hydration for ${fullUrl}\n`)
|
||||
|
||||
const checkHydrated = async () => {
|
||||
await browser.executeAsyncScript(function () {
|
||||
await browser.evalAsync(function () {
|
||||
var callback = arguments[arguments.length - 1]
|
||||
|
||||
// if it's not a Next.js app return
|
||||
if (document.documentElement.innerHTML.indexOf("__NEXT_DATA__") === -1) {
|
||||
console.log("Not a next.js page, resolving hydrate check")
|
||||
callback()
|
||||
}
|
||||
|
||||
// TODO: should we also ensure router.isReady is true
|
||||
// by default before resolving?
|
||||
if ((window as any).__NEXT_HYDRATED) {
|
||||
console.log("Next.js page already hydrated")
|
||||
callback()
|
||||
} else {
|
||||
var timeout = setTimeout(callback, 10 * 1000)
|
||||
;(window as any).__NEXT_HYDRATED_CB = function () {
|
||||
clearTimeout(timeout)
|
||||
console.log("Next.js hydrate callback fired")
|
||||
callback()
|
||||
}
|
||||
}
|
||||
@@ -240,9 +109,9 @@ export default async function webdriver(
|
||||
try {
|
||||
await checkHydrated()
|
||||
} catch (err) {
|
||||
if (allowHydrationRetry) {
|
||||
if (retryWaitHydration) {
|
||||
// re-try in case the page reloaded during check
|
||||
await waitFor(2000)
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||
await checkHydrated()
|
||||
} else {
|
||||
console.error("failed to check hydration")
|
||||
@@ -250,17 +119,7 @@ export default async function webdriver(
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(`\n> Hydration complete for ${url}\n`)
|
||||
console.log(`\n> Hydration complete for ${fullUrl}\n`)
|
||||
}
|
||||
|
||||
const promiseProp = new Set(["then", "catch", "finally"])
|
||||
|
||||
return new Proxy(new Chain(browser), {
|
||||
get(obj, prop) {
|
||||
if (obj[prop] || promiseProp.has(prop as string)) {
|
||||
return obj[prop]
|
||||
}
|
||||
return browser[prop]
|
||||
},
|
||||
})
|
||||
return browser
|
||||
}
|
||||
|
||||
@@ -19,9 +19,13 @@
|
||||
"fs-extra": "10.0.1",
|
||||
"get-port": "6.1.2",
|
||||
"node-fetch": "3.2.3",
|
||||
"pkg-dir": "5.0.0",
|
||||
"playwright-chromium": "1.14.1",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.0",
|
||||
"react-query": "3.39.0",
|
||||
"resolve-cwd": "3.0.0",
|
||||
"resolve-from": "5.0.0",
|
||||
"rimraf": "3.0.2",
|
||||
"selenium-webdriver": "4.1.1",
|
||||
"tree-kill": "1.2.2",
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"clean": "turbo run clean && rm -rf node_modules",
|
||||
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
|
||||
"pre-publish": "changeset add && changeset version && pnpm build && git add . && git commit -v",
|
||||
"release": "pnpm build && changeset publish",
|
||||
"publish-release": "changeset publish && git push --follow-tags"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,5 +1,64 @@
|
||||
# @blitzjs/auth
|
||||
|
||||
## 2.0.0-alpha.32
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.32
|
||||
|
||||
## 2.0.0-alpha.31
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.31
|
||||
|
||||
## 2.0.0-alpha.30
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ce453683]
|
||||
- blitz@2.0.0-alpha.30
|
||||
|
||||
## 2.0.0-alpha.29
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [962eb58a]
|
||||
- blitz@2.0.0-alpha.29
|
||||
|
||||
## 2.0.0-alpha.28
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.28
|
||||
|
||||
## 2.0.0-alpha.27
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.27
|
||||
|
||||
## 2.0.0-alpha.26
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- blitz@2.0.0-alpha.26
|
||||
|
||||
## 2.0.0-alpha.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 1436e761: Add passport adapter to @blitzjs/auth
|
||||
- Updated dependencies [1436e761]
|
||||
- blitz@2.0.0-alpha.25
|
||||
|
||||
## 2.0.0-alpha.24
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8490b072]
|
||||
- blitz@2.0.0-alpha.24
|
||||
|
||||
## 2.0.0-alpha.23
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@blitzjs/auth",
|
||||
"version": "2.0.0-alpha.23",
|
||||
"version": "2.0.0-alpha.32",
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"predev": "wait-on -d 250 ../blitz/dist/index-server.d.ts",
|
||||
@@ -21,21 +21,25 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"@types/b64-lite": "1.3.0",
|
||||
"@types/cookie-session": "2.0.44",
|
||||
"@types/passport": "1.0.7",
|
||||
"@types/secure-password": "3.1.1",
|
||||
"b64-lite": "1.4.0",
|
||||
"bad-behavior": "1.0.1",
|
||||
"blitz": "2.0.0-alpha.23",
|
||||
"blitz": "2.0.0-alpha.32",
|
||||
"cookie": "0.4.1",
|
||||
"cookie-session": "2.0.0",
|
||||
"debug": "4.3.3",
|
||||
"http": "0.0.1-security",
|
||||
"jsonwebtoken": "8.5.1",
|
||||
"nanoid": "3.2.0",
|
||||
"passport": "0.5.2",
|
||||
"path": "0.12.7",
|
||||
"secure-password": "4.0.0",
|
||||
"url": "0.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.23",
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.32",
|
||||
"@testing-library/react": "13.0.0",
|
||||
"@testing-library/react-hooks": "7.0.2",
|
||||
"@types/cookie": "0.4.1",
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
createClientPlugin,
|
||||
AuthenticationError,
|
||||
RedirectError,
|
||||
RouteUrlObject,
|
||||
Ctx,
|
||||
} from "blitz"
|
||||
import {
|
||||
COOKIE_CSRF_TOKEN,
|
||||
@@ -26,7 +28,6 @@ import {
|
||||
} from "../shared"
|
||||
import _debug from "debug"
|
||||
import {formatWithValidation} from "../shared/url-utils"
|
||||
import {Ctx} from "blitz"
|
||||
import {ComponentType} from "react"
|
||||
import {ComponentProps} from "react"
|
||||
|
||||
@@ -190,9 +191,9 @@ export const useRedirectAuthenticated = (to: UrlObject | string) => {
|
||||
}
|
||||
}
|
||||
|
||||
export interface RouteUrlObject extends Pick<UrlObject, "pathname" | "query"> {
|
||||
pathname: string
|
||||
}
|
||||
// export interface RouteUrlObject extends Pick<UrlObject, "pathname" | "query"> {
|
||||
// pathname: string
|
||||
// }
|
||||
|
||||
export type RedirectAuthenticatedTo = string | RouteUrlObject | false
|
||||
export type RedirectAuthenticatedToFnCtx = {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./auth-sessions"
|
||||
export * from "./auth-utils"
|
||||
export * from "./auth-plugin"
|
||||
export * from "./passport-adapter"
|
||||
|
||||
204
packages/blitz-auth/src/server/passport-adapter.ts
Normal file
204
packages/blitz-auth/src/server/passport-adapter.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
/* @eslint-disable no-redeclare */
|
||||
import cookieSession from "cookie-session"
|
||||
import passport from "passport"
|
||||
import type {AuthenticateOptions, Strategy} from "passport"
|
||||
import {isLocalhost} from "./index"
|
||||
import {
|
||||
assert,
|
||||
connectMiddleware,
|
||||
Ctx,
|
||||
handleRequestWithMiddleware,
|
||||
Middleware,
|
||||
MiddlewareResponse,
|
||||
secureProxyMiddleware,
|
||||
} from "blitz"
|
||||
import {IncomingMessage, ServerResponse} from "http"
|
||||
import {PublicData, SessionContext} from "../shared"
|
||||
|
||||
const isFunction = (functionToCheck: unknown): functionToCheck is Function =>
|
||||
typeof functionToCheck === "function"
|
||||
|
||||
const isVerifyCallbackResult = (value: unknown): value is VerifyCallbackResult =>
|
||||
typeof value === "object" && value !== null && "publicData" in value
|
||||
|
||||
const INTERNAL_REDIRECT_URL_KEY = "_redirectUrl"
|
||||
|
||||
export interface BlitzPassportConfigCallbackParams {
|
||||
ctx: Ctx
|
||||
req: IncomingMessage
|
||||
res: ServerResponse
|
||||
}
|
||||
|
||||
export type BlitzPassportConfigCallback = ({
|
||||
ctx,
|
||||
req,
|
||||
res,
|
||||
}: BlitzPassportConfigCallbackParams) => BlitzPassportConfigObject
|
||||
|
||||
export type BlitzPassportConfig = BlitzPassportConfigObject | BlitzPassportConfigCallback
|
||||
|
||||
export type BlitzPassportStrategy = {
|
||||
authenticateOptions?: AuthenticateOptions
|
||||
strategy: Strategy
|
||||
}
|
||||
|
||||
export type BlitzPassportConfigObject = {
|
||||
successRedirectUrl?: string
|
||||
errorRedirectUrl?: string
|
||||
strategies: BlitzPassportStrategy[]
|
||||
secureProxy?: boolean
|
||||
}
|
||||
|
||||
export type VerifyCallbackResult = {
|
||||
publicData: PublicData
|
||||
privateData?: Record<string, unknown>
|
||||
redirectUrl?: string
|
||||
}
|
||||
|
||||
export type ApiHandlerIncomingMessage = IncomingMessage & {
|
||||
query: {
|
||||
[key: string]: string | string[]
|
||||
}
|
||||
}
|
||||
|
||||
export type ApiHandler = (
|
||||
req: ApiHandlerIncomingMessage,
|
||||
res: MiddlewareResponse & {status: (statusCode: number) => any},
|
||||
) => void | Promise<void>
|
||||
|
||||
export function passportAuth(config: BlitzPassportConfig): ApiHandler {
|
||||
return async function authHandler(req, res) {
|
||||
const configObject: BlitzPassportConfigObject = isFunction(config)
|
||||
? config({ctx: res.blitzCtx, req, res})
|
||||
: config
|
||||
|
||||
const cookieSessionMiddleware = cookieSession({
|
||||
secret: process.env.SESSION_SECRET_KEY || "default-dev-secret",
|
||||
secure: process.env.NODE_ENV === "production" && !isLocalhost(req),
|
||||
})
|
||||
|
||||
const passportMiddleware = passport.initialize()
|
||||
|
||||
const middleware: Middleware<ApiHandlerIncomingMessage, MiddlewareResponse<Ctx>>[] = [
|
||||
connectMiddleware(cookieSessionMiddleware as Middleware),
|
||||
connectMiddleware(passportMiddleware as Middleware),
|
||||
connectMiddleware(passport.session()),
|
||||
]
|
||||
|
||||
if (configObject.secureProxy) {
|
||||
middleware.push(secureProxyMiddleware)
|
||||
}
|
||||
|
||||
assert(
|
||||
req.query.auth,
|
||||
"req.query.auth is not defined. Page must be named [...auth].ts/js. See more at https://blitzjs.com/docs/passportjs#1-add-the-passport-js-api-route",
|
||||
)
|
||||
assert(
|
||||
Array.isArray(req.query.auth),
|
||||
"req.query.auth must be an array. Page must be named [...auth].ts/js. See more at https://blitzjs.com/docs/passportjs#1-add-the-passport-js-api-route",
|
||||
)
|
||||
|
||||
if (!req.query.auth.length) {
|
||||
return res.status(404).end()
|
||||
}
|
||||
|
||||
assert(
|
||||
configObject.strategies.length,
|
||||
"No Passport strategies found! Please add at least one strategy.",
|
||||
)
|
||||
|
||||
const blitzStrategy = configObject.strategies.find(
|
||||
({strategy}) => strategy.name === req.query?.auth?.[0] ?? "",
|
||||
)
|
||||
assert(blitzStrategy, `A passport strategy was not found for: ${req.query.auth[0]}`)
|
||||
|
||||
const {strategy, authenticateOptions} = blitzStrategy
|
||||
|
||||
passport.use(strategy)
|
||||
const strategyName = strategy.name as string
|
||||
|
||||
if (req.query.auth.length === 1) {
|
||||
console.info(`Starting authentication via ${strategyName}...`)
|
||||
if (req.query.redirectUrl) {
|
||||
// eslint-disable-next-line no-shadow
|
||||
middleware.push(async (req, res, next) => {
|
||||
const session = res.blitzCtx.session as SessionContext
|
||||
assert(session, "Missing Blitz sessionMiddleware!")
|
||||
await session.$setPublicData({
|
||||
[INTERNAL_REDIRECT_URL_KEY]: req.query.redirectUrl,
|
||||
} as any)
|
||||
return next()
|
||||
})
|
||||
}
|
||||
middleware.push(
|
||||
connectMiddleware(passport.authenticate(strategyName, {...authenticateOptions})),
|
||||
)
|
||||
} else if (req.query.auth[1] === "callback") {
|
||||
console.info(`Processing callback for ${strategyName}...`)
|
||||
middleware.push(
|
||||
// eslint-disable-next-line no-shadow
|
||||
connectMiddleware((req, res, next) => {
|
||||
const session = res.blitzCtx.session as SessionContext
|
||||
assert(session, "Missing Blitz sessionMiddleware!")
|
||||
|
||||
passport.authenticate(strategyName, async (err: any, result: any) => {
|
||||
try {
|
||||
let error = err
|
||||
|
||||
if (!error && result === false) {
|
||||
console.warn(
|
||||
`Login via ${strategyName} failed - usually this means the user did not authenticate properly with the provider`,
|
||||
)
|
||||
error = `Login failed`
|
||||
}
|
||||
|
||||
const redirectUrlFromVerifyResult =
|
||||
result && typeof result === "object" && result.redirectUrl
|
||||
let redirectUrl: string =
|
||||
redirectUrlFromVerifyResult ||
|
||||
(session.$publicData as any)[INTERNAL_REDIRECT_URL_KEY] ||
|
||||
(error ? configObject.errorRedirectUrl : configObject.successRedirectUrl) ||
|
||||
"/"
|
||||
|
||||
if (error) {
|
||||
redirectUrl += "?authError=" + encodeURIComponent(error.toString())
|
||||
res.setHeader("Location", redirectUrl)
|
||||
res.statusCode = 302
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
|
||||
assert(
|
||||
typeof result === "object" && result !== null,
|
||||
`Your '${strategyName}' passport verify callback returned empty data. Ensure you call 'done(null, {publicData: {userId: 1}})' along with any other publicData fields you need)`,
|
||||
)
|
||||
assert(
|
||||
(result as any).publicData,
|
||||
`'publicData' is missing from your '${strategyName}' passport verify callback. Ensure you call 'done(null, {publicData: {userId: 1}})' along with any other publicData fields you need)`,
|
||||
)
|
||||
assert(isVerifyCallbackResult(result), "Passport verify callback is invalid")
|
||||
|
||||
delete (result.publicData as any)[INTERNAL_REDIRECT_URL_KEY]
|
||||
|
||||
await session.$create(result.publicData, result.privateData)
|
||||
|
||||
res.setHeader("Location", redirectUrl)
|
||||
res.statusCode = 302
|
||||
res.end()
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
res.statusCode = 500
|
||||
res.end()
|
||||
}
|
||||
})(req, res, next)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
await handleRequestWithMiddleware<ApiHandlerIncomingMessage, MiddlewareResponse<Ctx>>(
|
||||
req,
|
||||
res,
|
||||
middleware,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,64 @@
|
||||
# @blitzjs/next
|
||||
|
||||
## 2.0.0-alpha.32
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.32
|
||||
|
||||
## 2.0.0-alpha.31
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [17ce29e5]
|
||||
- @blitzjs/rpc@2.0.0-alpha.31
|
||||
|
||||
## 2.0.0-alpha.30
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.30
|
||||
|
||||
## 2.0.0-alpha.29
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.29
|
||||
|
||||
## 2.0.0-alpha.28
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.28
|
||||
|
||||
## 2.0.0-alpha.27
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [07292910]
|
||||
- @blitzjs/rpc@2.0.0-alpha.27
|
||||
|
||||
## 2.0.0-alpha.26
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 0e762fb5: export BlitzPage & BlitzLayout types from @blitzjs/next
|
||||
- @blitzjs/rpc@2.0.0-alpha.26
|
||||
|
||||
## 2.0.0-alpha.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 931156c3: Rename prefetchBlitzQuery to prefetchQuery, add prefetchInfiniteQuery
|
||||
- b0c21b07: Move blitz config to next.config.js
|
||||
- @blitzjs/rpc@2.0.0-alpha.25
|
||||
|
||||
## 2.0.0-alpha.24
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- @blitzjs/rpc@2.0.0-alpha.24
|
||||
|
||||
## 2.0.0-alpha.23
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@blitzjs/next",
|
||||
"version": "2.0.0-alpha.23",
|
||||
"version": "2.0.0-alpha.32",
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"dev": "pnpm predev && pnpm watch unbuild src --wait=0.2",
|
||||
@@ -23,7 +23,7 @@
|
||||
"eslint.js"
|
||||
],
|
||||
"dependencies": {
|
||||
"@blitzjs/rpc": "2.0.0-alpha.23",
|
||||
"@blitzjs/rpc": "2.0.0-alpha.32",
|
||||
"@types/hoist-non-react-statics": "3.3.1",
|
||||
"debug": "4.3.3",
|
||||
"fs-extra": "10.0.1",
|
||||
@@ -32,7 +32,7 @@
|
||||
"superjson": "1.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.23",
|
||||
"@blitzjs/config": "workspace:2.0.0-alpha.32",
|
||||
"@testing-library/dom": "8.13.0",
|
||||
"@testing-library/jest-dom": "5.16.3",
|
||||
"@testing-library/react": "13.0.0",
|
||||
@@ -43,7 +43,7 @@
|
||||
"@types/react": "18.0.1",
|
||||
"@types/react-dom": "17.0.14",
|
||||
"@types/testing-library__react-hooks": "4.0.0",
|
||||
"blitz": "2.0.0-alpha.23",
|
||||
"blitz": "2.0.0-alpha.32",
|
||||
"cross-spawn": "7.0.3",
|
||||
"find-up": "4.1.0",
|
||||
"lodash.frompairs": "4.0.1",
|
||||
|
||||
@@ -5,12 +5,15 @@ import type {
|
||||
UnionToIntersection,
|
||||
Simplify,
|
||||
} from "blitz"
|
||||
import {AppProps} from "next/app"
|
||||
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"
|
||||
import {Ctx} from "blitz"
|
||||
import {UrlObject} from "url"
|
||||
import {AppPropsType} from "next/dist/shared/lib/utils"
|
||||
import {Router} from "next/router"
|
||||
|
||||
export * from "./error-boundary"
|
||||
export * from "./error-component"
|
||||
@@ -68,6 +71,27 @@ export type BlitzProviderProps = {
|
||||
hydrateOptions?: HydrateOptions
|
||||
}
|
||||
|
||||
interface RouteUrlObject extends Pick<UrlObject, "pathname" | "query"> {
|
||||
pathname: string
|
||||
}
|
||||
type RedirectAuthenticatedTo = string | RouteUrlObject | false
|
||||
type RedirectAuthenticatedToFnCtx = {
|
||||
session: Ctx["session"]["$publicData"]
|
||||
}
|
||||
type RedirectAuthenticatedToFn = (args: RedirectAuthenticatedToFnCtx) => RedirectAuthenticatedTo
|
||||
export type BlitzPage<P = {}> = React.ComponentType<P> & {
|
||||
getLayout?: (component: JSX.Element) => JSX.Element
|
||||
authenticate?: boolean | {redirectTo?: string}
|
||||
suppressFirstRenderFlicker?: boolean
|
||||
redirectAuthenticatedTo?: RedirectAuthenticatedTo | RedirectAuthenticatedToFn
|
||||
}
|
||||
export type BlitzLayout<P = {}> = React.ComponentType<P> & {
|
||||
authenticate?: boolean | {redirectTo?: string | RouteUrlObject}
|
||||
redirectAuthenticatedTo?: RedirectAuthenticatedTo | RedirectAuthenticatedToFn
|
||||
}
|
||||
export type AppProps<P = {}> = AppPropsType<Router, P> & {
|
||||
Component: BlitzPage
|
||||
}
|
||||
const BlitzProvider = ({
|
||||
client,
|
||||
contextSharing = false,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user