@universal-middleware/compress
Version:
Universal compress middleware
95 lines (91 loc) • 2.66 kB
JavaScript
import { bindUniversal, universalSymbol, getAdapterRuntime, contextSymbol } from './chunk-A5W3PKM7.js';
import { middleware_default } from './chunk-OE4YTAMF.js';
// ../adapter-hono/dist/index.js
function getExecutionCtx(honoContext) {
try {
return honoContext.executionCtx;
} catch {
return;
}
}
function createMiddleware(middlewareFactory) {
return (...args) => {
const middleware = middlewareFactory(...args);
return bindUniversal(middleware, async function universalMiddlewareHono(honoContext, next) {
const context = initContext(honoContext);
const response = await this[universalSymbol](honoContext.req.raw, context, getRuntime(honoContext));
if (typeof response === "function") {
await next();
const res = await response(honoContext.res);
if (res) {
honoContext.res = res;
}
} else if (response !== null && typeof response === "object") {
if (response instanceof Response) {
return stripHonoCache(response);
}
setContext(honoContext, response);
return next();
} else {
return next();
}
});
};
}
function stripHonoCache(response) {
const ownSymbols = Object.getOwnPropertySymbols(response);
for (const sym of ownSymbols) {
if (sym.toString() === "Symbol(cache)") {
delete response[sym];
}
}
return response;
}
function initContext(honoContext) {
let ctx = getContext(honoContext);
if (ctx === void 0) {
ctx = {};
setContext(honoContext, ctx);
}
return ctx;
}
function setContext(honoContext, value) {
honoContext.set(contextSymbol, value);
if (honoContext.env) {
honoContext.env[contextSymbol] = value;
}
if (honoContext.env?.eventContext?.env) {
honoContext.env.eventContext.env[contextSymbol] = value;
}
}
function getContext(honoContext) {
return honoContext.get(contextSymbol) ?? honoContext.env?.[contextSymbol] ?? honoContext.env?.eventContext?.env[contextSymbol];
}
function getRuntime(honoContext) {
let params;
const ctx = getExecutionCtx(honoContext);
try {
params = honoContext.req.param();
} catch {
if (ctx) {
params = ctx.params ?? void 0;
}
}
return getAdapterRuntime(
"hono",
{
params,
hono: honoContext
},
{
env: honoContext.env,
ctx,
req: honoContext.env?.incoming,
res: honoContext.env?.outgoing
},
honoContext.req.raw
);
}
// virtual:universal-middleware:virtual:universal-middleware:hono:middleware:src/middleware.ts
var middleware_default2 = createMiddleware(middleware_default);
export { middleware_default2 as default };