Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

refactor(ts): de-duplicate types #1690

Merged
merged 28 commits into from
Apr 19, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
2f0ddd5
refactor(ts): deduplicate internal types
balazsorban44 Apr 11, 2021
eabd50f
refactor(ts): ease up providers typings
balazsorban44 Apr 11, 2021
6b4533d
test(ts): fix failing TS tests
balazsorban44 Apr 11, 2021
6f25866
test(ts): rename TS property to fix test
balazsorban44 Apr 11, 2021
2acdb32
docs(ts): mention TS docs in README.md
balazsorban44 Apr 16, 2021
9f1351e
feat(ts): move/update client types
balazsorban44 Apr 16, 2021
8448ab1
refactor(TS): rename some types
balazsorban44 Apr 16, 2021
085325e
test(ts): fix client tests
balazsorban44 Apr 16, 2021
02ff7e1
docs(ts): move function descriptions to .d.ts
balazsorban44 Apr 16, 2021
186b061
chore: fix lint error
balazsorban44 Apr 16, 2021
5278e01
refactor(ts): separate internal types
balazsorban44 Apr 17, 2021
352d3e8
chore: simplify build-types script
balazsorban44 Apr 17, 2021
304d055
chore: update type import paths in src
balazsorban44 Apr 17, 2021
dc27eda
chore(build): create root files at build
balazsorban44 Apr 17, 2021
5d03732
chore: remove unnecessary .npmignore
balazsorban44 Apr 17, 2021
9a3b731
Merge branch 'beta' into feat/deduplicate-types
balazsorban44 Apr 17, 2021
9986c48
chore: run prettier on types
balazsorban44 Apr 17, 2021
c92dce2
fix(ts): clean up jwt types
balazsorban44 Apr 17, 2021
d74df69
fix(ts): make getToken return type depend on raw param
balazsorban44 Apr 17, 2021
2579de2
docs(page): explain page errors, add theming note
balazsorban44 Apr 19, 2021
06583f2
docs(ts): add JSDoc to NextAuthOptions props
balazsorban44 Apr 19, 2021
65fcc39
chore(ts): remove unused import
balazsorban44 Apr 19, 2021
2c1bd3a
docs(ts): change JSDOC docs notation
balazsorban44 Apr 19, 2021
20a6697
refactor(build): extract module entries into enum
balazsorban44 Apr 19, 2021
07a61b0
chore(ts): move ClientSafeProvider
balazsorban44 Apr 19, 2021
652e97e
chore(ts): simplify GetTokenParams generic
balazsorban44 Apr 19, 2021
8573aee
style(lint): fix linting errors
balazsorban44 Apr 19, 2021
2c1369c
chore: re-add generic extension to GetTokenParams
balazsorban44 Apr 19, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions src/lib/logger.d.ts

This file was deleted.

10 changes: 5 additions & 5 deletions src/lib/logger.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** @type {import("./logger").LoggerInstance} */
/** @type {import("types").LoggerInstance} */
const _logger = {
error (code, ...message) {
console.error(
Expand Down Expand Up @@ -26,7 +26,7 @@ const _logger = {
/**
* Override the built-in logger.
* Any `undefined` level will use the default logger.
* @param {Partial<import("./logger").LoggerInstance>} newLogger
* @param {Partial<import("types").LoggerInstance>} newLogger
*/
export function setLogger (newLogger = {}) {
if (newLogger.error) _logger.error = newLogger.error
Expand All @@ -38,17 +38,17 @@ export default _logger

/**
* Serializes client-side log messages and sends them to the server
* @param {import("./logger").LoggerInstance} logger
* @param {import("types").LoggerInstance} logger
* @param {string} basePath
* @return {import("./logger").LoggerInstance}
* @return {import("types").LoggerInstance}
*/
export function proxyLogger (logger = _logger, basePath) {
try {
if (typeof window === 'undefined') {
return logger
}

const clientLogger = {}
const clientLogger = console
for (const level in logger) {
clientLogger[level] = (code, ...message) => {
_logger[level](code, ...message) // Log on client as usual
Expand Down
2 changes: 1 addition & 1 deletion src/providers/instagram.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* @param {import("../server").Provider} options
* @type {import("types/providers").OAuthProvider} options
* @example
*
* ```js
Expand Down
94 changes: 0 additions & 94 deletions src/server/index.d.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ if (!process.env.NEXTAUTH_URL) {
/**
* @param {import("next").NextApiRequest} req
* @param {import("next").NextApiResponse} res
* @param {import(".").NextAuthOptions} userOptions
* @param {import("types").NextAuthOptions} userOptions
*/
async function NextAuthHandler (req, res, userOptions) {
if (userOptions.logger) {
Expand Down
7 changes: 0 additions & 7 deletions src/server/lib/callbacks.d.ts

This file was deleted.

16 changes: 0 additions & 16 deletions src/server/lib/cookie.d.ts

This file was deleted.

46 changes: 34 additions & 12 deletions src/server/lib/cookie.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
* (with fixes for specific issues) to keep dependancy size down.
*/
export function set (res, name, value, options = {}) {
const stringValue = typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)
const stringValue =
typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)

if ('maxAge' in options) {
options.expires = new Date(Date.now() + options.maxAge)
Expand All @@ -19,7 +20,9 @@ export function set (res, name, value, options = {}) {
// Preserve any existing cookies that have already been set in the same session
let setCookieHeader = res.getHeader('Set-Cookie') || []
// If not an array (i.e. a string with a single cookie) convert it into an array
if (!Array.isArray(setCookieHeader)) { setCookieHeader = [setCookieHeader] }
if (!Array.isArray(setCookieHeader)) {
setCookieHeader = [setCookieHeader]
}
setCookieHeader.push(_serialize(name, String(stringValue), options))
res.setHeader('Set-Cookie', setCookieHeader)
}
Expand All @@ -30,32 +33,44 @@ function _serialize (name, val, options) {
const opt = options || {}
const enc = opt.encode || encodeURIComponent

if (typeof enc !== 'function') { throw new TypeError('option encode is invalid') }
if (typeof enc !== 'function') {
throw new TypeError('option encode is invalid')
}

if (!fieldContentRegExp.test(name)) { throw new TypeError('argument name is invalid') }
if (!fieldContentRegExp.test(name)) {
throw new TypeError('argument name is invalid')
}

const value = enc(val)

if (value && !fieldContentRegExp.test(value)) { throw new TypeError('argument val is invalid') }
if (value && !fieldContentRegExp.test(value)) {
throw new TypeError('argument val is invalid')
}

let str = name + '=' + value

if (opt.maxAge != null) {
const maxAge = opt.maxAge - 0

if (isNaN(maxAge) || !isFinite(maxAge)) { throw new TypeError('option maxAge is invalid') }
if (isNaN(maxAge) || !isFinite(maxAge)) {
throw new TypeError('option maxAge is invalid')
}

str += '; Max-Age=' + Math.floor(maxAge)
}

if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) { throw new TypeError('option domain is invalid') }
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError('option domain is invalid')
}

str += '; Domain=' + opt.domain
}

if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) { throw new TypeError('option path is invalid') }
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError('option path is invalid')
}

str += '; Path=' + opt.path
} else {
Expand All @@ -73,12 +88,19 @@ function _serialize (name, val, options) {
str += '; Expires=' + expires
}

if (opt.httpOnly) { str += '; HttpOnly' }
if (opt.httpOnly) {
str += '; HttpOnly'
}

if (opt.secure) { str += '; Secure' }
if (opt.secure) {
str += '; Secure'
}

if (opt.sameSite) {
const sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite
const sameSite =
typeof opt.sameSite === 'string'
? opt.sameSite.toLowerCase()
: opt.sameSite

switch (sameSite) {
case true:
Expand Down Expand Up @@ -110,7 +132,7 @@ function _serialize (name, val, options) {
* For more on prefixes see https://googlechrome.github.io/samples/cookie-prefixes/
*
* @TODO Review cookie settings (names, options)
* @return {import("./cookie").CookiesOptions}
* @return {import("types").CookiesOptions}
*/
export function defaultCookies (useSecureCookies) {
const cookiePrefix = useSecureCookies ? '__Secure-' : ''
Expand Down
12 changes: 0 additions & 12 deletions src/server/lib/events.d.ts

This file was deleted.

14 changes: 3 additions & 11 deletions src/server/lib/oauth/callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import oAuthClient from './client'
import logger from '../../../lib/logger'
import { OAuthCallbackError } from '../../../lib/errors'

/** @param {import("../..").NextAuthRequest} req */
/** @param {import("types").NextAuthRequest} req */
export default async function oAuthCallback (req) {
const { provider, pkce } = req.options
const client = oAuthClient(provider)
Expand Down Expand Up @@ -81,16 +81,8 @@ export default async function oAuthCallback (req) {
* Returns profile, raw profile and auth provider details
* @param {{
* profileData: object | string
* tokens: {
* accessToken: string
* idToken?: string
* refreshToken?: string
* access_token: string
* expires_in?: string | Date | null
* refresh_token?: string
* id_token?: string
* }
* provider: import("../..").Provider
* tokens: import("types").TokenSet
* provider: import("types/providers").OAuthConfig
* user?: object
* }} profileParams
*/
Expand Down
6 changes: 3 additions & 3 deletions src/server/lib/oauth/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { sign as jwtSign } from 'jsonwebtoken'
* @TODO Refactor to remove dependancy on 'oauth' package
* It is already quite monkey patched, we don't use all the features and and it
* would be easier to maintain if all the code was native to next-auth.
* @param {import("../..").Provider} provider
* @param {import("types/providers").OAuthConfig} provider
*/
export default function oAuthClient (provider) {
if (provider.version?.startsWith('2.')) {
Expand Down Expand Up @@ -88,7 +88,7 @@ export default function oAuthClient (provider) {
/**
* Ported from https://github.com/ciaranj/node-oauth/blob/a7f8a1e21c362eb4ed2039431fb9ac2ae749f26a/lib/oauth2.js
* @param {string} code
* @param {import("../..").Provider} provider
* @param {import("types/providers").OAuthConfig} provider
* @param {string | undefined} codeVerifier
*/
async function getOAuth2AccessToken (code, provider, codeVerifier) {
Expand Down Expand Up @@ -196,7 +196,7 @@ async function getOAuth2AccessToken (code, provider, codeVerifier) {
*
* 18/08/2020 @robertcraigie added results parameter to pass data to an optional request preparer.
* e.g. see providers/bungie
* @param {import("../..").Provider} provider
* @param {import("types/providers").OAuthConfig} provider
* @param {string} accessToken
* @param {any} results
*/
Expand Down
8 changes: 4 additions & 4 deletions src/server/lib/oauth/pkce-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ const PKCE_MAX_AGE = 60 * 15 // 15 minutes in seconds

/**
* Adds `code_verifier` to `req.options.pkce`, and removes the corresponding cookie
* @param {import("../..").NextAuthRequest} req
* @param {import("../..").NextAuthResponse} res
* @param {import("types").NextAuthRequest} req
* @param {import("types").NextAuthResponse} res
*/
export async function handleCallback (req, res) {
const { cookies, provider, baseUrl, basePath } = req.options
Expand Down Expand Up @@ -44,8 +44,8 @@ export async function handleCallback (req, res) {

/**
* Adds `code_challenge` and `code_challenge_method` to `req.options.pkce`.
* @param {import("../..").NextAuthRequest} req
* @param {import("../..").NextAuthResponse} res
* @param {import("types").NextAuthRequest} req
* @param {import("types").NextAuthResponse} res
*/
export async function handleSignin (req, res) {
const { cookies, provider, baseUrl, basePath } = req.options
Expand Down
8 changes: 4 additions & 4 deletions src/server/lib/oauth/state-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { OAuthCallbackError } from '../../../lib/errors'
* For OAuth 2.0 flows, if the provider supports state,
* check if state matches the one sent on signin
* (a hash of the NextAuth.js CSRF token).
* @param {import("../..").NextAuthRequest} req
* @param {import("../..").NextAuthResponse} res
* @param {import("types").NextAuthRequest} req
* @param {import("types").NextAuthResponse} res
*/
export async function handleCallback (req, res) {
const { csrfToken, provider, baseUrl, basePath } = req.options
Expand Down Expand Up @@ -35,8 +35,8 @@ export async function handleCallback (req, res) {

/**
* Adds CSRF token to the authorizationParams.
* @param {import("../..").NextAuthRequest} req
* @param {import("../..").NextAuthResponse} res
* @param {import("types").NextAuthRequest} req
* @param {import("types").NextAuthResponse} res
*/
export async function handleSignin (req, res) {
const { provider, baseUrl, basePath, csrfToken } = req.options
Expand Down
Loading