Skip to content

Commit f802558

Browse files
committed
feat(logs): use consola for logs
This allows to control the level of logs with `CONSOLA_LEVEL=5 pnpm run dev`
1 parent 7c21690 commit f802558

13 files changed

+118
-123
lines changed

Diff for: build.config.ts

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export default defineBuildConfig({
2929
'firebase-admin/auth',
3030
'firebase-functions',
3131
'firebase-functions/params',
32+
'consola',
3233
],
3334

3435
rollup: {

Diff for: package.json

+5
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@
6767
"vue-demi": "latest"
6868
},
6969
"peerDependencies": {
70+
"consola": "^3.2.3",
7071
"firebase": "^9.0.0 || ^10.0.0",
7172
"vue": "^2.7.0 || ^3.2.0"
7273
},
@@ -76,13 +77,17 @@
7677
},
7778
"@vue/composition-api": {
7879
"optional": true
80+
},
81+
"consola": {
82+
"optional": true
7983
}
8084
},
8185
"devDependencies": {
8286
"@vitest/coverage-v8": "^0.33.0",
8387
"@vue/runtime-core": "^3.3.4",
8488
"@vue/test-utils": "^2.4.0",
8589
"chalk": "^5.3.0",
90+
"consola": "^3.2.3",
8691
"conventional-changelog-cli": "^2.0.34",
8792
"enquirer": "^2.3.6",
8893
"execa": "^7.1.1",

Diff for: packages/nuxt/build.config.ts

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { defineBuildConfig } from 'unbuild'
2+
3+
export default defineBuildConfig({
4+
// explicitly externalize consola since Nuxt has it
5+
externals: ['consola'],
6+
})

Diff for: packages/nuxt/src/module.ts

+6-7
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ import type {
1616
App as FirebaseAdminApp,
1717
} from 'firebase-admin/app'
1818
import { markRaw } from 'vue'
19+
import { consola } from 'consola'
1920
import type { NuxtVueFireAppCheckOptions } from './runtime/app-check'
20-
import { log } from './runtime/logging'
2121

2222
export interface VueFireNuxtModuleOptions {
2323
/**
@@ -63,6 +63,8 @@ export interface VueFireNuxtModuleOptions {
6363
auth?: boolean
6464
}
6565

66+
const logger = consola.withTag('nuxt-vuefire module')
67+
6668
export default defineNuxtModule<VueFireNuxtModuleOptions>({
6769
meta: {
6870
name: 'vuefire',
@@ -126,8 +128,7 @@ export default defineNuxtModule<VueFireNuxtModuleOptions>({
126128

127129
if (options.auth) {
128130
if (nuxt.options.ssr && !hasServiceAccount) {
129-
log(
130-
'warn',
131+
logger.warn(
131132
'You activated both SSR and auth but you are not providing a service account for the admin SDK. See https://vuefire.vuejs.org/nuxt/getting-started.html#configuring-the-admin-sdk.'
132133
)
133134
}
@@ -138,8 +139,7 @@ export default defineNuxtModule<VueFireNuxtModuleOptions>({
138139
if (hasServiceAccount) {
139140
addPlugin(resolve(runtimeDir, 'app-check/plugin.server'))
140141
} else if (nuxt.options.ssr) {
141-
log(
142-
'warn',
142+
logger.warn(
143143
'You activated both SSR and app-check but you are not providing a service account for the admin SDK. See https://vuefire.vuejs.org/nuxt/getting-started.html#configuring-the-admin-sdk.'
144144
)
145145
}
@@ -192,8 +192,7 @@ export default defineNuxtModule<VueFireNuxtModuleOptions>({
192192
// we start the admin app before the regular app so we can have access to the user uid everywhere
193193
if (options.admin || nuxt.options.ssr) {
194194
if (!nuxt.options.ssr) {
195-
log(
196-
'warn',
195+
logger.warn(
197196
'The "admin" option is only used during SSR. You should reenable SSR to use it or remove it if you are not doing SSR or SSG.'
198197
)
199198
}

Diff for: packages/nuxt/src/runtime/app/plugin.server.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { deleteApp, type FirebaseApp, initializeApp } from 'firebase/app'
22
import { type User } from 'firebase/auth'
33
import { DecodedIdToken } from 'firebase-admin/auth'
44
import { LRUCache } from 'lru-cache'
5-
import { log } from '../logging'
5+
import { logger } from '../logging'
66
import { DECODED_ID_TOKEN_SYMBOL } from '../constants'
77
import { defineNuxtPlugin, useAppConfig } from '#app'
88

@@ -36,21 +36,21 @@ export default defineNuxtPlugin((nuxtApp) => {
3636

3737
let firebaseApp: FirebaseApp | undefined
3838

39-
// log('debug', 'initializing app with', appConfig.firebaseConfig)
39+
// logger.debug('initializing app with', appConfig.firebaseConfig)
4040
if (uid) {
4141
firebaseApp = appCache.get(uid)
4242
if (!firebaseApp) {
4343
const randomId = Math.random().toString(36).slice(2)
4444
// TODO: do we need a randomId?
4545
const appName = `auth:${uid}:${randomId}`
4646

47-
log('debug', '👤 creating new app', appName)
47+
logger.debug('👤 creating new app', appName)
4848

4949
appCache.set(uid, initializeApp(appConfig.firebaseConfig, appName))
5050
firebaseApp = appCache.get(uid)!
5151
// console.time('token')
5252
} else {
53-
log('debug', '👤 reusing authenticated app', firebaseApp.name)
53+
logger.debug('👤 reusing authenticated app', firebaseApp.name)
5454
}
5555
} else {
5656
// TODO: is this safe? should we create a new one everytime
@@ -59,7 +59,7 @@ export default defineNuxtPlugin((nuxtApp) => {
5959
}
6060
firebaseApp = appCache.get('')!
6161
// anonymous session, just create a new app
62-
log('debug', '🥸 anonymous session')
62+
logger.debug('🥸 anonymous session')
6363
}
6464

6565
return {

Diff for: packages/nuxt/src/runtime/auth/api.session-verification.ts

+6-7
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
setResponseStatus,
99
} from 'h3'
1010
import { getAdminApp } from 'vuefire/server'
11-
import { log } from '../logging'
11+
import { logger } from '../logging'
1212

1313
/**
1414
* Setups an API endpoint to be used by the client to mint a cookie based auth session.
@@ -17,11 +17,11 @@ export default defineEventHandler(async (event) => {
1717
assertMethod(event, 'POST')
1818
const { token } = await readBody<{ token?: string }>(event)
1919

20-
log('debug', 'Getting the admin app')
20+
logger.debug('Getting the admin app')
2121
const adminApp = getAdminApp({}, 'session-verification')
2222
const adminAuth = getAdminAuth(adminApp)
2323

24-
log('debug', 'read idToken from Authorization header', token)
24+
logger.debug(token ? 'Verifying the token' : 'Deleting the session cookie')
2525
const verifiedIdToken = token ? await adminAuth.verifyIdToken(token) : null
2626

2727
if (verifiedIdToken) {
@@ -31,11 +31,10 @@ export default defineEventHandler(async (event) => {
3131
const cookie = await adminAuth
3232
.createSessionCookie(token!, { expiresIn: AUTH_COOKIE_MAX_AGE })
3333
.catch((e: any) => {
34-
log('error', 'Error minting the cookie -', e.message)
35-
log('error', e)
34+
logger.error('Error minting the cookie', e)
3635
})
3736
if (cookie) {
38-
// log('debug', `minted a session cookie for user ${verifiedIdToken.uid}`)
37+
// logger.debug(`minted a session cookie for user ${verifiedIdToken.uid}`)
3938
setCookie(event, AUTH_COOKIE_NAME, cookie, {
4039
maxAge: AUTH_COOKIE_MAX_AGE,
4140
secure: true,
@@ -51,7 +50,7 @@ export default defineEventHandler(async (event) => {
5150
}
5251
}
5352
} else {
54-
// log('debug', 'deleting the session cookie')
53+
// logger.debug('deleting the session cookie')
5554
deleteCookie(event, AUTH_COOKIE_NAME)
5655
setResponseStatus(event, 204)
5756
}

Diff for: packages/nuxt/src/runtime/auth/plugin.server.ts

+5-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type { FirebaseApp } from 'firebase/app'
44
import type { App as AdminApp } from 'firebase-admin/app'
55
import { VueFireAuthServer } from 'vuefire/server'
66
import { DECODED_ID_TOKEN_SYMBOL, UserSymbol } from '../constants'
7-
import { log } from '../logging'
7+
import { logger } from '../logging'
88
import { defineNuxtPlugin, useRequestEvent } from '#app'
99

1010
/**
@@ -30,7 +30,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
3030
const customToken = await adminAuth
3131
.createCustomToken(uid)
3232
.catch((err) => {
33-
log('error', 'Error creating custom token', err)
33+
logger.error('Error creating custom token', err)
3434
return null
3535
})
3636
// console.timeLog('token', `got token for ${user.uid}`)
@@ -50,12 +50,14 @@ export default defineNuxtPlugin(async (nuxtApp) => {
5050
UserSymbol as unknown as string
5151
] = user
5252
// expose the user to requests
53+
// FIXME: should be doable in nitro server routes too
54+
// use addServerPlugin
5355
event.context.user = user
5456
// Hydrates the user
5557
nuxtApp.payload.vuefireUser = user?.toJSON()
5658
}
5759

58-
// log('debug', 'setting up user for app', firebaseApp.name, user?.uid)
60+
// logger.debug('setting up user for app', firebaseApp.name, user?.uid)
5961

6062
// provide the user data to the app during ssr
6163
VueFireAuthServer(firebaseApp, nuxtApp.vueApp, auth.currentUser)

Diff for: packages/nuxt/src/runtime/logging.ts

+16-21
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,19 @@
1-
export type LogType = 'debug' | 'info' | 'warn' | 'error' | 'trace' | 'log'
1+
import { consola as consolaBase } from 'consola'
2+
export type { LogType } from 'consola'
23

3-
// TODO: allow disabling logs with some env variables
4+
const nuxtVueFireConsola = consolaBase.withTag('nuxt-vuefire')
45

5-
export function log(type: LogType, ...args: any[]): void
6-
export function log(...args: any[]): void
7-
export function log(...args: unknown[]): void {
8-
const [typeOrLog, ...rest] = args
9-
if (isLogType(typeOrLog)) {
10-
console[typeOrLog]('[nuxt-vuefire]:', ...rest)
11-
} else {
12-
console.log('[nuxt-vuefire]:', ...args)
13-
}
14-
}
6+
export { nuxtVueFireConsola as logger }
157

16-
function isLogType(logType: unknown): logType is LogType {
17-
return (
18-
logType === 'debug' ||
19-
logType === 'info' ||
20-
logType === 'warn' ||
21-
logType === 'error' ||
22-
logType === 'trace'
23-
)
24-
}
8+
// run this to have more levels of logging
9+
// https://github.com/unjs/consola#log-level
10+
// CONSOLA_LEVEL=5 nr dev
11+
12+
// NOTE: used to test
13+
// nuxtVueFireConsola.trace('trace', 'i am a test')
14+
// nuxtVueFireConsola.debug('debug', 'i am a test')
15+
// nuxtVueFireConsola.log('log', 'i am a test')
16+
// nuxtVueFireConsola.info('info', 'i am a test')
17+
// nuxtVueFireConsola.success('success', 'i am a test')
18+
// nuxtVueFireConsola.warn('warn', 'i am a test')
19+
// nuxtVueFireConsola.error('error', 'i am a test', new Error('haha'))

0 commit comments

Comments
 (0)