Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: allow multiple nuxt in a single process #30510

Open
wants to merge 24 commits into
base: main
Choose a base branch
from

Conversation

huang-julien
Copy link
Member

@huang-julien huang-julien commented Jan 9, 2025

🔗 Linked issue

unblocked by nitrojs/nitro#2983 ❤️
fix nuxt/test-utils#537
fix nuxt/test-utils#1034
resolve nuxt/test-utils#664
fix #22565

📚 Description

This PR allows to create multiple Nuxt instance within a single process.

We were previously setting a Nuxt Singleton with unctx. This means that we can only run a single Nuxt instance in a single process.

By using asyncLocalStorage, we'll be able to track an unique id for each buildNuxt and initNuxt -> allowing to run these in parallel and all useNuxt() within it. It also convert nuxtCtx to be a getter so it retrieves the correct namespace with ASyncLocalStorage

For backward compatibility, we'll keep a fallback global singleton of the first Nuxt instance that is being set. This behavior CAN be removed in V5. We can also add a .run on the Nuxt build instance later.

next step: merge all nuxt test within a single job

Copy link

stackblitz bot commented Jan 9, 2025

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

socket-security bot commented Jan 9, 2025

New, updated, and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@vue/[email protected] 🔁 npm/@vue/[email protected] Transitive: network +3 554 kB webfansplz
npm/[email protected] environment, filesystem +29 10.4 MB posva

🚮 Removed packages: npm/[email protected], npm/[email protected]

View full report↗︎

@huang-julien
Copy link
Member Author

/ecosystem-ci run

@nuxt-ecosystem-ci
Copy link

📝 Ran ecosystem CI on 0b4781e: Open

suite result latest scheduled
content failure success
ui failure failure
image failure success
pinia failure success
examples failure success
bridge failure success
vite-pwa failure success
docus failure success
og-image failure success
histoire failure failure
elk failure failure
devtools failure failure
fonts failure failure
scripts failure success
icon failure success
test-utils failure success
module-builder failure success
sanity-module failure success
sitemap failure success
i18n-module failure success
werewolves-assistant failure failure
storybook failure failure

starter, example-layers-monorepo, nuxt-com, cli, tailwindcss

@huang-julien
Copy link
Member Author

ecosystem ci fails due to typecheck

@huang-julien
Copy link
Member Author

huang-julien commented Jan 11, 2025

return nuxtCtx.tryUse()
const nuxt = nuxtCtx().tryUse()
if (!nuxt) {
logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.')
Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure how to rephrase this to make it sound a bit gentler 😅. Any suggestions?

cc @danielroe

Copy link
Member Author

Choose a reason for hiding this comment

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

this also isn't going to be remove d in V4, maybe in V5 🤔

@huang-julien huang-julien marked this pull request as ready for review January 11, 2025 16:53
Copy link

coderabbitai bot commented Jan 11, 2025

Walkthrough

The pull request introduces significant changes to the Nuxt context management system across multiple packages. The primary modifications focus on enhancing context retrieval and management using asynchronous local storage. A new getNuxtCtx function is implemented to retrieve the Nuxt context, replacing the previous static context approach.

The changes introduce a unique identifier (__name) for Nuxt instances, enabling better tracking and debugging, especially in complex environments like mono-repositories. The implementation adds asyncNameStorage to manage asynchronous contexts, allowing for more robust context handling during Nuxt instance creation, hook execution, and build processes.

The modifications include updates to context retrieval methods, fallback mechanisms for global context usage, and improved logging for deprecated usage patterns. These changes aim to provide more flexible and reliable context management across different Nuxt operations, with a focus on asynchronous execution and context tracking.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
packages/kit/src/context.ts (1)

26-26: 🛠️ Refactor suggestion

Rephrase the deprecation warning for clarity and correct version

The warning message could be phrased more gently and should reflect the correct version in which the deprecation will occur.

Suggested change:

-logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behaviour is deprecated and will be removed in v4.')
+logger.warn('Using fallback global Nuxt instance. Using @nuxt/kit composables outside of a Nuxt context is deprecated and will be removed in v5. Please ensure you are within a proper Nuxt context.')

Also applies to: 50-50

🧹 Nitpick comments (3)
packages/nuxt/test/load-nuxt.test.ts (1)

47-56: Enhance test coverage for multiple Nuxt instances.

Whilst the test verifies concurrent loading, it could be more robust with:

  1. Assertions to verify each instance has a unique __name
  2. Verification that each instance operates independently
  3. Cleanup of instances after the test
 it('load multiple nuxt', async () => {
-  await Promise.all([
+  const [nuxt1, nuxt2] = await Promise.all([
     loadNuxt({
       cwd: repoRoot,
     }),
     loadNuxt({
       cwd: repoRoot,
     }),
   ])
+  expect(nuxt1.__name).toBeDefined()
+  expect(nuxt2.__name).toBeDefined()
+  expect(nuxt1.__name).not.toBe(nuxt2.__name)
+  await Promise.all([nuxt1.close(), nuxt2.close()])
 })
packages/nuxt/src/core/nuxt.ts (2)

54-54: Consider documenting the new __name property.

The new __name property and its usage with asyncNameStorage should be documented to help users understand how multiple Nuxt instances are managed.

Would you like me to generate documentation for the new __name property and its role in multi-instance support?

Also applies to: 62-62, 66-66


178-189: Enhance the backward compatibility comment.

The comment "backward compatibility with 3.x" could be more descriptive to explain why and how the global singleton is maintained.

Consider updating the comment to:

-    // backward compatibility with 3.x
+    // Maintain backward compatibility with Nuxt 3.x by setting the first instance as global singleton.
+    // This ensures existing applications continue to work without modifications.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7dba335 and 982af4e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (8)
  • packages/kit/src/context.ts (3 hunks)
  • packages/kit/src/index.ts (2 hunks)
  • packages/kit/src/loader/nuxt.ts (2 hunks)
  • packages/kit/src/utils.ts (1 hunks)
  • packages/nuxt/src/core/nuxt.ts (4 hunks)
  • packages/nuxt/test/load-nuxt.test.ts (1 hunks)
  • packages/schema/src/types/nuxt.ts (1 hunks)
  • test/bundle.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: code
🔇 Additional comments (6)
packages/kit/src/loader/nuxt.ts (1)

44-44: Ensure nuxt.__name is defined before using it in asyncNameStorage.run

If nuxt.__name is undefined or not set, calling asyncNameStorage.run(nuxt.__name, ...) may cause unexpected behaviour. Please verify that __name is properly initialised on the nuxt instance.

You might consider adding a default name or handling the undefined case:

-return asyncNameStorage.run(nuxt.__name, () => build(nuxt))
+const name = nuxt.__name || 'default-nuxt-instance'
+return asyncNameStorage.run(name, () => build(nuxt))
packages/kit/src/index.ts (2)

21-21: LGTM! Context management exports look good.

The renaming of nuxtCtx to getNuxtCtx and addition of globalNuxtCtx properly support both the new multi-instance capability and maintain backward compatibility.


37-37: LGTM! Async storage export enables instance tracking.

The export of asyncNameStorage aligns with the PR's objective of managing multiple Nuxt instances in a single process.

packages/schema/src/types/nuxt.ts (1)

83-86: LGTM! Well-documented interface addition.

The __name property is:

  • Properly marked as internal with double underscore prefix
  • Well-documented with clear use cases
  • Correctly typed as string
test/bundle.test.ts (1)

103-103: LGTM! Acceptable bundle size increase.

The 1KB increase in server bundle size is minimal and justified by the addition of multi-instance support functionality.

packages/nuxt/src/core/nuxt.ts (1)

7-7: LGTM! Import changes look good.

The new imports support the multi-instance functionality with proper context management.

Also applies to: 25-25

/** Direct access to the Nuxt context - see https://github.com/unjs/unctx. */
export const nuxtCtx = getContext<Nuxt>('nuxt')
/** Direct access to the Nuxt context with asyncLocalStorage - see https://github.com/unjs/unctx. */
export const getNuxtCtx = () => getContext<Nuxt>(asyncNameStorage.getStore()!)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential null return value from asyncNameStorage.getStore()

Using the non-null assertion operator ! with asyncNameStorage.getStore() may lead to runtime errors if the store is undefined. Consider adding a null check to ensure robustness.

Suggested change:

-export const getNuxtCtx = () => getContext<Nuxt>(asyncNameStorage.getStore()!)
+export const getNuxtCtx = () => {
+  const store = asyncNameStorage.getStore()
+  if (!store) {
+    // Handle the undefined case, e.g., throw an error or provide a fallback
+    throw new Error('AsyncLocalStorage store is undefined')
+  }
+  return getContext<Nuxt>(store)
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const getNuxtCtx = () => getContext<Nuxt>(asyncNameStorage.getStore()!)
export const getNuxtCtx = () => {
const store = asyncNameStorage.getStore()
if (!store) {
// Handle the undefined case, e.g., throw an error or provide a fallback
throw new Error('AsyncLocalStorage store is undefined')
}
return getContext<Nuxt>(store)
}

packages/kit/src/utils.ts Show resolved Hide resolved
@@ -50,18 +51,19 @@ import { VirtualFSPlugin } from './plugins/virtual'

export function createNuxt (options: NuxtOptions): Nuxt {
const hooks = createHooks<NuxtHooks>()
Copy link
Member

Choose a reason for hiding this comment

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

we probably need to ensure that hooks are called in a way that passes the name of the Nuxt concerned.... maybe via a custom caller, or by overriding callHook?

Copy link
Member Author

Choose a reason for hiding this comment

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

hooks is assigned to the Nuxt instance.
If users wants to know which nuxt is concerned, they probably knows it when calling useNuxt or nuxt.hook <-- means they have stored it in a variable somewhere

What are you thinking of 👀 ?

Copy link
Member

Choose a reason for hiding this comment

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

I mean we want this to work:

nuxt.hook('modules:done', () => {
  addTemplate(someTemplate)
})

Copy link
Member

Choose a reason for hiding this comment

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

actually that may be a bad example as it's called within initNuxt but consider another hook that's called later on - we need nuxt context available then too. Users shouldn't have to update their code to explicitly run nuxt.run any time they need to run a kit utility.

Copy link
Member Author

Choose a reason for hiding this comment

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

How about

  const nuxt: Nuxt = {
    _version: version,
    options,
    hooks,
    callHook: hooks.callHook,
    addHooks: hooks.addHooks,
    hook: (name, fn, opts) => asyncNameStorage.run(name, () => hooks.hook(name, fn, opts)),
    ready: () => asyncNameStorage.run(name, () => initNuxt(nuxt)),
    close: () => hooks.callHook('close', nuxt),
    vfs: {},
    apps: {},
    __name: name,
  }

this would only work in hooks tho.

Copy link
Member Author

Choose a reason for hiding this comment

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

I think we'd still need to add a nuxt.run in the future

Copy link
Member

Choose a reason for hiding this comment

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

It's also possible to acess nuxt.hooks directly, and in fact we use addHooks to add user hooks, for example.

we can have nuxt.run, of course, but the value of most of kit utilities is that they shouldn't require it by having to pass nuxt around. at least reducing the surface area of possible places where users can call it would help a lot.

Copy link
Member Author

@huang-julien huang-julien Jan 11, 2025

Choose a reason for hiding this comment

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

It's also possible to acess nuxt.hooks directly, and in fact we use addHooks to add user hooks, for example.

Indeed so do we need to override it directly in hooks ? Or could we maybe override callHook from hooks

we can have nuxt.run, of course, but the value of most of kit utilities is that they shouldn't require it by having to pass nuxt around. at least reducing the surface area of possible places where users can call it would help a lot.

It's only for cases when users wants to run it outside of loadNuxt or buildNuxt, I don't really see a lot of cases 🤔

@huang-julien huang-julien marked this pull request as draft January 11, 2025 21:02
@huang-julien huang-julien marked this pull request as ready for review January 12, 2025 18:57
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
packages/kit/src/context.ts (1)

6-7: ⚠️ Potential issue

Handle potential null return value from asyncNameStorage.getStore()

Using the non-null assertion operator ! with asyncNameStorage.getStore() may lead to runtime errors if the store is undefined. Consider adding a null check to ensure robustness.

-export const getNuxtCtx = () => getContext<Nuxt>(asyncNameStorage.getStore()!)
+export const getNuxtCtx = () => {
+  const store = asyncNameStorage.getStore()
+  if (!store) {
+    // Handle the undefined case, e.g., throw an error or provide a fallback
+    throw new Error('AsyncLocalStorage store is undefined')
+  }
+  return getContext<Nuxt>(store)
+}
🧹 Nitpick comments (4)
packages/nuxt/test/load-nuxt.test.ts (2)

52-62: Consider enhancing test coverage

While the test correctly verifies concurrent loading and absence of warnings, consider adding assertions to:

  1. Verify each instance has a unique __name
  2. Confirm each instance is properly initialised
  3. Test the context isolation between instances
 it('load multiple nuxt', async () => {
-  await Promise.all([
+  const [nuxt1, nuxt2] = await Promise.all([
     loadNuxt({
       cwd: repoRoot,
     }),
     loadNuxt({
       cwd: repoRoot,
     }),
   ])
   expect(loggerWarn).not.toHaveBeenCalled()
+  expect(nuxt1.__name).not.toBe(nuxt2.__name)
+  expect(nuxt1).toBeDefined()
+  expect(nuxt2).toBeDefined()
+
+  // Test context isolation
+  await nuxt1.run(() => {
+    expect(asyncNameStorage.getStore()).toBe(nuxt1.__name)
+  })
+  await nuxt2.run(() => {
+    expect(asyncNameStorage.getStore()).toBe(nuxt2.__name)
+  })
 })

64-81: Improve type safety in test

Instead of using @ts-expect-error for a "random" hook, consider:

  1. Using a properly typed test hook
  2. Creating a type-safe test hook name constant
+const TEST_HOOK = 'test:context' as const
+
 it('expect hooks to get the correct context outside of initNuxt', async () => {
   const nuxt = await loadNuxt({
     cwd: repoRoot,
   })

-  // @ts-expect-error - random hook
-  await nuxt.hook('test', () => {
+  await nuxt.hook(TEST_HOOK, () => {
     const nuxt = useNuxt()
     expect(asyncNameStorage.getStore()).toBe(nuxt.__name)
   })

   expect(asyncNameStorage.getStore()).toBeUndefined()

-  // @ts-expect-error - random hook
-  await nuxt.callHook('test')
+  await nuxt.callHook(TEST_HOOK)

   expect(loggerWarn).not.toHaveBeenCalled()
 })
packages/schema/src/types/nuxt.ts (1)

90-93: Enhance method documentation

Consider adding more detailed documentation for the run method to explain:

  1. Its purpose in managing async context
  2. Usage examples
  3. Return value expectations
 /**
  * @internal
+ * Executes a function within this Nuxt instance's context.
+ * 
+ * @example
+ * ```ts
+ * await nuxt.run(async () => {
+ *   const ctx = useNuxt() // Gets this instance's context
+ *   await ctx.callHook('my-hook')
+ * })
+ * ```
+ * 
+ * @param fn The function to execute within this context
+ * @returns The return value of the executed function
  */
 run: <T extends (...args: any[]) => any>(fn: T) => ReturnType<T>
packages/nuxt/src/core/nuxt.ts (1)

83-89: Consider adding error handling

The context setup could benefit from error handling to ensure proper cleanup in case of initialization failures.

 nuxt.run(() => {
+  try {
     // Set nuxt instance for useNuxt
     getNuxtCtx().set(nuxt)
     nuxt.hook('close', () => {
       getNuxtCtx().unset()
     })
+  } catch (error) {
+    logger.error('Failed to initialize Nuxt context:', error)
+    throw error
+  }
 })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 982af4e and ce246a4.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (6)
  • packages/kit/src/context.ts (3 hunks)
  • packages/kit/src/index.ts (2 hunks)
  • packages/kit/src/utils.ts (1 hunks)
  • packages/nuxt/src/core/nuxt.ts (4 hunks)
  • packages/nuxt/test/load-nuxt.test.ts (4 hunks)
  • packages/schema/src/types/nuxt.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/kit/src/utils.ts
  • packages/kit/src/index.ts
🔇 Additional comments (9)
packages/kit/src/context.ts (1)

3-3: LGTM! The import of asyncNameStorage is correctly added for the new context management system.

packages/nuxt/test/load-nuxt.test.ts (2)

7-7: LGTM! The required imports are correctly added for the new test cases.


28-30: LGTM! The beforeEach hook correctly clears the loggerWarn spy, ensuring a clean state for each test.

packages/schema/src/types/nuxt.ts (1)

83-86: LGTM! The __name property is well-documented and correctly typed.

packages/nuxt/src/core/nuxt.ts (5)

3-3: LGTM! Using the built-in randomUUID from node:crypto is a good choice for generating unique instance identifiers.


56-59: LGTM! Hook calls are correctly wrapped to maintain context, covering all hook methods (callHook, callHookParallel, callHookWith).


68-74: LGTM! The Nuxt instance is correctly configured with the new __name property, run method, and context-aware ready method.


76-82: LGTM! The global context fallback is correctly implemented with proper cleanup via the close hook.


824-837: LGTM! The dependency version checks and hooks registration are correctly wrapped in the instance context.

Comment on lines +49 to +54
const nuxt = getNuxtCtx().tryUse()
if (!nuxt) {
logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.')
return nuxtCtx.tryUse()
}
return nuxt
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update deprecation warning message

The warning message has the same v4/v5 issue as in the useNuxt function.

-    logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.')
+    logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v5.')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const nuxt = getNuxtCtx().tryUse()
if (!nuxt) {
logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.')
return nuxtCtx.tryUse()
}
return nuxt
const nuxt = getNuxtCtx().tryUse()
if (!nuxt) {
logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v5.')
return nuxtCtx.tryUse()
}
return nuxt

Comment on lines +23 to 32
const instance = getNuxtCtx().tryUse()
if (!instance) {
const fallbackInstance = nuxtCtx.tryUse()
if (fallbackInstance) {
logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.')
return fallbackInstance
}

throw new Error('Nuxt instance is unavailable!')
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update deprecation warning message

The warning message incorrectly states that the fallback behaviour will be removed in v4, but according to the past review comments, this is planned for v5.

-      logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.')
+      logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v5.')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const instance = getNuxtCtx().tryUse()
if (!instance) {
const fallbackInstance = nuxtCtx.tryUse()
if (fallbackInstance) {
logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.')
return fallbackInstance
}
throw new Error('Nuxt instance is unavailable!')
}
const instance = getNuxtCtx().tryUse()
if (!instance) {
const fallbackInstance = nuxtCtx.tryUse()
if (fallbackInstance) {
logger.warn('Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v5.')
return fallbackInstance
}
throw new Error('Nuxt instance is unavailable!')
}

@danielroe danielroe modified the milestones: 4.0, 3.16 Jan 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants