UNPKG

@trifrost/core

Version:

Blazingly fast, runtime-agnostic server framework for modern edge and node environments

85 lines (84 loc) 2.95 kB
"use strict"; /// <reference types="@cloudflare/workers-types" /> Object.defineProperty(exports, "__esModule", { value: true }); exports.WorkerdRuntime = void 0; const Logger_1 = require("../../modules/Logger"); const Generic_1 = require("../../utils/Generic"); const Context_1 = require("./Context"); class WorkerdRuntime { /* Global logger instance when runtime has started */ #logger = null; /* Runtime Start Options */ #cfg = null; /* Runtime-Enriched Config */ #runtimeCfg = null; /* Incoming handler which is to be called by the runtime when an incoming request happens */ #onIncoming = null; /** * MARK: Workerd handlers */ exports = { fetch: async (request, env, cloudflareCtx) => { if (!this.#onIncoming) return new Response('Internal Server Error', { status: 500 }); /* JIT Runtime config resolution */ if (!this.#runtimeCfg) { const runtimeEnv = { ...env, ...(this.#cfg.env || {}) }; this.#runtimeCfg = { ...this.#cfg, env: runtimeEnv, trustProxy: (0, Generic_1.determineTrustProxy)(runtimeEnv, true), }; } /* Instantiate context */ const ctx = new Context_1.WorkerdContext(this.#runtimeCfg, this.#logger, request, cloudflareCtx); try { await this.#onIncoming(ctx); if (!ctx.response) throw new Error('Handler did not respond'); return ctx.response; } catch (err) { this.#logger.error(err, { ctx: ctx.method, path: ctx.path }); return new Response('Internal Server Error', { status: 500 }); } }, }; /** * MARK: Runtime Implementation */ get name() { return 'Workerd'; } get version() { return null; } async boot(opts) { /* Set onIncoming handler */ this.#onIncoming = opts.onIncoming; /* Set logger instance */ this.#logger = opts.logger; /** * Set global config. * Take Note: Given that cloudflare workers/workerd by design runs in a trusted environment * we default trustProxy to true here. */ this.#cfg = { ...opts.cfg }; this.#logger.debug('WorkerdRuntime@boot'); } defaultExporter(env) { return (0, Generic_1.isDevMode)(env) ? new Logger_1.ConsoleExporter() : new Logger_1.JsonExporter(); } async shutdown() { if (!this.#onIncoming) return; this.#logger.debug('WorkerdRuntime@stop'); /* Clear onIncoming handler */ this.#onIncoming = null; /* Clear logger instance */ this.#logger = null; /* Clear global config */ this.#cfg = null; } } exports.WorkerdRuntime = WorkerdRuntime;