{"_id":"avvio@9.3.1","bugs":{"url":"https://github.com/fastify/avvio/issues"},"dist":{"shasum":"9f48a9fd07afa823549e12a334b81dad2575996f","tarball":"http://registry-npm.ywwl.com/avvio/download/avvio-9.3.1.tgz","fileCount":77,"integrity":"sha512-QyTKW61/qlba+cUQBm/sT9X8lri4UdomqSDwCnrnj1IvLVDRRiXRkz4CgBRWB+/cmfC7SK5WQc8T1vSdGvaUcQ==","signatures":[{"sig":"MEYCIQCNdDsTZuwfGlba89QkihTH8xzzlqDhtdfnmYR1L+01BQIhAMp/H8lnyRMLqXQR7Wu06jGG3XVC1Dllzz1kROMhJ/Ft","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDb/ZaGWrSycSSWJf3mOl5ZscFCOXLP+796XmO7u7lyXgIhANyZk2+O3E7DU+IJQT33bV013FcD2R15lgm23tLpNgqY"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/avvio@9.3.1","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":232204,"size":41130,"noattachment":false,"key":"/avvio/-/avvio-9.3.1.tgz"},"main":"index.js","name":"avvio","type":"commonjs","types":"index.d.ts","author":{"name":"Matteo Collina","email":"hello@matteocollina.com"},"funding":[{"url":"https://github.com/sponsors/fastify","type":"github"},{"url":"https://opencollective.com/fastify","type":"opencollective"}],"gitHead":"dc35b4af2bd1d5d258d4f20e92d6087064390c50","license":"MIT","scripts":{"lint":"eslint","test":"npm run test:unit && npm run test:typescript","lint:fix":"eslint --fix","test:unit":"borp --coverage --check-coverage --reporter=@jsumners/line-reporter","test:coverage":"c8 borp --reporter=@jsumners/line-reporter","test:typescript":"tsc --project ./test/types/tsconfig.json"},"version":"9.3.1","_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"3cc4002b-60e5-4df9-acb2-5d8a80925302"}},"homepage":"https://github.com/fastify/avvio#readme","keywords":["async","boot","delayed","open"],"repository":{"url":"git+https://github.com/fastify/avvio.git","type":"git"},"_npmVersion":"11.19.0","description":"Asynchronous bootstrapping of Node applications","directories":{},"maintainers":[{"name":"jsumners","email":"james.sumners@gmail.com"},{"name":"delvedor","email":"tommydelved@gmail.com"},{"name":"matteo.collina","email":"hello@matteocollina.com"},{"name":"eomm","email":"behemoth89@gmail.com"},{"name":"climba03003","email":"kaka@kakawebsitedemo.com"}],"_nodeVersion":"24.21.0","contributors":[{"url":"https://delvedor.dev","name":"Tomas Della Vedova"},{"name":"Manuel Spigolon","email":"behemoth89@gmail.com"},{"name":"Aras Abbasi","email":"aras.abbasi@gmail.com"},{"url":"https://github.com/fdawgs","name":"Frazer Smith","email":"frazer.dev@icloud.com"}],"dependencies":{"fastq":"^1.17.1","@fastify/error":"^4.0.0"},"_hasShrinkwrap":false,"devDependencies":{"c8":"^12.0.0","borp":"^1.0.0","eslint":"^9.17.0","typescript":"~6.0.2","@types/node":"^26.0.0","neostandard":"^0.13.0","@jsumners/line-reporter":"^1.0.1"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/avvio_9.3.1_1791626571767_0.7107763540088066"},"readme":"# avvio\n\n[![CI](https://github.com/fastify/avvio/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/avvio/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/avvio.svg?style=flat)](https://www.npmjs.com/package/avvio)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nAsynchronous bootstrapping is hard, different things can go wrong, *error handling* and *load order* just to name a few. The module aims to make it simple.\n\n`avvio` is fully *reentrant* and *graph-based*. You can load\ncomponents/plugins *within* plugins, and be still sure that things will\nhappen in the right order. At the end of the loading, your application will start.\n\n- [Install](#install)\n- [Example](#example)\n- [How Avvio works](#how-avvio-works)\n  - [The plugin tree](#the-plugin-tree)\n  - [Load order](#load-order)\n  - [The boot lifecycle](#the-boot-lifecycle)\n  - [Using `use()`, `after()`, and `ready()`](#using-use-after-and-ready)\n  - [Error handling](#error-handling)\n  - [Shutdown](#shutdown)\n- [API](#api)\n- [Errors](#errors)\n- [Acknowledgments](#acknowledgments)\n- [License](#license)\n\n## Install\n\nTo install `avvio`, simply use npm:\n\n```sh\nnpm i avvio\n```\n\nTypeScript type definitions are bundled with the package (`index.d.ts`), so no extra `@types` package is needed.\n\nTo enable internal debug logging, run your application with the `NODE_DEBUG=avvio` environment variable set:\n\n```sh\nNODE_DEBUG=avvio node app.js\n```\n\n## Example\n\nThe example below demonstrates how to use `avvio` to load functions and plugins in order.\n\n```js\n'use strict'\n\nconst app = require('avvio')()\n\napp\n  .use(first, { hello: 'world' })\n  .after((err, cb) => {\n    if (err) {\n      throw err\n    }\n\n    console.log('after first and second')\n    cb()\n  })\n\napp.use(third)\n\napp.ready(function (err) {\n  \n  if (err) {\n    throw err\n  }\n\n  console.log('application booted!')\n})\n\nfunction first (instance, opts, cb) {\n  console.log('first loaded', opts)\n  instance.use(second)\n  cb()\n}\n\nfunction second (instance, opts, cb) {\n  console.log('second loaded')\n  process.nextTick(cb)\n}\n\n// async/await or Promise support\nasync function third (instance, opts) {\n  console.log('third loaded')\n}\n```\n\nThe important part of this example is that `first` registers `second` while it is loading.\n\nThis creates the following plugin tree:\n\n```text\nroot\n├── first\n│   └── second\n└── third\n```\n\nThe plugins are loaded in this order:\n\n```text\nfirst\nsecond\nthird\n```\n\nOnly after the required plugins have completed can the application become ready.\n\n## How Avvio works\n\nAvvio builds a tree of plugins and loads that tree in a predictable order.\n\nThe main concepts are:\n\n- plugins can register other plugins;\n- nested plugins become dependencies of their parent;\n- plugins are loaded according to their position in the tree;\n- `after()` waits for plugins registered before it;\n- `ready()` waits for the complete boot process;\n- errors stop the boot process until they are handled or propagated to `ready()`;\n- `onClose()` and `close()` provide the shutdown lifecycle.\n\n### The plugin tree\n\nA call to `use()` adds a plugin to the current context.\n\nA plugin can register additional plugins while it is loading. Those plugins become children of the current plugin.\n\nFor example:\n\n```js\napp.use(first)\n\napp.use(third)\n\nfunction first (instance, opts, done) {\n  instance.use(second)\n  done()\n}\n```\n\ncreates this tree:\n\n```text\nroot\n├── first\n│   └── second\n└── third\n```\n\nThe nested `second` plugin belongs to `first`, because it was registered while `first` was loading.\n\nThis is what makes Avvio *reentrant*: a plugin can use the same application instance to register more plugins without losing the correct execution order.\n\n### Load order\n\nAvvio loads plugins according to their position in the plugin tree.\n\nGiven:\n\n```js\napp.use(first)\n\napp.use(third)\n\nfunction first (instance, opts, done) {\n  instance.use(second)\n  done()\n}\n\nfunction second (instance, opts, done) {\n  done()\n}\n\nfunction third (instance, opts, done) {\n  done()\n}\n```\n\nthe execution order is:\n\n```text\nfirst\nsecond\nthird\n```\n\n`second` must finish before Avvio can continue with `third`, because `second` is a dependency of `first`.\n\nThis allows plugins to register the components they depend on without requiring the application to manually calculate the complete load order.\n\n### The boot lifecycle\n\nThe boot process can be thought of as a sequence of phases:\n\n```text\nuse()\n  │\n  │ register plugins\n  ▼\nplugin loading\n  │\n  │ nested plugins are loaded\n  ▼\nafter()\n  │\n  │ wait for plugins registered so far\n  ▼\nready()\n  │\n  │ wait for the complete boot process\n  ▼\nstart\n```\n\nA plugin can register more plugins while it is loading:\n\n```js\napp.use(database)\n\nfunction database (instance, opts, done) {\n  instance.use(connectionPool)\n  done()\n}\n```\n\nAvvio waits for the nested plugin before considering the parent plugin complete.\n\n### Using `use()`, `after()`, and `ready()`\n\nThe three methods have different purposes.\n\n#### `use()`\n\nUse `use()` to register a plugin:\n\n```js\napp.use(database)\napp.use(routes)\n```\n\nA plugin can register additional plugins:\n\n```js\nfunction database (instance, opts, done) {\n  instance.use(connectionPool)\n  done()\n}\n```\n\n#### `after()`\n\nUse `after()` when you want to wait for all plugins registered before that point, including their dependencies:\n\n```js\napp.use(database)\n\napp.after(function (err) {\n  if (err) {\n    throw err\n  }\n\n  // database and its dependencies are ready here\n})\n```\n\nThe application has not emitted the `start` event yet.\n\nWith async/await, `after()` can be awaited:\n\n```js\napp.use(database)\n\nawait app.after()\n\n// database and its dependencies are ready here\n```\n\n#### `ready()`\n\nUse `ready()` when you want to wait for the complete boot process:\n\n```js\napp.use(database)\napp.use(routes)\n\nawait app.ready()\n\n// the application is ready\n```\n\n`ready()` runs after all plugins and `after()` callbacks have completed, but before the `start` event is emitted.\n\nA useful way to think about the difference is:\n\n```text\nuse()\n  Register work\n\nafter()\n  Wait for work registered so far\n\nready()\n  Wait for the complete boot process\n```\n\n### Error handling\n\nErrors are part of the boot lifecycle.\n\nIf a plugin fails:\n\n```js\napp.use(function (instance, opts, done) {\n  done(new Error('database failed'))\n})\n```\n\nAvvio stops loading until the error is handled.\n\nAn `after()` callback can handle or propagate the error:\n\n```js\napp.after(function (err) {\n  if (err) {\n    throw err\n  }\n\n  // continue\n})\n```\n\nIf the error is not handled by an `after()` callback, it is propagated to `ready()`:\n\n```js\napp.ready(function (err) {\n  if (err) {\n    console.error(err)\n    return\n  }\n\n  console.log('application booted')\n})\n```\n\nThe general flow is:\n\n```text\nplugin\n  │\n  ├── success ──────────────> continue\n  │\n  └── error\n       │\n       ▼\n     after()\n       │\n       ├── handled ─────────> continue\n       │\n       └── not handled\n              │\n              ▼\n            ready()\n```\n\nPlugins and callbacks can also fail by not completing within the configured `timeout`.\n\nSee [Errors](#errors) for the available error codes.\n\n### Shutdown\n\nBootstrapping is only one part of an application's lifecycle. Avvio also provides a shutdown mechanism.\n\nUse `onClose()` to register cleanup functions:\n\n```js\napp.onClose(async function () {\n  await database.close()\n})\n```\n\nCall `close()` to start the shutdown process:\n\n```js\nawait app.close()\n```\n\nThe registered `onClose()` callbacks are executed before the `close()` operation completes.\n\nThe lifecycle is therefore:\n\n```text\nboot\n │\n ▼\nready\n │\n ▼\napplication running\n │\n │ close()\n ▼\nonClose()\n │\n ▼\nclosed\n```\n\n## API\n\n- [avvio](#avvio)\n  - [Install](#install)\n  - [Example](#example)\n  - [How Avvio works](#how-avvio-works)\n    - [The plugin tree](#the-plugin-tree)\n    - [Load order](#load-order)\n    - [The boot lifecycle](#the-boot-lifecycle)\n    - [Using `use()`, `after()`, and `ready()`](#using-use-after-and-ready)\n      - [`use()`](#use)\n      - [`after()`](#after)\n      - [`ready()`](#ready)\n    - [Error handling](#error-handling)\n    - [Shutdown](#shutdown)\n  - [API](#api)\n    - [`avvio([instance], [options], [started])`](#avvioinstance-options-started)\n      - [Options](#options)\n        - [`expose`](#expose)\n        - [`autostart`](#autostart)\n        - [`timeout`](#timeout)\n      - [Events](#events)\n        - [`start`](#start)\n        - [`preReady`](#preready)\n        - [`close`](#close)\n      - [Properties](#properties)\n        - [`instance.started`](#instancestarted)\n        - [`instance.booted`](#instancebooted)\n      - [Constructor usage](#constructor-usage)\n    - [`app.use(func, [optsOrFunc]) => Thenable`](#appusefunc-optsorfunc--thenable)\n      - [Nested plugins](#nested-plugins)\n      - [Awaiting `use()`](#awaiting-use)\n      - [Dynamic options](#dynamic-options)\n      - [ESM](#esm)\n    - [Error handling](#error-handling-1)\n    - [`app.after(func(error, [context], [done]))`](#appafterfuncerror-context-done)\n      - [Callback signatures](#callback-signatures)\n    - [`await app.after() | app.after() => Promise`](#await-appafter--appafter--promise)\n    - [`app.ready([func(error, [context], [done])])`](#appreadyfuncerror-context-done)\n      - [Callback signatures](#callback-signatures-1)\n    - [`app.start()`](#appstart)\n    - [`app.override(server, plugin, options)`](#appoverrideserver-plugin-options)\n    - [`app.onClose(func([context], [done]))`](#apponclosefunccontext-done)\n    - [`app.close(func(error, [context], [done]))`](#appclosefuncerror-context-done)\n    - [`app[Symbol.asyncDispose]()`](#appsymbolasyncdispose)\n    - [`avvio.toJSON()`](#avviotojson)\n    - [`avvio.prettyPrint()`](#avvioprettyprint)\n  - [Errors](#errors)\n    - [Debugging timeouts](#debugging-timeouts)\n  - [Acknowledgments](#acknowledgments)\n  - [License](#license)\n\n---\n\n### `avvio([instance], [options], [started])`\n\nStarts the Avvio boot sequence.\n\nAs the name suggests, `instance` is the object representing your application. Avvio adds the functions `use`, `after`, `ready`, `onClose`, and `close` to the instance.\n\n```js\nconst server = {}\n\nrequire('avvio')(server)\n\nserver\n  .use(function first (s, opts, cb) {\n    s.use(function second (s, opts, cb) {\n      cb()\n    })\n\n    cb()\n  })\n  .after(function (err, cb) {\n    if (err) {\n      throw err\n    }\n\n    // first and second are finished\n    cb()\n  })\n```\n\n#### Options\n\n##### `expose`\n\nA key/value property to change how `use`, `after`, `ready`, `onClose`, and `close` are exposed on the instance.\n\nThis is useful when one of the default names is already taken.\n\n```js\nconst server = {}\n\nrequire('avvio')(server, {\n  expose: {\n    use: 'register',\n    ready: 'onReady'\n  }\n})\n\nserver.register(function (s, opts, done) {\n  done()\n})\n\nserver.onReady(function (err) {\n  if (err) {\n    throw err\n  }\n})\n```\n\n##### `autostart`\n\nWhen `autostart` is `false`, Avvio does not start loading plugins automatically. The boot sequence starts when `.start()` or `.ready()` is called.\n\n```js\nconst app = require('avvio')({\n  autostart: false\n})\n\napp.use(plugin)\n\n// boot starts here\napp.start()\n```\n\n##### `timeout`\n\nThe number of milliseconds to wait for a plugin or lifecycle callback to complete.\n\nIf the timeout is reached, Avvio emits:\n\n- `AVV_ERR_PLUGIN_EXEC_TIMEOUT` for plugins;\n- `AVV_ERR_READY_TIMEOUT` for `ready()` and `after()` callbacks.\n\nThe default is `0`, which disables the timeout.\n\nSee [Errors](#errors).\n\n#### Events\n\n##### `start`\n\nEmitted when the application starts.\n\n##### `preReady`\n\nEmitted before the ready queue is run.\n\n##### `close`\n\nEmitted when the application has completed the shutdown procedure started with [`close()`](#appclosefuncerror-context-done).\n\n#### Properties\n\n##### `instance.started`\n\n`true` once [`start()`](#appstart) has been called, or once [`ready()`](#appreadyfuncerror-context-done) starts the boot sequence when `autostart` is enabled.\n\nIt does not mean that loading has completed.\n\n##### `instance.booted`\n\n`true` once the root plugin and all of its dependencies have finished loading successfully.\n\n#### Constructor usage\n\nThe `avvio` function can also be used as a constructor to inherit from.\n\n```js\nfunction Server () {}\n\nconst app = require('avvio')(new Server())\n\napp.use(function (s, opts, done) {\n  done()\n})\n\napp.on('start', () => {\n  // your application can start\n})\n```\n\n---\n\n### `app.use(func, [optsOrFunc]) => Thenable`\n\nLoads one or more functions asynchronously.\n\nThe function can use the following callback signature:\n\n```js\nfunction plugin (instance, options, done) {\n  done()\n}\n```\n\n`done` should be called only once, when the plugin is ready.\n\nAdditional calls to `done` are ignored.\n\nIf the plugin is ready immediately after the function is evaluated, `done` can be omitted:\n\n```js\nfunction plugin (instance, options) {\n  // synchronous plugin\n}\n```\n\nIf the function returns a Promise, an async function can be used instead:\n\n```js\nasync function plugin (instance, options) {\n  await initialize()\n}\n```\n\n#### Nested plugins\n\nA plugin can register additional plugins:\n\n```js\nfunction first (instance, opts, done) {\n  instance.use(second)\n  done()\n}\n\nfunction second (instance, opts, done) {\n  done()\n}\n\napp.use(first)\n```\n\nAvvio waits for `second` before considering `first` complete.\n\n#### Awaiting `use()`\n\n`use()` returns a thenable wrapped instance, so it can be awaited:\n\n```js\nasync function main () {\n  await app.use(async function (server, opts) {\n    await sleep(10)\n    console.log('this first')\n  })\n\n  console.log('then this')\n\n  await app.ready()\n  console.log('ready')\n}\n\nmain().catch((err) => console.error(err))\n```\n\n#### Dynamic options\n\nThe options argument can also be a function.\n\nThe function receives the parent instance and returns the options for the plugin:\n\n```js\nfunction first (server, opts, done) {\n  server.foo = 'bar'\n  done()\n}\n\nfunction second (server, opts, done) {\n  console.log(opts.foo === 'bar')\n  done()\n}\n\nconst options = parent => {\n  return {\n    foo: parent.foo\n  }\n}\n\napp.use(first)\napp.use(second, options)\n```\n\nThis is useful when a value created by a plugin needs to be made available as options to another plugin.\n\n#### ESM\n\nES modules can be loaded using a dynamic import:\n\n```js\nimport boot from 'avvio'\n\nconst app = boot()\n\napp.use(import('./fixtures/esm.mjs'))\n```\n\n---\n\n### Error handling\n\nTo handle errors in plugins, use [`ready()`](#appreadyfuncerror-context-done):\n\n```js\napp.use(function (instance, opts, done) {\n  done(new Error('error'))\n})\n\napp.ready(function (err) {\n  if (err) {\n    throw err\n  }\n})\n```\n\nWhen an error happens, plugin loading stops until the error is handled by an [`after()`](#appafterfuncerror-context-done) callback.\n\nIf it is not handled, the error is propagated to [`ready()`](#appreadyfuncerror-context-done).\n\n---\n\n### `app.after(func(error, [context], [done]))`\n\nCalls a function after all previously defined plugins have loaded, including all their dependencies.\n\nThe `start` event has not been emitted yet.\n\n`after()` can be used as a callback or awaited as a Promise.\n\n#### Callback signatures\n\nThe callback signature changes based on the number of parameters it declares:\n\n1. If no parameter is given, an error is passed to the next error handler.\n2. If one parameter is given, it receives the `error`.\n3. If two parameters are given, the first receives the `error` and the second is the `done` callback.\n4. If three parameters are given, the first receives the `error`, the second receives the top-level `context`, and the third is the `done` callback.\n\nIn the zero- and one-parameter variants, the callback can return a Promise.\n\n```js\nconst server = {}\nconst app = require('avvio')(server)\n\n// one parameter\napp.after(function (err) {\n  if (err) {\n    throw err\n  }\n})\n\n// two parameters\napp.after(function (err, done) {\n  if (err) {\n    throw err\n  }\n\n  done()\n})\n\n// three parameters\napp.after(function (err, context, done) {\n  if (err) {\n    throw err\n  }\n\n  assert.equal(context, server)\n  done()\n})\n\n// async\napp.after(async function (err) {\n  if (err) {\n    throw err\n  }\n\n  await sleep(10)\n})\n```\n\n`done` must be called only once.\n\nWhen called with a function, `after()` returns the instance on which it was called, allowing chaining.\n\n---\n\n### `await app.after() | app.after() => Promise`\n\nCalling `after()` without a function loads all plugins previously registered with `use()` and returns a Promise.\n\nThe Promise resolves when all plugins registered so far have loaded.\n\n```js\nasync function main () {\n  app.use(async function (server, opts) {\n    await sleep(10)\n    console.log('this first')\n  })\n\n  app.use(async function (server, opts) {\n    await sleep(10)\n    console.log('this second')\n  })\n\n  console.log('before after')\n\n  await app.after()\n\n  console.log('after after')\n\n  app.use(async function (server, opts) {\n    await sleep(10)\n    console.log('this third')\n  })\n\n  await app.ready()\n\n  console.log('ready')\n}\n\nmain().catch((err) => console.error(err))\n```\n\nUnlike callback-based `after()` and `use()`, `await after` is not chainable.\n\n---\n\n### `app.ready([func(error, [context], [done])])`\n\nCalls a function after all plugins and `after()` callbacks have completed, but before the `start` event is emitted.\n\n`ready()` callbacks are executed one at a time.\n\n#### Callback signatures\n\nThe callback signature changes based on the number of parameters it declares:\n\n1. If no parameter is given, an error is passed to the next error handler.\n2. If one parameter is given, it receives the `error`.\n3. If two parameters are given, the first receives the `error` and the second is the `done` callback.\n4. If three parameters are given, the first receives the `error`, the second receives the top-level `context`, and the third is the `done` callback.\n\nWhen both `server` and `override` are specified, the context is the value returned by `override`.\n\n```js\nconst server = {}\nconst app = require('avvio')(server)\n\n// one parameter\napp.ready(function (err) {\n  if (err) {\n    throw err\n  }\n})\n\n// two parameters\napp.ready(function (err, done) {\n  if (err) {\n    throw err\n  }\n\n  done()\n})\n\n// three parameters\napp.ready(function (err, context, done) {\n  if (err) {\n    throw err\n  }\n\n  assert.equal(context, server)\n  done()\n})\n```\n\nIf no callback is provided, `ready()` returns a Promise:\n\n```js\napp.ready()\n  .then(() => console.log('Ready'))\n  .catch(err => {\n    console.error(err)\n    process.exit(1)\n  })\n```\n\nIt can also be awaited:\n\n```js\nasync function main () {\n  try {\n    await app.ready()\n    console.log('Ready')\n  } catch (err) {\n    console.error(err)\n    process.exit(1)\n  }\n}\n\nmain()\n```\n\n`done` must be called only once.\n\nThe callback form of this function has no return value.\n\nIf `autostart: false` is passed as an option, calling `ready()` also starts the boot sequence.\n\n---\n\n### `app.start()`\n\nStarts the boot sequence if it has not started yet.\n\nReturns the `app` instance.\n\n```js\nconst app = require('avvio')({\n  autostart: false\n})\n\napp.use(plugin)\n\napp.start()\n```\n\n---\n\n### `app.override(server, plugin, options)`\n\nAllows overriding the instance passed to each loading plugin.\n\nIt can be used to create an inheritance chain between server instances.\n\nThe first parameter is the server instance, the second is the plugin function, and the third is the options object passed to `use()`.\n\nFor example:\n\n```js\nconst assert = require('node:assert')\n\nconst server = {\n  count: 0\n}\n\nconst app = require('avvio')(server)\n\napp.override = function (s, fn, opts) {\n  const res = Object.create(s)\n  res.count = res.count + 1\n  return res\n}\n\napp.use(function first (s1, opts, cb) {\n  assert(s1 !== server)\n  assert(Object.prototype.isPrototypeOf.call(server, s1))\n  assert(s1.count === 1)\n\n  s1.use(second)\n  cb()\n\n  function second (s2, opts, cb) {\n    assert(s2 !== s1)\n    assert(Object.prototype.isPrototypeOf.call(s1, s2))\n    assert(s2.count === 2)\n    cb()\n  }\n})\n```\n\nThe resulting relationship is:\n\n```text\nserver\n  │\n  ▼\ninstance for first\n  │\n  ▼\ninstance for second\n```\n\nEach child instance inherits from its parent.\n\n---\n\n### `app.onClose(func([context], [done]))`\n\nRegisters a callback that is executed when the [`close()`](#appclosefuncerror-context-done) API is called.\n\nThe callback can use one of the following signatures:\n\n1. One parameter: receives the `context`.\n2. Zero or one parameter: may return a Promise.\n3. Two parameters: receives the `context` and `done` callback.\n\n```js\nconst server = {}\nconst app = require('avvio')(server)\n\n// one parameter\napp.onClose(function (context) {\n  // ...\n})\n\n// Promise\napp.onClose(function (context) {\n  return new Promise((resolve, reject) => {\n    // ...\n  })\n})\n\n// async\napp.onClose(async function (context) {\n  await cleanup()\n})\n\n// callback\napp.onClose(function (context, done) {\n  // ...\n  done()\n})\n```\n\nIf the callback returns a Promise, the next `onClose()` callback and the `close()` callback wait until the Promise resolves or rejects.\n\n`done` must be called only once.\n\nReturns the instance on which `onClose()` was called, allowing chaining.\n\n---\n\n### `app.close(func(error, [context], [done]))`\n\nStarts the shutdown procedure.\n\nThe callback is called once all registered `onClose()` callbacks have completed.\n\nThe callback can use one of the following signatures:\n\n1. One parameter: receives the `error`.\n2. Two parameters: receives the `error` and `done` callback.\n3. Three parameters: receives the `error`, `context`, and `done` callback.\n\n```js\nconst server = {}\nconst app = require('avvio')(server)\n\n// one parameter\napp.close(function (err) {\n  if (err) {\n    throw err\n  }\n})\n\n// two parameters\napp.close(function (err, done) {\n  if (err) {\n    throw err\n  }\n\n  done()\n})\n\n// three parameters\napp.close(function (err, context, done) {\n  if (err) {\n    throw err\n  }\n\n  assert.equal(context, server)\n  done()\n})\n```\n\nWhen no callback is provided, `close()` returns a Promise:\n\n```js\napp.close()\n  .then(() => console.log('Closed'))\n  .catch(err => {\n    console.error(err)\n    process.exit(1)\n  })\n```\n\n`done` must be called only once.\n\n---\n\n### `app[Symbol.asyncDispose]()`\n\nThis method is an alias for [`app.close()`](#appclosefuncerror-context-done) and supports ECMAScript Explicit Resource Management.\n\nIt allows the use of `await using` to automatically close the Avvio instance when it goes out of scope.\n\nThis is especially useful in unit tests and short-lived processes where resources need to be cleaned up automatically.\n\n```js\ntest('my test', async () => {\n  await using app = avvio()\n\n  app.use(function (server, opts, done) {\n    done()\n  })\n\n  await app.ready()\n\n  // app.close() is called automatically\n})\n```\n\nThis feature requires Node.js 20 or later.\n\n---\n\n### `avvio.toJSON()`\n\nReturns a JSON tree representing the state of the plugins and their loading times.\n\nCall it on `preReady` to get the complete tree.\n\n```js\nconst app = require('avvio')()\n\napp.on('preReady', () => {\n  console.log(app.toJSON())\n})\n```\n\nThe output is similar to:\n\n```json\n{\n  \"label\": \"root\",\n  \"start\": 1550245184665,\n  \"nodes\": [\n    {\n      \"parent\": \"root\",\n      \"start\": 1550245184665,\n      \"label\": \"first\",\n      \"nodes\": [\n        {\n          \"parent\": \"first\",\n          \"start\": 1550245184708,\n          \"label\": \"second\",\n          \"nodes\": [],\n          \"stop\": 1550245184709,\n          \"diff\": 1\n        }\n      ],\n      \"stop\": 1550245184709,\n      \"diff\": 44\n    }\n  ],\n  \"stop\": 1550245184709,\n  \"diff\": 44\n}\n```\n\n---\n\n### `avvio.prettyPrint()`\n\nReturns a printable representation of the tree returned by `toJSON()`.\n\n```js\nconst app = require('avvio')()\n\napp.on('preReady', () => {\n  console.log(app.prettyPrint())\n})\n```\n\nExample output:\n\n```text\navvio 56 ms\n├── first 52 ms\n├── second 1 ms\n└── third 2 ms\n```\n\n---\n\n## Errors\n\n`avvio` uses [`@fastify/error`](https://github.com/fastify/fastify-error) to generate its errors.\n\nEvery error exposes a stable `code` and `message`.\n\n| Code | Message | Notes |\n| --- | --- | --- |\n| `AVV_ERR_EXPOSE_ALREADY_DEFINED` | `'%s' is already defined, specify an expose option for '%s'` | Thrown when a property that Avvio needs to expose on the instance (`use`, `after`, `ready`, `onClose`, `close`) is already taken. Use the `expose` option to rename it. |\n| `AVV_ERR_ATTRIBUTE_ALREADY_DEFINED` | `'%s' is already defined` | Thrown when the instance already has a `then` property, which Avvio needs to make itself awaitable. |\n| `AVV_ERR_CALLBACK_NOT_FN` | `Callback for '%s' hook is not a function. Received: '%s'` | Thrown when a non-function value is passed where a callback (`ready`, `close`, `onClose`, etc.) is expected. |\n| `AVV_ERR_PLUGIN_NOT_VALID` | `Plugin must be a function or a promise. Received: '%s'` | Thrown when the value passed to `use()` is neither a function nor a thenable. |\n| `AVV_ERR_ROOT_PLG_BOOTED` | `Root plugin has already booted` | Thrown when calling `use()` after the instance has already booted. |\n| `AVV_ERR_PARENT_PLG_LOADED` | `Impossible to load '%s' plugin because the parent '%s' was already loaded` | Thrown when trying to register a plugin on a parent that has already finished loading. |\n| `AVV_ERR_READY_TIMEOUT` | `Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise` | Thrown when a `ready()` or `after()` callback does not complete before the configured `timeout` elapses. |\n| `AVV_ERR_PLUGIN_EXEC_TIMEOUT` | `Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise` | Thrown when a plugin passed to `use()` does not complete before the configured `timeout` elapses. |\n\nThe plugin or callback name used in `'%s'` is derived from the function name, an explicit `name` option, or, for [`fastify-plugin`](https://github.com/fastify/fastify-plugin)-wrapped plugins, the metadata attached to the plugin.\n\nThis is also the name shown by [`prettyPrint()`](#avvioprettyprint) and [`toJSON()`](#avviotojson).\n\n### Debugging timeouts\n\nWhen a timeout occurs, the error message includes the name of the plugin or callback that did not complete.\n\nIf a plugin uses the callback API, make sure `done()` is called:\n\n```js\napp.use(function plugin (instance, opts, done) {\n  initializeSomething()\n  done()\n})\n```\n\nIf a plugin uses async/await, make sure its Promise resolves:\n\n```js\napp.use(async function plugin (instance, opts) {\n  await initializeSomething()\n})\n```\n\n## Acknowledgments\n\nThis project was kindly sponsored by [nearForm](https://nearform.com/).\n\n## License\n\nCopyright Matteo Collina 2016-2020, Licensed under [MIT](LICENSE).\n","publish_time":1791626571863,"_cnpm_publish_time":1791626571863,"dist-tags":{"latest":"9.3.1","next":"9.0.0-pre.fv5.1","seven":"7.2.5"}}