@fonderie/adapter-koa 1.0.1 → 1.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 +14 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +15 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -89,7 +89,13 @@ async function webResponseToKoa(webRes, ctx) {
|
|
|
89
89
|
function bridge(fonderie) {
|
|
90
90
|
return async (ctx, next) => {
|
|
91
91
|
const webReq = koaContextToWeb(ctx);
|
|
92
|
-
|
|
92
|
+
const fCtx = await fonderie.buildContext(webReq.clone());
|
|
93
|
+
const clientIp = (0, import_middlewares.resolveClientIp)(
|
|
94
|
+
ctx.req.socket?.remoteAddress ?? void 0,
|
|
95
|
+
webReq.headers
|
|
96
|
+
);
|
|
97
|
+
if (clientIp) fCtx.meta.clientIp = clientIp;
|
|
98
|
+
ctx.state["_fonderie"] = fCtx;
|
|
93
99
|
await next();
|
|
94
100
|
};
|
|
95
101
|
}
|
|
@@ -155,7 +161,13 @@ function requireFeature(key) {
|
|
|
155
161
|
function mount(app, fonderie) {
|
|
156
162
|
app.use(async (ctx, next) => {
|
|
157
163
|
const webReq = koaContextToWeb(ctx);
|
|
158
|
-
|
|
164
|
+
const fCtx = await fonderie.buildContext(webReq.clone());
|
|
165
|
+
const clientIp = (0, import_middlewares.resolveClientIp)(
|
|
166
|
+
ctx.req.socket?.remoteAddress ?? void 0,
|
|
167
|
+
webReq.headers
|
|
168
|
+
);
|
|
169
|
+
if (clientIp) fCtx.meta.clientIp = clientIp;
|
|
170
|
+
ctx.state["_fonderie"] = fCtx;
|
|
159
171
|
await next();
|
|
160
172
|
if (ctx.body === void 0) {
|
|
161
173
|
const webRes = await fonderie.handle(webReq);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\nimport type Koa from 'koa';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype KoaMiddleware<S = any, C = any> = Koa.Middleware<S, C>;\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth } 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// Minimal Koa shape used internally for Web Standard translation.\n// Application code uses Koa's own context types (Koa.ParameterizedContext).\nexport interface KoaContext {\n\trequest: {\n\t\turl: string;\n\t\tmethod: string;\n\t\trawBody?: string;\n\t\theaders: Record<string, string | string[] | undefined>;\n\t};\n\tresponse: {\n\t\tbody: unknown;\n\t\tstatus: number;\n\t\tset(key: string, value: string): void;\n\t};\n\treq: IncomingMessage;\n\tstate: Record<string, unknown>;\n}\n\nexport type KoaNext = () => Promise<void>;\n\n// ── Web Standard ↔ Koa translation ───────────────────────────────\n\nexport function koaContextToWeb(ctx: KoaContext): Request {\n\tconst encrypted = (ctx.req.socket as { encrypted?: boolean }).encrypted;\n\tconst protocol = encrypted ? 'https' : 'http';\n\tconst host = ctx.request.headers['host'] ?? 'localhost';\n\tconst url = `${protocol}://${host}${ctx.request.url}`;\n\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(ctx.request.headers)) {\n\t\tif (!value) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const v of value) headers.append(key, v);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\n\tconst method = ctx.request.method.toUpperCase();\n\tconst hasBody = method !== 'GET' && method !== 'HEAD';\n\n\treturn new Request(url, {\n\t\theaders,\n\t\tmethod,\n\t\tbody: hasBody ? (ctx.request.rawBody ?? null) : null,\n\t});\n}\n\nexport async function webResponseToKoa(webRes: Response, ctx: KoaContext): Promise<void> {\n\tctx.response.status = webRes.status;\n\twebRes.headers.forEach((value, key) => ctx.response.set(key, value));\n\tctx.response.body = await webRes.text();\n}\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Koa middleware. Populates ctx.state._fonderie with the fonderie context\n// (user, workspace, meta) for all subsequent route handlers.\n// Requires koa-bodyparser (or equivalent) to run first so rawBody is set.\n//\n// app.use(bodyParser())\n// app.use(bridge(fonderie))\n\nexport function bridge(fonderie: FonderieApp): KoaMiddleware {\n\treturn async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tctx.state['_fonderie'] = await fonderie.buildContext(webReq.clone());\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Koa\n// middleware function. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function adapt(middleware: Middleware): KoaMiddleware<any, any> {\n\treturn async (ctx, next) => {\n\t\tconst fCtx = (ctx.state as Record<string, unknown>)['_fonderie'] as\n\t\t\t| IFonderieContext\n\t\t\t| undefined;\n\t\tif (!fCtx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(fCtx, 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\tawait webResponseToKoa(result, ctx as unknown as KoaContext);\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 Koa middleware.\n//\n// router.get('/jobs', requireAuth, withWorkspace(store), ...)\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const requireAuth: KoaMiddleware<any, any> = 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. Koa middleware is async either way,\n// so the extra await changes nothing for callers.\n\nexport function withWorkspace(\n\tstore: Parameters<typeof _withWorkspace>[0],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function requireFeature(key: string): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Koa app. Uses Koa's onion model to register a\n// single wrap-around middleware: builds fonderie context, calls next()\n// so user routes run, then falls back to fonderie infra only if the\n// request was not handled (ctx.body is still undefined).\n//\n// Routes registered after mount() are included automatically — Koa\n// composes all middlewares lazily at request time, not at registration.\n//\n// app.use(bodyParser())\n// const api = mount(app, fonderie) // returns same app\n// api.use(router.routes())\n// api.use(router.allowedMethods())\n// app.listen(port)\n\nexport function mount(app: Koa, fonderie: FonderieApp): Koa {\n\tapp.use(async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tctx.state['_fonderie'] = await fonderie.buildContext(webReq.clone());\n\t\tawait next();\n\t\tif (ctx.body === undefined) {\n\t\t\tconst webRes = await fonderie.handle(webReq);\n\t\t\tawait webResponseToKoa(webRes, ctx as unknown as KoaContext);\n\t\t}\n\t});\n\treturn app;\n}\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,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,KAAK,IAAI;AAAA,EACvB;AACD;AAGO,SAAS,eAAe,KAAsC;AAEpE,MAAI;AACJ,SAAO,OAAO,KAAK,SAAS;AAC3B,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,KAAK,IAAI;AAAA,EACvB;AACD;AAkBO,SAAS,MAAM,KAAU,UAA4B;AAC3D,MAAI,IAAI,OAAO,KAAK,SAAS;AAC5B,UAAM,SAAS,gBAAgB,GAA4B;AAC3D,QAAI,MAAM,WAAW,IAAI,MAAM,SAAS,aAAa,OAAO,MAAM,CAAC;AACnE,UAAM,KAAK;AACX,QAAI,IAAI,SAAS,QAAW;AAC3B,YAAM,SAAS,MAAM,SAAS,OAAO,MAAM;AAC3C,YAAM,iBAAiB,QAAQ,GAA4B;AAAA,IAC5D;AAAA,EACD,CAAC;AACD,SAAO;AACR;","names":["_requireAuth"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\nimport type Koa from 'koa';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype KoaMiddleware<S = any, C = any> = Koa.Middleware<S, C>;\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// Minimal Koa shape used internally for Web Standard translation.\n// Application code uses Koa's own context types (Koa.ParameterizedContext).\nexport interface KoaContext {\n\trequest: {\n\t\turl: string;\n\t\tmethod: string;\n\t\trawBody?: string;\n\t\theaders: Record<string, string | string[] | undefined>;\n\t};\n\tresponse: {\n\t\tbody: unknown;\n\t\tstatus: number;\n\t\tset(key: string, value: string): void;\n\t};\n\treq: IncomingMessage;\n\tstate: Record<string, unknown>;\n}\n\nexport type KoaNext = () => Promise<void>;\n\n// ── Web Standard ↔ Koa translation ───────────────────────────────\n\nexport function koaContextToWeb(ctx: KoaContext): Request {\n\tconst encrypted = (ctx.req.socket as { encrypted?: boolean }).encrypted;\n\tconst protocol = encrypted ? 'https' : 'http';\n\tconst host = ctx.request.headers['host'] ?? 'localhost';\n\tconst url = `${protocol}://${host}${ctx.request.url}`;\n\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(ctx.request.headers)) {\n\t\tif (!value) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const v of value) headers.append(key, v);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\n\tconst method = ctx.request.method.toUpperCase();\n\tconst hasBody = method !== 'GET' && method !== 'HEAD';\n\n\treturn new Request(url, {\n\t\theaders,\n\t\tmethod,\n\t\tbody: hasBody ? (ctx.request.rawBody ?? null) : null,\n\t});\n}\n\nexport async function webResponseToKoa(webRes: Response, ctx: KoaContext): Promise<void> {\n\tctx.response.status = webRes.status;\n\twebRes.headers.forEach((value, key) => ctx.response.set(key, value));\n\tctx.response.body = await webRes.text();\n}\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Koa middleware. Populates ctx.state._fonderie with the fonderie context\n// (user, workspace, meta) for all subsequent route handlers.\n// Requires koa-bodyparser (or equivalent) to run first so rawBody is set.\n//\n// app.use(bodyParser())\n// app.use(bridge(fonderie))\n\nexport function bridge(fonderie: FonderieApp): KoaMiddleware {\n\treturn async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tconst fCtx = await fonderie.buildContext(webReq.clone());\n\t\tconst clientIp = resolveClientIp(\n\t\t\t(ctx as unknown as KoaContext).req.socket?.remoteAddress ?? undefined,\n\t\t\twebReq.headers,\n\t\t);\n\t\tif (clientIp) fCtx.meta.clientIp = clientIp;\n\t\tctx.state['_fonderie'] = fCtx;\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Koa\n// middleware function. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function adapt(middleware: Middleware): KoaMiddleware<any, any> {\n\treturn async (ctx, next) => {\n\t\tconst fCtx = (ctx.state as Record<string, unknown>)['_fonderie'] as\n\t\t\t| IFonderieContext\n\t\t\t| undefined;\n\t\tif (!fCtx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(fCtx, 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\tawait webResponseToKoa(result, ctx as unknown as KoaContext);\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 Koa middleware.\n//\n// router.get('/jobs', requireAuth, withWorkspace(store), ...)\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const requireAuth: KoaMiddleware<any, any> = 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. Koa middleware is async either way,\n// so the extra await changes nothing for callers.\n\nexport function withWorkspace(\n\tstore: Parameters<typeof _withWorkspace>[0],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function requireFeature(key: string): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Koa app. Uses Koa's onion model to register a\n// single wrap-around middleware: builds fonderie context, calls next()\n// so user routes run, then falls back to fonderie infra only if the\n// request was not handled (ctx.body is still undefined).\n//\n// Routes registered after mount() are included automatically — Koa\n// composes all middlewares lazily at request time, not at registration.\n//\n// app.use(bodyParser())\n// const api = mount(app, fonderie) // returns same app\n// api.use(router.routes())\n// api.use(router.allowedMethods())\n// app.listen(port)\n\nexport function mount(app: Koa, fonderie: FonderieApp): Koa {\n\tapp.use(async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tconst fCtx = await fonderie.buildContext(webReq.clone());\n\t\tconst clientIp = resolveClientIp(\n\t\t\t(ctx as unknown as KoaContext).req.socket?.remoteAddress ?? undefined,\n\t\t\twebReq.headers,\n\t\t);\n\t\tif (clientIp) fCtx.meta.clientIp = clientIp;\n\t\tctx.state['_fonderie'] = fCtx;\n\t\tawait next();\n\t\tif (ctx.body === undefined) {\n\t\t\tconst webRes = await fonderie.handle(webReq);\n\t\t\tawait webResponseToKoa(webRes, ctx as unknown as KoaContext);\n\t\t}\n\t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|
-
import { requireAuth as _requireAuth } from "@fonderie/core/middlewares";
|
|
2
|
+
import { requireAuth as _requireAuth, resolveClientIp } from "@fonderie/core/middlewares";
|
|
3
3
|
import { OPERATIONS } from "@fonderie/core";
|
|
4
4
|
async function loadOptionalPeer(load, pkg, api) {
|
|
5
5
|
try {
|
|
@@ -46,7 +46,13 @@ async function webResponseToKoa(webRes, ctx) {
|
|
|
46
46
|
function bridge(fonderie) {
|
|
47
47
|
return async (ctx, next) => {
|
|
48
48
|
const webReq = koaContextToWeb(ctx);
|
|
49
|
-
|
|
49
|
+
const fCtx = await fonderie.buildContext(webReq.clone());
|
|
50
|
+
const clientIp = resolveClientIp(
|
|
51
|
+
ctx.req.socket?.remoteAddress ?? void 0,
|
|
52
|
+
webReq.headers
|
|
53
|
+
);
|
|
54
|
+
if (clientIp) fCtx.meta.clientIp = clientIp;
|
|
55
|
+
ctx.state["_fonderie"] = fCtx;
|
|
50
56
|
await next();
|
|
51
57
|
};
|
|
52
58
|
}
|
|
@@ -112,7 +118,13 @@ function requireFeature(key) {
|
|
|
112
118
|
function mount(app, fonderie) {
|
|
113
119
|
app.use(async (ctx, next) => {
|
|
114
120
|
const webReq = koaContextToWeb(ctx);
|
|
115
|
-
|
|
121
|
+
const fCtx = await fonderie.buildContext(webReq.clone());
|
|
122
|
+
const clientIp = resolveClientIp(
|
|
123
|
+
ctx.req.socket?.remoteAddress ?? void 0,
|
|
124
|
+
webReq.headers
|
|
125
|
+
);
|
|
126
|
+
if (clientIp) fCtx.meta.clientIp = clientIp;
|
|
127
|
+
ctx.state["_fonderie"] = fCtx;
|
|
116
128
|
await next();
|
|
117
129
|
if (ctx.body === void 0) {
|
|
118
130
|
const webRes = await fonderie.handle(webReq);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\nimport type Koa from 'koa';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype KoaMiddleware<S = any, C = any> = Koa.Middleware<S, C>;\n\nimport type { FonderieApp, IFonderieContext, Middleware } from '@fonderie/core';\nimport { requireAuth as _requireAuth } 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// Minimal Koa shape used internally for Web Standard translation.\n// Application code uses Koa's own context types (Koa.ParameterizedContext).\nexport interface KoaContext {\n\trequest: {\n\t\turl: string;\n\t\tmethod: string;\n\t\trawBody?: string;\n\t\theaders: Record<string, string | string[] | undefined>;\n\t};\n\tresponse: {\n\t\tbody: unknown;\n\t\tstatus: number;\n\t\tset(key: string, value: string): void;\n\t};\n\treq: IncomingMessage;\n\tstate: Record<string, unknown>;\n}\n\nexport type KoaNext = () => Promise<void>;\n\n// ── Web Standard ↔ Koa translation ───────────────────────────────\n\nexport function koaContextToWeb(ctx: KoaContext): Request {\n\tconst encrypted = (ctx.req.socket as { encrypted?: boolean }).encrypted;\n\tconst protocol = encrypted ? 'https' : 'http';\n\tconst host = ctx.request.headers['host'] ?? 'localhost';\n\tconst url = `${protocol}://${host}${ctx.request.url}`;\n\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(ctx.request.headers)) {\n\t\tif (!value) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const v of value) headers.append(key, v);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\n\tconst method = ctx.request.method.toUpperCase();\n\tconst hasBody = method !== 'GET' && method !== 'HEAD';\n\n\treturn new Request(url, {\n\t\theaders,\n\t\tmethod,\n\t\tbody: hasBody ? (ctx.request.rawBody ?? null) : null,\n\t});\n}\n\nexport async function webResponseToKoa(webRes: Response, ctx: KoaContext): Promise<void> {\n\tctx.response.status = webRes.status;\n\twebRes.headers.forEach((value, key) => ctx.response.set(key, value));\n\tctx.response.body = await webRes.text();\n}\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Koa middleware. Populates ctx.state._fonderie with the fonderie context\n// (user, workspace, meta) for all subsequent route handlers.\n// Requires koa-bodyparser (or equivalent) to run first so rawBody is set.\n//\n// app.use(bodyParser())\n// app.use(bridge(fonderie))\n\nexport function bridge(fonderie: FonderieApp): KoaMiddleware {\n\treturn async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tctx.state['_fonderie'] = await fonderie.buildContext(webReq.clone());\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Koa\n// middleware function. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function adapt(middleware: Middleware): KoaMiddleware<any, any> {\n\treturn async (ctx, next) => {\n\t\tconst fCtx = (ctx.state as Record<string, unknown>)['_fonderie'] as\n\t\t\t| IFonderieContext\n\t\t\t| undefined;\n\t\tif (!fCtx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(fCtx, 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\tawait webResponseToKoa(result, ctx as unknown as KoaContext);\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 Koa middleware.\n//\n// router.get('/jobs', requireAuth, withWorkspace(store), ...)\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const requireAuth: KoaMiddleware<any, any> = 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. Koa middleware is async either way,\n// so the extra await changes nothing for callers.\n\nexport function withWorkspace(\n\tstore: Parameters<typeof _withWorkspace>[0],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function requireFeature(key: string): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Koa app. Uses Koa's onion model to register a\n// single wrap-around middleware: builds fonderie context, calls next()\n// so user routes run, then falls back to fonderie infra only if the\n// request was not handled (ctx.body is still undefined).\n//\n// Routes registered after mount() are included automatically — Koa\n// composes all middlewares lazily at request time, not at registration.\n//\n// app.use(bodyParser())\n// const api = mount(app, fonderie) // returns same app\n// api.use(router.routes())\n// api.use(router.allowedMethods())\n// app.listen(port)\n\nexport function mount(app: Koa, fonderie: FonderieApp): Koa {\n\tapp.use(async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tctx.state['_fonderie'] = await fonderie.buildContext(webReq.clone());\n\t\tawait next();\n\t\tif (ctx.body === undefined) {\n\t\t\tconst webRes = await fonderie.handle(webReq);\n\t\t\tawait webResponseToKoa(webRes, ctx as unknown as KoaContext);\n\t\t}\n\t});\n\treturn app;\n}\n"],"mappings":";AAOA,SAAS,eAAe,oBAAoB;AAQ5C,SAAS,kBAAkB;AAE3B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,WAAO,MAAM,KAAK,IAAI;AAAA,EACvB;AACD;AAGO,SAAS,eAAe,KAAsC;AAEpE,MAAI;AACJ,SAAO,OAAO,KAAK,SAAS;AAC3B,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,KAAK,IAAI;AAAA,EACvB;AACD;AAkBO,SAAS,MAAM,KAAU,UAA4B;AAC3D,MAAI,IAAI,OAAO,KAAK,SAAS;AAC5B,UAAM,SAAS,gBAAgB,GAA4B;AAC3D,QAAI,MAAM,WAAW,IAAI,MAAM,SAAS,aAAa,OAAO,MAAM,CAAC;AACnE,UAAM,KAAK;AACX,QAAI,IAAI,SAAS,QAAW;AAC3B,YAAM,SAAS,MAAM,SAAS,OAAO,MAAM;AAC3C,YAAM,iBAAiB,QAAQ,GAA4B;AAAA,IAC5D;AAAA,EACD,CAAC;AACD,SAAO;AACR;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http';\nimport type Koa from 'koa';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype KoaMiddleware<S = any, C = any> = Koa.Middleware<S, C>;\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// Minimal Koa shape used internally for Web Standard translation.\n// Application code uses Koa's own context types (Koa.ParameterizedContext).\nexport interface KoaContext {\n\trequest: {\n\t\turl: string;\n\t\tmethod: string;\n\t\trawBody?: string;\n\t\theaders: Record<string, string | string[] | undefined>;\n\t};\n\tresponse: {\n\t\tbody: unknown;\n\t\tstatus: number;\n\t\tset(key: string, value: string): void;\n\t};\n\treq: IncomingMessage;\n\tstate: Record<string, unknown>;\n}\n\nexport type KoaNext = () => Promise<void>;\n\n// ── Web Standard ↔ Koa translation ───────────────────────────────\n\nexport function koaContextToWeb(ctx: KoaContext): Request {\n\tconst encrypted = (ctx.req.socket as { encrypted?: boolean }).encrypted;\n\tconst protocol = encrypted ? 'https' : 'http';\n\tconst host = ctx.request.headers['host'] ?? 'localhost';\n\tconst url = `${protocol}://${host}${ctx.request.url}`;\n\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(ctx.request.headers)) {\n\t\tif (!value) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const v of value) headers.append(key, v);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\n\tconst method = ctx.request.method.toUpperCase();\n\tconst hasBody = method !== 'GET' && method !== 'HEAD';\n\n\treturn new Request(url, {\n\t\theaders,\n\t\tmethod,\n\t\tbody: hasBody ? (ctx.request.rawBody ?? null) : null,\n\t});\n}\n\nexport async function webResponseToKoa(webRes: Response, ctx: KoaContext): Promise<void> {\n\tctx.response.status = webRes.status;\n\twebRes.headers.forEach((value, key) => ctx.response.set(key, value));\n\tctx.response.body = await webRes.text();\n}\n\n// ── bridge ────────────────────────────────────────────────────────\n//\n// Koa middleware. Populates ctx.state._fonderie with the fonderie context\n// (user, workspace, meta) for all subsequent route handlers.\n// Requires koa-bodyparser (or equivalent) to run first so rawBody is set.\n//\n// app.use(bodyParser())\n// app.use(bridge(fonderie))\n\nexport function bridge(fonderie: FonderieApp): KoaMiddleware {\n\treturn async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tconst fCtx = await fonderie.buildContext(webReq.clone());\n\t\tconst clientIp = resolveClientIp(\n\t\t\t(ctx as unknown as KoaContext).req.socket?.remoteAddress ?? undefined,\n\t\t\twebReq.headers,\n\t\t);\n\t\tif (clientIp) fCtx.meta.clientIp = clientIp;\n\t\tctx.state['_fonderie'] = fCtx;\n\t\tawait next();\n\t};\n}\n\n// ── adapt ─────────────────────────────────────────────────────────\n//\n// Low-level escape hatch — wraps any fonderie Middleware into a Koa\n// middleware function. Use this for custom fonderie middleware; prefer the\n// named exports below for the built-in fonderie guards.\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function adapt(middleware: Middleware): KoaMiddleware<any, any> {\n\treturn async (ctx, next) => {\n\t\tconst fCtx = (ctx.state as Record<string, unknown>)['_fonderie'] as\n\t\t\t| IFonderieContext\n\t\t\t| undefined;\n\t\tif (!fCtx) throw new Error('[fonderie] bridge() must be registered before adapt()');\n\n\t\tlet continued = false;\n\t\tconst result = await middleware(fCtx, 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\tawait webResponseToKoa(result, ctx as unknown as KoaContext);\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 Koa middleware.\n//\n// router.get('/jobs', requireAuth, withWorkspace(store), ...)\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const requireAuth: KoaMiddleware<any, any> = 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. Koa middleware is async either way,\n// so the extra await changes nothing for callers.\n\nexport function withWorkspace(\n\tstore: Parameters<typeof _withWorkspace>[0],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\nexport function requirePermission(\n\toperation: Parameters<typeof _requirePermission>[0],\n\tpermissionKey: Parameters<typeof _requirePermission>[1],\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function requireFeature(key: string): KoaMiddleware<any, any> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tlet inner: KoaMiddleware<any, any> | undefined;\n\treturn async (ctx, 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(ctx, next);\n\t};\n}\n\n// ── mount ─────────────────────────────────────────────────────────\n//\n// Wires up fonderie to a Koa app. Uses Koa's onion model to register a\n// single wrap-around middleware: builds fonderie context, calls next()\n// so user routes run, then falls back to fonderie infra only if the\n// request was not handled (ctx.body is still undefined).\n//\n// Routes registered after mount() are included automatically — Koa\n// composes all middlewares lazily at request time, not at registration.\n//\n// app.use(bodyParser())\n// const api = mount(app, fonderie) // returns same app\n// api.use(router.routes())\n// api.use(router.allowedMethods())\n// app.listen(port)\n\nexport function mount(app: Koa, fonderie: FonderieApp): Koa {\n\tapp.use(async (ctx, next) => {\n\t\tconst webReq = koaContextToWeb(ctx as unknown as KoaContext);\n\t\tconst fCtx = await fonderie.buildContext(webReq.clone());\n\t\tconst clientIp = resolveClientIp(\n\t\t\t(ctx as unknown as KoaContext).req.socket?.remoteAddress ?? undefined,\n\t\t\twebReq.headers,\n\t\t);\n\t\tif (clientIp) fCtx.meta.clientIp = clientIp;\n\t\tctx.state['_fonderie'] = fCtx;\n\t\tawait next();\n\t\tif (ctx.body === undefined) {\n\t\t\tconst webRes = await fonderie.handle(webReq);\n\t\t\tawait webResponseToKoa(webRes, ctx as unknown as KoaContext);\n\t\t}\n\t});\n\treturn app;\n}\n"],"mappings":";AAOA,SAAS,eAAe,cAAc,uBAAuB;AAQ7D,SAAS,kBAAkB;AAE3B,eAAe,iBAAoB,MAAwB,KAAa,KAAyB;AAChG,MAAI;AACH,WAAO,MAAM,KAAK;AAAA,EACnB,SAAS,KAAK;A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