common.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. export type Awaitable<T> = T | Promise<T>;
  2. // TODO: allow dispatching more events?
  3. export type Dispatcher = (
  4. type: "scheduled",
  5. init: { cron?: string }
  6. ) => Awaitable<void>;
  7. export type IncomingRequest = Request<
  8. unknown,
  9. IncomingRequestCfProperties<unknown>
  10. >;
  11. export interface MiddlewareContext {
  12. dispatch: Dispatcher;
  13. next(request: IncomingRequest, env: any): Awaitable<Response>;
  14. }
  15. export type Middleware = (
  16. request: IncomingRequest,
  17. env: any,
  18. ctx: ExecutionContext,
  19. middlewareCtx: MiddlewareContext
  20. ) => Awaitable<Response>;
  21. const __facade_middleware__: Middleware[] = [];
  22. // The register functions allow for the insertion of one or many middleware,
  23. // We register internal middleware first in the stack, but have no way of controlling
  24. // the order that addMiddleware is run in service workers so need an internal function.
  25. export function __facade_register__(...args: (Middleware | Middleware[])[]) {
  26. __facade_middleware__.push(...args.flat());
  27. }
  28. export function __facade_registerInternal__(
  29. ...args: (Middleware | Middleware[])[]
  30. ) {
  31. __facade_middleware__.unshift(...args.flat());
  32. }
  33. function __facade_invokeChain__(
  34. request: IncomingRequest,
  35. env: any,
  36. ctx: ExecutionContext,
  37. dispatch: Dispatcher,
  38. middlewareChain: Middleware[]
  39. ): Awaitable<Response> {
  40. const [head, ...tail] = middlewareChain;
  41. const middlewareCtx: MiddlewareContext = {
  42. dispatch,
  43. next(newRequest, newEnv) {
  44. return __facade_invokeChain__(newRequest, newEnv, ctx, dispatch, tail);
  45. },
  46. };
  47. return head(request, env, ctx, middlewareCtx);
  48. }
  49. export function __facade_invoke__(
  50. request: IncomingRequest,
  51. env: any,
  52. ctx: ExecutionContext,
  53. dispatch: Dispatcher,
  54. finalMiddleware: Middleware
  55. ): Awaitable<Response> {
  56. return __facade_invokeChain__(request, env, ctx, dispatch, [
  57. ...__facade_middleware__,
  58. finalMiddleware,
  59. ]);
  60. }