@fonderie/adapter-hono 6.0.1 → 6.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -62,6 +62,9 @@ function bridge(fonderie, options = {}) {
|
|
|
62
62
|
const ctx = await fonderie.buildContext(c.req.raw);
|
|
63
63
|
const early = ctx.meta["pipelineResponse"];
|
|
64
64
|
if (early instanceof Response) return early;
|
|
65
|
+
if (ctx.request !== c.req.raw) {
|
|
66
|
+
c.req.raw = ctx.request;
|
|
67
|
+
}
|
|
65
68
|
const socketIp = c.env?.incoming?.socket?.remoteAddress;
|
|
66
69
|
const headerIp = options.ipHeader ? c.req.raw.headers.get(options.ipHeader) ?? void 0 : void 0;
|
|
67
70
|
const clientIp = (0, import_middlewares.resolveClientIp)(headerIp ?? socketIp ?? void 0, c.req.raw.headers);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth, resolveClientIp } from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,yBAA6D;AAQ7D,kBAA2B;AAE3B,eAAe,iBAAoB,MAAwB,KAAa,KAAyB;AAChG,MAAI;AACH,WAAO,MAAM,KAAK;AAAA,EACnB,SAAS,KAAK;AACb,UAAM,IAAI;AACV,UAAM,WAAW,GAAG,SAAS,0BAA0B,GAAG,SAAS;AAInE,UAAM,UAAU,WAAW,2CAA2C,KAAK,GAAG,WAAW,EAAE,IAAI,CAAC,IAAI;AACpG,QAAI,YAAY,OAAO,SAAS,WAAW,MAAM,GAAG,GAAG;AACtD,YAAM,IAAI;AAAA,QACT,cAAc,GAAG,2CAA2C,GAAG,8BAA8B,GAAG;AAAA,MACjG;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;AAoCO,SAAS,OAAO,UAAuB,UAA0B,CAA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AO;AACX,YAAM,MAAM,MAAM;AAAA,QACjB,MAAM,OAAO,uBAAuB;AAAA,QACpC;AAAA,QACA;AAAA,MACD;AACA,cAAQ,MAAM,IAAI,kBAAkB,WAAW,aAAa,CAAC;AAAA,IAC9D;AACA,WAAO,MAAM,GAAG,IAAI;AAAA,EACrB;AACD;AAEO,SAAS,eAAe,KAAgC;AAC9D,MAAI;AACJ,SAAO,OAAO,GAAG,SAAS;AACzB,QAAI,CAAC,OAAO;AACX,YAAM,MAAM,MAAM;AAAA,QACjB,MAAM,OAAO,mBAAmB;AAAA,QAChC;AAAA,QACA;AAAA,MACD;AACA,cAAQ,MAAM,IAAI,eAAe,GAAG,CAAC;AAAA,IACtC;AACA,WAAO,MAAM,GAAG,IAAI;AAAA,EACrB;AACD;AAeO,SAAS,MAAM,MAAY,UAA6B;AAC9D,OAAK,SAAS,CAAC,MAAM;AAKpB,UAAM,MAAM,EAAE,IAAI,WAAW;AAC7B,WAAO,SAAS,OAAO,KAAK,WAAW,EAAE,IAAI,GAAG;AAAA,EACjD,CAAC;AACD,SAAO;AACR;","names":["_requireAuth"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth, resolveClientIp } from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// buildContext CONSUMED c.req.raw's body (no clone — a tee stalls on\n\t\t// large bodies). Core's parser re-materialized ctx.request from the\n\t\t// buffered bytes; point Hono's request at it so the app's OWN native\n\t\t// handlers (c.req.json()/text()/parseBody()) still read the body —\n\t\t// otherwise they'd hit a drained stream. For content-types the parser\n\t\t// leaves untouched (multipart), ctx.request === the original, so this\n\t\t// is a no-op. bodyCache is empty here (nothing read yet).\n\t\tif (ctx.request !== c.req.raw) {\n\t\t\t(c.req as { raw: Request }).raw = ctx.request;\n\t\t}\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,yBAA6D;AAQ7D,kBAA2B;AAE3B,eAAe,iBAAoB,MAAwB,KAAa,KAAyB;AAChG,MAAI;AACH,WAAO,MAAM,KAAK;AAAA,EACnB,SAAS,KAAK;AACb,UAAM,IAAI;AACV,UAAM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ACD;AAUO,IAAM,cAAiC,MAAM,mBAAAA,WAAY;AAMzD,SAAS,cAAc,OAAgE;AAC7F,MAAI;AACJ,SAAO,OAAO,GAAG,SAAS;AACzB,QAAI,CAAC,OAAO;AACX,YAAM,MAAM,MAAM;AAAA,QACjB,MAAM,OAAO,sBAAsB;AAAA,QACnC;AAAA,QACA;AAAA,MACD;AACA,cAAQ,MAAM,IAAI,cAAc,KAAK,CAAC;AAAA,IACvC;AACA,WAAO,MAAM,GAAG,IAAI;AAAA,EACrB;AACD;AAEO,SAAS,kBACf,WACA,eACoB;AACpB,MAAI;AACJ,SAAO,OAAO,GAAG,SAAS;AACzB,QAAI,CAAC,OAAO;AACX,YAAM,MAAM,MAAM;AAAA,QACjB,MAAM,OAAO,uBAAuB;AAAA,QACpC;AAAA,QACA;AAAA,MACD;AACA,cAAQ,MAAM,IAAI,kBAAkB,WAAW,aAAa,CAAC;AAAA,IAC9D;AACA,WAAO,MAAM,GAAG,IAAI;AAAA,EACrB;AACD;AAEO,SAAS,eAAe,KAAgC;AAC9D,MAAI;AACJ,SAAO,OAAO,GAAG,SAAS;AACzB,QAAI,CAAC,OAAO;AACX,YAAM,MAAM,MAAM;AAAA,QACjB,MAAM,OAAO,mBAAmB;AAAA,QAChC;AAAA,QACA;AAAA,MACD;AACA,cAAQ,MAAM,IAAI,eAAe,GAAG,CAAC;AAAA,IACtC;AACA,WAAO,MAAM,GAAG,IAAI;AAAA,EACrB;AACD;AAeO,SAAS,MAAM,MAAY,UAA6B;AAC9D,OAAK,SAAS,CAAC,MAAM;AAKpB,UAAM,MAAM,EAAE,IAAI,WAAW;AAC7B,WAAO,SAAS,OAAO,KAAK,WAAW,EAAE,IAAI,GAAG;AAAA,EACjD,CAAC;AACD,SAAO;AACR;","names":["_requireAuth"]}
|
package/dist/index.js
CHANGED
|
@@ -21,6 +21,9 @@ function bridge(fonderie, options = {}) {
|
|
|
21
21
|
const ctx = await fonderie.buildContext(c.req.raw);
|
|
22
22
|
const early = ctx.meta["pipelineResponse"];
|
|
23
23
|
if (early instanceof Response) return early;
|
|
24
|
+
if (ctx.request !== c.req.raw) {
|
|
25
|
+
c.req.raw = ctx.request;
|
|
26
|
+
}
|
|
24
27
|
const socketIp = c.env?.incoming?.socket?.remoteAddress;
|
|
25
28
|
const headerIp = options.ipHeader ? c.req.raw.headers.get(options.ipHeader) ?? void 0 : void 0;
|
|
26
29
|
const clientIp = resolveClientIp(headerIp ?? socketIp ?? void 0, c.req.raw.headers);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth, resolveClientIp } from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n"],"mappings":";AAIA,SAAS,eAAe,cAAc,uBAAuB;AAQ7D,SAAS,kBAAkB;AAE3B,eAAe,iBAAoB,MAAwB,KAAa,KAAyB;AAChG,MAAI;AACH,WAAO,MAAM,KAAK;AAAA,EACnB,SAAS,KAAK;AACb,UAAM,IAAI;AACV,UAAM,WAAW,GAAG,SAAS,0BAA0B,GAAG,SAAS;AAInE,UAAM,UAAU,WAAW,2CAA2C,KAAK,GAAG,WAAW,EAAE,IAAI,CAAC,IAAI;AACpG,QAAI,YAAY,OAAO,SAAS,WAAW,MAAM,GAAG,GAAG;AACtD,YAAM,IAAI;AAAA,QACT,cAAc,GAAG,2CAA2C,GAAG,8BAA8B,GAAG;AAAA,MACjG;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;AAoCO,SAAS,OAAO,UAAuB,UAA0B,CAAC,GAAsB;AAC9F,SAAO,OAAO,GAAG,SAAS;AAOzB,UAAM,MAAM,MAAM,SAAS,aAAa,EAAE,IAAI,GAAG;AAIjD,UAAM,QAAQ,IAAI,KAAK,kBAAkB;AACzC,QAAI,iBAAiB,SAAU,QAAO;AAStC,UAAM,WACL,EAAE,KACA,UAAU,QAAQ;AACrB,UAAM,WAAW,QAAQ,WACrB,EAAE,IAAI,IAAI,QAAQ,IAAI,QAAQ,QAAQ,KAAK,SAC5C;AACH,UAAM,WAAW,gBAAgB,YAAY,YAAY,QAAW,EAAE,IAAI,IAAI,OAAO;AACrF,QAAI,SAAU,KAAI,KAAK,WAAW;AAClC,MAAE,IAAI,aAAa,GAAG;A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AAO,MAAM,GAAG,IAAI;AAAA,EACrB;AACD;AAeO,SAAS,MAAM,MAAY,UAA6B;AAC9D,OAAK,SAAS,CAAC,MAAM;AAKpB,UAAM,MAAM,EAAE,IAAI,WAAW;AAC7B,WAAO,SAAS,OAAO,KAAK,WAAW,EAAE,IAAI,GAAG;AAAA,EACjD,CAAC;AACD,SAAO;AACR;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Context, MiddlewareHandler } from 'hono';\nimport type { Hono } from 'hono';\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth, resolveClientIp } from '@fonderie/core/middlewares';\n// Optional peers: type-only imports (erased at runtime). The guard factories\n// below load them lazily so installing this adapter never requires\n// @fonderie/workspaces, @fonderie/permissions, or @fonderie/billing unless\n// the corresponding guard is actually used.\nimport type { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport type { requirePermission as _requirePermission } from '@fonderie/permissions';\n\nexport { OPERATIONS } from '@fonderie/core';\n\nasync function loadOptionalPeer<T>(load: () => Promise<T>, pkg: string, api: string): Promise<T> {\n\ttry {\n\t\treturn await load();\n\t} catch (err) {\n\t\tconst e = err as { code?: string; message?: string } | undefined;\n\t\tconst notFound = e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND';\n\t\t// Only claim the peer is missing when the unresolved specifier IS the\n\t\t// peer — a transitive failure inside an installed peer must surface\n\t\t// as-is, not as a misleading install hint.\n\t\tconst missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? '')?.[1] : undefined;\n\t\tif (missing === pkg || missing?.startsWith(pkg + '/')) {\n\t\t\tthrow new Error(\n\t\t\t\t`[fonderie] ${api} requires the optional peer dependency \"${pkg}\". Install it: npm install ${pkg}`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n// Augment Hono's ContextVariableMap so c.get('_fonderie') is typed.\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t_fonderie: IFonderieContext;\n\t}\n}\n\n// Re-export for consumers who want to type their Hono app:\n// const hono = new Hono<{ Variables: FonderieVariables }>()\nexport type FonderieVariables = {\n\t_fonderie: IFonderieContext;\n};\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Global middleware. Runs fonderie's session + billing global stack so that\n// ctx.user and ctx.meta['billing'] are available in every route handler.\n// Must be registered before any fonderie-aware route middleware.\n//\n// hono.use('*', bridge(fonderie))\n\nexport interface IBridgeOptions {\n\t/**\n\t * Name of the header that carries the PLATFORM-VERIFIED client IP — e.g.\n\t * 'cf-connecting-ip' on Cloudflare, 'x-real-ip' behind an nginx that sets\n\t * it. This is an explicit opt-in: request headers are attacker-settable,\n\t * so trusting one by default would let any client spoof its IP and dodge\n\t * per-IP rate limits (auth brute-force limiters key on this). Only set it\n\t * when your platform/proxy STRIPS the header from client requests and\n\t * injects its own value.\n\t */\n\tipHeader?: string;\n}\n\nexport function bridge(fonderie: FonderieApp, options: IBridgeOptions = {}): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// No clone(): teeing a request and fully reading ONE branch while the\n\t\t// other sits unread stalls once the body crosses the stream's\n\t\t// high-water mark (undici's tee applies backpressure from the slower\n\t\t// consumer). buildContext consumes the body and core's parser\n\t\t// re-materializes ctx.request from the buffered bytes, so mount() and\n\t\t// app routes read from THAT instead of the spent raw request.\n\t\tconst ctx = await fonderie.buildContext(c.req.raw);\n\t\t// A global middleware short-circuited while building context (e.g. the\n\t\t// body parser's 413) — that response must reach the client, not be\n\t\t// swallowed by context-building.\n\t\tconst early = ctx.meta['pipelineResponse'];\n\t\tif (early instanceof Response) return early;\n\t\t// buildContext CONSUMED c.req.raw's body (no clone — a tee stalls on\n\t\t// large bodies). Core's parser re-materialized ctx.request from the\n\t\t// buffered bytes; point Hono's request at it so the app's OWN native\n\t\t// handlers (c.req.json()/text()/parseBody()) still read the body —\n\t\t// otherwise they'd hit a drained stream. For content-types the parser\n\t\t// leaves untouched (multipart), ctx.request === the original, so this\n\t\t// is a no-op. bodyCache is empty here (nothing read yet).\n\t\tif (ctx.request !== c.req.raw) {\n\t\t\t(c.req as { raw: Request }).raw = ctx.request;\n\t\t}\n\t\t// Client IP, spoof-safe by default (mirrors core's trustProxy model):\n\t\t// 1. The real socket address when the runtime exposes one\n\t\t// (@hono/node-server puts the node request on c.env.incoming).\n\t\t// 2. A platform header ONLY when explicitly configured via ipHeader.\n\t\t// 3. X-Forwarded-For only per core's TRUST_PROXY hop count.\n\t\t// Previously cf-connecting-ip/x-real-ip were trusted UNCONDITIONALLY,\n\t\t// which let any direct client forge its IP (fresh rate-limit bucket per\n\t\t// request) or omit it (limiter skipped) on self-hosted deployments.\n\t\tconst socketIp = (\n\t\t\tc.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined\n\t\t)?.incoming?.socket?.remoteAddress;\n\t\tconst headerIp = options.ipHeader\n\t\t\t? (c.req.raw.headers.get(options.ipHeader) ?? undefined)\n\t\t\t: undefined;\n\t\tconst clientIp = resolveClientIp(headerIp ?? socketIp ?? undefined, c.req.raw.headers);\n\t\tif (clientIp) ctx.meta.clientIp = clientIp;\n\t\tc.set('_fonderie', ctx);\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Hono\n// MiddlewareHandler. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\nexport function adapt(middleware: Middleware): MiddlewareHandler {\n\treturn async (c: Context, next) => {\n\t\tconst ctx = c.get('_fonderie');\n\t\tif (!ctx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(ctx, async () => {\n\t\t\tcontinued = true;\n\t\t\treturn new Response();\n\t\t});\n\n\t\tif (continued) {\n\t\t\tawait next();\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ── Pre-adapted middleware ────────────────────────────────────────\n//\n// Drop-in replacements for the fonderie middleware functions — no adapt()\n// needed. Import directly from this package instead of from the source\n// packages, and use them as native Hono middleware.\n//\n// hono.get('/jobs', requireAuth, withWorkspace(store), ...)\n\nexport const requireAuth: MiddlewareHandler = adapt(_requireAuth);\n\n// The three guards below wrap OPTIONAL peers, so the peer is imported lazily\n// on first request — not at module load. MiddlewareHandler is async either\n// way, so the extra await changes nothing for callers.\n\nexport function withWorkspace(store: Parameters<typeof _withWorkspace>[0]): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/workspaces'),\n\t\t\t\t'@fonderie/workspaces',\n\t\t\t\t'withWorkspace()',\n\t\t\t);\n\t\t\tinner = adapt(mod.withWorkspace(store));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/permissions'),\n\t\t\t\t'@fonderie/permissions',\n\t\t\t\t'requirePermission()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requirePermission(operation, permissionKey));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\nexport function requireFeature(key: string): MiddlewareHandler {\n\tlet inner: MiddlewareHandler | undefined;\n\treturn async (c, next) => {\n\t\tif (!inner) {\n\t\t\tconst mod = await loadOptionalPeer(\n\t\t\t\t() => import('@fonderie/billing'),\n\t\t\t\t'@fonderie/billing',\n\t\t\t\t'requireFeature()',\n\t\t\t);\n\t\t\tinner = adapt(mod.requireFeature(key));\n\t\t}\n\t\treturn inner(c, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Hono app. Returns the same app so you can add\n// routes after mount() — fonderie infra is the notFound handler, so\n// user routes always take priority:\n//\n// const api = mount(hono, fonderie)\n// api.get('/v1/todos', requireAuth, handler)\n// export default hono\n\n// mount() wires fonderie's infrastructure routes as the notFound fallback so\n// user routes always take priority. Call bridge() yourself before your routes\n// to ensure _fonderie is populated for them.\nexport function mount(hono: Hono, fonderie: FonderieApp): Hono {\n\thono.notFound((c) => {\n\t\t// bridge() consumed the raw body (see its no-clone note) and core's\n\t\t// parser re-materialized ctx.request with the buffered bytes — route\n\t\t// fonderie's handling through THAT. Without bridge (no ctx), the raw\n\t\t// request is untouched and safe to hand over directly.\n\t\tconst ctx = c.get('_fonderie') as IFonderieContext | undefined;\n\t\treturn fonderie.handle(ctx?.request ?? c.req.raw);\n\t});\n\treturn hono;\n}\n"],"mappings":";AAIA,SAAS,eAAe,cAAc,uBAAuB;AAQ7D,SAAS,kBAAkB;AAE3B,eAAe,iBAAoB,MAAwB,KAAa,KAAyB;AAChG,MAAI;AACH,WAAO,MAAM,KAAK;AAAA,EACnB,SAAS,KAAK;AACb,UAAM,IAAI;AACV,UAAM,WAAW,GAAG,SAAS,0BAA0B,GAAG,SAAS;AAInE,UAAM,UAAU,WAAW,2CAA2C,KAAK,GAAG,WAAW,EAAE,IAAI,CAAC,IAAI;AACpG,QAAI,YAAY,OAAO,SAAS,WAAW,MAAM,GAAG,GAAG;AACtD,YAAM,IAAI;AAAA,QACT,cAAc,GAAG,2CAA2C,GAAG,8BAA8B,GAAG;AAAA,MACjG;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;AAoCO,SAAS,OAAO,UAAuB,UAA0B,CAAC,GAAsB;AAC9F,SAAO,OAAO,GAAG,SAAS;AAOzB,UAAM,MAAM,MAAM,SAAS,aAAa,EAAE,IAAI,GAAG;AAIjD,UAAM,QAAQ,IAAI,KAAK,kBAAkB;AACzC,QAAI,iBAAiB,SAAU,QAAO;AAQtC,QAAI,IAAI,YAAY,EAAE,IAAI,KAA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