Skip to content
Open
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: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ Plugin for serving static files as fast as possible.
npm i @fastify/static
```

TypeScript users get `reply.sendFile()` and `reply.download()` from the plugin
registration itself, so those reply decorators are only available on instances
where `@fastify/static` has actually been registered.

### Compatibility

| Plugin version | Fastify version |
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"c8": "^10.1.3",
"concat-stream": "^2.0.0",
"eslint": "^9.17.0",
"fastify": "^5.1.0",
"fastify": "github:fastify/fastify#feat/typed-decorators",
"neostandard": "^0.12.0",
"pino": "^10.0.0",
"proxyquire": "^2.1.3",
Expand Down
50 changes: 27 additions & 23 deletions types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,34 @@
import { FastifyPluginAsync, FastifyReply, FastifyRequest, RouteOptions } from 'fastify'
import {
AnyFastifyInstance,
ApplyDecorators,
FastifyPluginAsync,
FastifyReply,
FastifyRequest,
RouteOptions,
UnEncapsulatedPlugin
} from 'fastify'
import { Stats } from 'node: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 @@ -56,7 +70,6 @@ declare namespace fastifyStatic {

export interface ListOptionsJsonFormat extends ListOptions {
format: 'json';
// Required when the URL parameter `format=html` exists
render?: ListRender;
}

Expand All @@ -65,7 +78,6 @@ declare namespace fastifyStatic {
render: ListRender;
}

// Passed on to `send`
export interface SendOptions {
acceptRanges?: boolean;
contentType?: boolean;
Expand Down Expand Up @@ -94,7 +106,6 @@ declare namespace fastifyStatic {
SendOptions
& RootOptions
& {
// Added by this plugin
prefix?: string;
prefixAvoidTrailingSlash?: boolean;
decorateReply?: boolean;
Expand All @@ -105,13 +116,7 @@ declare namespace fastifyStatic {
globIgnore?: string[];
list?: boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat;
allowedPath?: (pathName: string, root: string, request: FastifyRequest) => boolean;
/**
* @description
* Opt-in to looking for pre-compressed files
*/
preCompressed?: boolean;

// Passed on to `send`
acceptRanges?: boolean;
contentType?: boolean;
cacheControl?: boolean;
Expand All @@ -127,10 +132,9 @@ declare namespace fastifyStatic {
}

export const fastifyStatic: FastifyStaticPlugin

export { fastifyStatic as default }
}

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

export = fastifyStatic
211 changes: 41 additions & 170 deletions types/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,34 @@
import fastify, { FastifyInstance, FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify'
import { Server } from 'node:http'
import fastify, { FastifyReply, FastifyRequest } from 'fastify'
import { Stats } from 'node:fs'
import { expectAssignable, expectError, expectType } from 'tsd'
import * as fastifyStaticStar from '..'
import fastifyStatic, {
FastifyStaticPlugin,
FastifyStaticPluginDecorators,
FastifyStaticOptions,
fastifyStatic as fastifyStaticNamed
} from '..'

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

const app: FastifyInstance = fastify()

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

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
)
const app = fastify()
app.register(fastifyStatic, { root: '/' })
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)

const appWithImplicitHttp = fastify()
const options: FastifyStaticOptions = {
acceptRanges: true,
contentType: true,
Expand Down Expand Up @@ -59,13 +56,10 @@ const options: FastifyStaticOptions = {
res.setHeader('X-Test', 'string')

expectType<string>(path)

expectType<Stats>(stat)
},
preCompressed: false,
allowedPath: (_pathName: string, _root: string, _request: FastifyRequest) => {
return true
},
allowedPath: (_pathName: string, _root: string, _request: FastifyRequest) => true,
constraints: {
host: /^.*\.example\.com$/,
version: '1.0.2'
Expand All @@ -80,161 +74,38 @@ expectError<FastifyStaticOptions>({

expectAssignable<FastifyStaticOptions>({
root: '',
list: {
format: 'json'
}
})

expectAssignable<FastifyStaticOptions>({
root: '',
list: {
format: 'json',
render: () => ''
}
list: { format: 'json' }
})

expectAssignable<FastifyStaticOptions>({
root: '',
list: {
format: 'html',
render: () => ''
}
list: { format: 'html', render: () => '' }
})

expectError<FastifyStaticOptions>({
root: '',
list: {
format: 'html'
}
})

expectAssignable<FastifyStaticOptions>({
root: ['']
list: { format: 'html' }
})

expectAssignable<FastifyStaticOptions>({
root: new URL('')
expectAssignable<FastifyStaticOptions>({ root: [''] })
expectAssignable<FastifyStaticOptions>({ root: new URL('file:///tmp') })
expectAssignable<FastifyStaticOptions>({ root: [new URL('file:///tmp')] })
expectError<FastifyStaticOptions>({ serve: true })
expectAssignable<FastifyStaticOptions>({ serve: true, root: '' })
expectAssignable<FastifyStaticOptions>({ serve: false })

const registered = fastify().register(fastifyStatic, options)
registered.get('/', (_request, reply) => {
expectType<FastifyStaticPluginDecorators['reply']['sendFile']>(reply.sendFile)
expectType<FastifyStaticPluginDecorators['reply']['download']>(reply.download)
reply.sendFile('some-file-name')
reply.sendFile('some-file-name', { cacheControl: false })
reply.download('some-file-name')
reply.download('some-file-name', 'custom-name', { contentType: false })
})

expectAssignable<FastifyStaticOptions>({
root: [new URL('')]
})

expectError<FastifyStaticOptions>({
serve: true
})

expectAssignable<FastifyStaticOptions>({
serve: true,
root: ''
})

expectAssignable<FastifyStaticOptions>({
serve: false
const serverWithHttp2 = fastify({ http2: true }).register(fastifyStatic, { root: '/' })
serverWithHttp2.get('/', (_request, reply) => {
reply.sendFile('some-file-name')
reply.download('some-file-name')
})

appWithImplicitHttp
.register(fastifyStatic, options)
.after(() => {
appWithImplicitHttp.get('/', (_request, reply) => {
reply.sendFile('some-file-name')
})
})

const appWithHttp2 = fastify({ http2: true })

appWithHttp2
.register(fastifyStatic, options)
.after(() => {
appWithHttp2.get('/', (_request, reply) => {
reply.sendFile('some-file-name')
})

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

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

appWithHttp2.get('/download/2', (_request, reply) => {
reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true })
})

appWithHttp2.get('/download/3', (_request, reply) => {
reply.download('some-file-name', 'some-filename', { contentType: false })
})
})

const multiRootAppWithImplicitHttp = fastify()
options.root = ['']

multiRootAppWithImplicitHttp
.register(fastifyStatic, options)
.after(() => {
multiRootAppWithImplicitHttp.get('/', (_request, reply) => {
reply.sendFile('some-file-name')
})

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

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

multiRootAppWithImplicitHttp.get('/', (_request, reply) => {
reply.sendFile('some-file-name', 'some-root-name-2', { contentType: false })
})

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

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

multiRootAppWithImplicitHttp.get('/download/2', (_request, reply) => {
reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true })
})

multiRootAppWithImplicitHttp.get('/download/3', (_request, reply) => {
reply.download('some-file-name', 'some-filename', { contentType: false })
})
})

const noIndexApp = fastify()
options.root = ''
options.index = false

noIndexApp
.register(fastifyStatic, options)
.after(() => {
noIndexApp.get('/', (_request, reply) => {
reply.send('<h1>fastify-static</h1>')
})
})

options.root = new URL('')

const URLRootApp = fastify()
URLRootApp.register(fastifyStatic, options)
.after(() => {
URLRootApp.get('/', (_request, reply) => {
reply.send('<h1>fastify-static</h1>')
})
})

const defaultIndexApp = fastify()
options.index = 'index.html'

defaultIndexApp
.register(fastifyStatic, options)
.after(() => {
defaultIndexApp.get('/', (_request, reply) => {
reply.send('<h1>fastify-static</h1>')
})
})
Loading