UNPKG

1.97 kBJavaScriptView Raw
1'use strict'
2
3const semver = require('semver')
4const console = require('console')
5const extractPluginName = require('./stackParser')
6const { join, dirname } = require('path')
7
8function plugin (fn, options = {}) {
9 if (typeof fn.default !== 'undefined') { // Support for 'export default' behaviour in transpiled ECMAScript module
10 fn = fn.default
11 }
12
13 if (typeof fn !== 'function') {
14 throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof fn}'`)
15 }
16
17 fn[Symbol.for('skip-override')] = true
18
19 const pluginName = (options && options.name) || checkName(fn)
20
21 if (typeof options === 'string') {
22 checkVersion(options, pluginName)
23 options = {}
24 }
25
26 if (typeof options !== 'object' || Array.isArray(options) || options === null) {
27 throw new TypeError('The options object should be an object')
28 }
29
30 if (!options.name) {
31 options.name = pluginName
32 }
33
34 fn[Symbol.for('fastify.display-name')] = options.name
35
36 if (options.fastify) {
37 checkVersion(options.fastify, pluginName)
38 }
39
40 fn[Symbol.for('plugin-meta')] = options
41
42 return fn
43}
44
45function checkName (fn) {
46 if (fn.name.length > 0) return fn.name
47
48 try {
49 throw new Error('anonymous function')
50 } catch (e) {
51 return extractPluginName(e.stack)
52 }
53}
54
55function checkVersion (version, pluginName) {
56 if (typeof version !== 'string') {
57 throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof version}'`)
58 }
59
60 var fastifyVersion
61 try {
62 const pkgPath = join(dirname(require.resolve('fastify', { paths: [require.main.filename] })), 'package.json')
63 fastifyVersion = semver.coerce(require(pkgPath).version)
64 } catch (_) {
65 console.info('fastify not found, proceeding anyway')
66 }
67
68 if (fastifyVersion && !semver.satisfies(fastifyVersion, version)) {
69 throw new Error(`fastify-plugin: ${pluginName} - expected '${version}' fastify version, '${fastifyVersion}' is installed`)
70 }
71}
72
73module.exports = plugin