Skip to content

Commit

Permalink
feat: new middleware hatsu
Browse files Browse the repository at this point in the history
  • Loading branch information
kwaa committed Jul 9, 2024
1 parent 3364557 commit 71f299c
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions middlewares/hatsu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type { Middleware } from "../core/server.ts";

export interface Options {
/**
* Hatsu instance URL.
*
* @default
* ```ts
* new URL('https://hatsu.local')
* ```
*/
instance: URL;
/**
* Match routes.
*
* @default
* ```ts
* [/^\/posts\/(.+)$/]
* ```
*/
matches?: (RegExp | string)[];
/**
* Whether to copy `/.well-known/` files.
* @default `undefined`
*/
wellKnown?: false;
/**
* Lume Site Location.
* @defaultValue
* ```ts
* new URL(req.url).host
* ```
* @example
* ```ts
* const site = lume({ location: new URL('https://example.com') })
* const server = new Server()
* server.use(hatsuMiddleware({
* instance: new URL('https://hatsu.local'),
* location: site.options.location,
* }))
* ```
*/
location?: URL;
}

export default (options: Options): Middleware => async (req, next) => {
const accept = req.headers.get("accept");
const { origin, pathname, search } = new URL(req.url);

// redirect .well-known
if (pathname.startsWith("/.well-known/")) {
return Response.redirect(
new URL(pathname + search, options.instance),
);
} else if (
// redirect application/activity+json request
accept?.includes("application/activity+json") &&
(!options.matches ||
(options.matches.some((match) =>
match instanceof RegExp
? pathname.match(match)
: pathname.includes(match)
)))
) {
return Response.redirect(
new URL(
`/posts/${origin + pathname}`,
options.instance,
),
);
} else {
return await next(req);
}
};

0 comments on commit 71f299c

Please sign in to comment.