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

No module augmentation #471

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@fastify/accept-negotiator": "^2.0.0",
"@fastify/send": "^3.1.0",
"content-disposition": "^0.5.4",
"fastify-plugin": "^5.0.0",
"fastify-plugin": "git+https://github.com/livingspec/fastify-plugin.git#support-decorators",
"fastq": "^1.17.1",
"glob": "^11.0.0"
},
Expand All @@ -42,7 +42,7 @@
"@types/node": "^22.0.0",
"concat-stream": "^2.0.0",
"eslint": "^9.9.0",
"fastify": "^5.0.0-alpha.4",
"fastify": "git+https://github.com/livingspec/fastify.git#type-improvements",
"neostandard": "^0.11.3",
"pino": "^9.1.0",
"proxyquire": "^2.1.3",
Expand Down
43 changes: 29 additions & 14 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,38 @@
// Leo <https://github.com/leomelzer>
/// <reference types="node" />

import { FastifyPluginAsync, FastifyReply, FastifyRequest, RouteOptions } from 'fastify'
import {
ApplyDecorators,
FastifyPluginAsync,
FastifyReply,
FastifyRequest,
RouteOptions,
AnyFastifyInstance,
UnEncapsulatedPlugin,
FastifyPluginOptions
} from 'fastify'
import { Stats } from 'fs'

declare module 'fastify' {
interface FastifyReply {
sendFile(filename: string, rootPath?: string): FastifyReply;
sendFile(filename: string, options?: fastifyStatic.SendOptions): FastifyReply;
sendFile(filename: string, rootPath?: string, options?: fastifyStatic.SendOptions): FastifyReply;
download(filepath: string, options?: fastifyStatic.SendOptions): FastifyReply;
download(filepath: string, filename?: string): FastifyReply;
download(filepath: string, filename?: string, options?: fastifyStatic.SendOptions): FastifyReply;
declare namespace fastifyStatic {
export type FastifyStaticPluginDecorators = {
reply: {
sendFile(filename: string, rootPath?: string): FastifyReply;
sendFile(filename: string, options?: fastifyStatic.SendOptions): FastifyReply;
sendFile(filename: string, rootPath?: string, options?: fastifyStatic.SendOptions): FastifyReply;
download(filepath: string, options?: fastifyStatic.SendOptions): FastifyReply;
download(filepath: string, filename?: string): FastifyReply;
download(filepath: string, filename?: string, options?: fastifyStatic.SendOptions): FastifyReply;
}
}
}

type FastifyStaticPlugin = FastifyPluginAsync<NonNullable<fastifyStatic.FastifyStaticOptions>>
export type FastifyStaticPlugin<TInstance extends AnyFastifyInstance = AnyFastifyInstance> = UnEncapsulatedPlugin<
FastifyPluginAsync<
NonNullable<fastifyStatic.FastifyStaticOptions>,
TInstance,
ApplyDecorators<TInstance, FastifyStaticPluginDecorators>
>
>

declare namespace fastifyStatic {
export interface SetHeadersResponse {
getHeader: FastifyReply['getHeader'];
setHeader: FastifyReply['header'];
Expand Down Expand Up @@ -70,7 +85,7 @@ declare namespace fastifyStatic {
}

// Passed on to `send`
export interface SendOptions {
export interface SendOptions extends FastifyPluginOptions {
acceptRanges?: boolean;
cacheControl?: boolean;
dotfiles?: 'allow' | 'deny' | 'ignore';
Expand Down Expand Up @@ -119,6 +134,6 @@ declare namespace fastifyStatic {
export { fastifyStatic as default }
}

declare function fastifyStatic (...params: Parameters<FastifyStaticPlugin>): ReturnType<FastifyStaticPlugin>
declare function fastifyStatic (...params: Parameters<fastifyStatic.FastifyStaticPlugin>): ReturnType<fastifyStatic.FastifyStaticPlugin>

export = fastifyStatic
93 changes: 60 additions & 33 deletions types/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
import fastify, { FastifyInstance, FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify'
import { Server } from 'http'
import fastify, { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'
import { Stats } from 'fs'
import { expectAssignable, expectError, expectType } from 'tsd'
import * as fastifyStaticStar from '..'
import fastifyStatic, {
FastifyStaticPlugin,
FastifyStaticOptions,
fastifyStatic as fastifyStaticNamed
fastifyStatic as fastifyStaticNamed,
FastifyStaticPluginDecorators
} from '..'
// TODO: remove after we land in fastify-plugin
import { createPlugin } from 'fastify-plugin'

import fastifyStaticCjsImport = require('..')
const fastifyStaticCjs = require('..')

const app: FastifyInstance = fastify()

app.register(fastifyStatic)
app.register(fastifyStaticNamed)
app.register(fastifyStaticCjs)
app.register(fastifyStaticCjsImport.default)
app.register(fastifyStaticCjsImport.fastifyStatic)
app.register(fastifyStaticStar.default)
app.register(fastifyStaticStar.fastifyStatic)

expectType<FastifyPluginAsync<FastifyStaticOptions, Server>>(fastifyStatic)
expectType<FastifyPluginAsync<FastifyStaticOptions, Server>>(fastifyStaticNamed)
expectType<FastifyPluginAsync<FastifyStaticOptions, Server>>(fastifyStaticCjsImport.default)
expectType<FastifyPluginAsync<FastifyStaticOptions, Server>>(fastifyStaticCjsImport.fastifyStatic)
expectType<FastifyPluginAsync<FastifyStaticOptions, Server>>(fastifyStaticStar.default)
expectType<FastifyPluginAsync<FastifyStaticOptions, Server>>(
fastifyStaticStar.fastifyStatic
)
app.register(fastifyStatic, { root: '/' })

Choose a reason for hiding this comment

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

If I properly understand the change, we now require an object to be always passed when we register a fastify plugin (so it's no longer optional). This is a breaking change, we should really careful if we want to ship it as it is, since it will break existing TS codebases

Copy link
Author

@nemanja-tosic nemanja-tosic Nov 29, 2024

Choose a reason for hiding this comment

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

An object is not necessary, fastify static plugin has a mandatory root param. Removing the object leads to

  Overload 1 of 3, (plugin: FastifyPluginCallback<FastifyPluginOptions, BaseFastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault, FastifyDecorators>>, opts?: FastifyRegisterOptions<...> | undefined): BaseFastifyInstance<...> & ... 1 more ... & { ...; }, gave the following error.
    Argument of type FastifyStaticPlugin<BaseFastifyInstance<any, any, any, any, any, FastifyDecorators>> is not assignable to parameter of type FastifyPluginCallback<FastifyPluginOptions, BaseFastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault, FastifyDecorators>>.
      Types of parameters opts and opts are incompatible.
        Property root is missing in type FastifyPluginOptions but required in type FastifyStaticOptions.
...

Making root optional fixes the error.

If anything, the possibility of not providing root was a bug as far as i can tell.

app.register(fastifyStaticNamed, { root: '/' })
app.register(fastifyStaticCjs, { root: '/' })
app.register(fastifyStaticCjsImport.default, { root: '/' })
app.register(fastifyStaticCjsImport.fastifyStatic, { root: '/' })
app.register(fastifyStaticStar.default, { root: '/' })
app.register(fastifyStaticStar.fastifyStatic, { root: '/' })

expectType<FastifyStaticPlugin>(fastifyStatic)
expectType<FastifyStaticPlugin>(fastifyStaticNamed)
expectType<FastifyStaticPlugin>(fastifyStaticCjsImport.default)
expectType<FastifyStaticPlugin>(fastifyStaticCjsImport.fastifyStatic)
expectType<FastifyStaticPlugin>(fastifyStaticStar.default)
expectType<FastifyStaticPlugin>(fastifyStaticStar.fastifyStatic)
expectType<any>(fastifyStaticCjs)

// make sure instance properties are preserved
const serverWithHttp2 = fastify({ http2: true })
expectAssignable<typeof serverWithHttp2>(serverWithHttp2.register(fastifyStatic, { root: '/' }))

const appWithImplicitHttp = fastify()
const options: FastifyStaticOptions = {
acceptRanges: true,
Expand Down Expand Up @@ -119,8 +124,12 @@ expectAssignable<FastifyStaticOptions>({

appWithImplicitHttp
.register(fastifyStatic, options)
.after(() => {
appWithImplicitHttp.get('/', (request, reply) => {
.after((err, instance) => {
if (err) {
// handle error
}

instance.get('/', (request, reply) => {
reply.sendFile('some-file-name')
})
})
Expand All @@ -129,20 +138,24 @@ const appWithHttp2 = fastify({ http2: true })

appWithHttp2
.register(fastifyStatic, options)
.after(() => {
appWithHttp2.get('/', (request, reply) => {
.after((err, instance) => {

Choose a reason for hiding this comment

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

This is a breaking change since we no longer support the scenario of the test: if err and instance params are not defined, .sendFile will not exist at TS level
image

Copy link
Author

Choose a reason for hiding this comment

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

I do not see which test case this is, the code is obscured with the error message. Can you provide a test case that i can take a look at?

Choose a reason for hiding this comment

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

It refers to the test case on line 140.
Basically, with the change, this test should still pass

if (err) {
// handle error
}

instance.get('/', (request, reply) => {
reply.sendFile('some-file-name')
})

appWithHttp2.get('/download', (request, reply) => {
instance.get('/download', (request, reply) => {
reply.download('some-file-name')
})

appWithHttp2.get('/download/1', (request, reply) => {
instance.get('/download/1', (request, reply) => {
reply.download('some-file-name', { maxAge: '2 days' })
})

appWithHttp2.get('/download/2', (request, reply) => {
instance.get('/download/2', (request, reply) => {
reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true })
})
})
Expand All @@ -152,28 +165,32 @@ options.root = ['']

multiRootAppWithImplicitHttp
.register(fastifyStatic, options)
.after(() => {
multiRootAppWithImplicitHttp.get('/', (request, reply) => {
.after((err, instance) => {
if (err) {
// handle error
}

instance.get('/', (request, reply) => {
reply.sendFile('some-file-name')
})

multiRootAppWithImplicitHttp.get('/', (request, reply) => {
instance.get('/', (request, reply) => {
reply.sendFile('some-file-name', { cacheControl: false, acceptRanges: true })
})

multiRootAppWithImplicitHttp.get('/', (request, reply) => {
instance.get('/', (request, reply) => {
reply.sendFile('some-file-name', 'some-root-name', { cacheControl: false, acceptRanges: true })
})

multiRootAppWithImplicitHttp.get('/download', (request, reply) => {
instance.get('/download', (request, reply) => {
reply.download('some-file-name')
})

multiRootAppWithImplicitHttp.get('/download/1', (request, reply) => {
instance.get('/download/1', (request, reply) => {
reply.download('some-file-name', { maxAge: '2 days' })
})

multiRootAppWithImplicitHttp.get('/download/2', (request, reply) => {
instance.get('/download/2', (request, reply) => {
reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true })
})
})
Expand Down Expand Up @@ -210,3 +227,13 @@ defaultIndexApp
reply.send('<h1>fastify-static</h1>')
})
})

const pluginWithFastifyStaticDependency = createPlugin((instance) =>
instance.get('/', (req, res) => {
expectType<FastifyStaticPluginDecorators['reply']['sendFile']>(res.sendFile)
expectType<FastifyStaticPluginDecorators['reply']['download']>(res.download)
}), { dependencies: [fastifyStatic] })

expectError(fastify().register(pluginWithFastifyStaticDependency))

fastify().register(fastifyStatic, { root: '' }).register(pluginWithFastifyStaticDependency)