@fonderie/adapter-koa 1.0.0 → 1.0.1

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/README.md CHANGED
@@ -13,13 +13,35 @@ npm install @fonderie/adapter-koa
13
13
  ## Use
14
14
 
15
15
  ```ts
16
- import { bridge, adapt, requireAuth } from '@fonderie/adapter-koa';
17
- ```
16
+ import Koa from 'koa';
17
+ import bodyParser from 'koa-bodyparser';
18
+ import Router from '@koa/router';
19
+ import { mount, requireAuth, withWorkspace } from '@fonderie/adapter-koa';
20
+ import { buildFonderie } from './fonderie'; // your FonderieApp — see @fonderie/core
21
+
22
+ const { fonderie, store } = await buildFonderie();
23
+
24
+ const app = new Koa();
25
+ app.use(bodyParser()); // must run first so rawBody is populated
18
26
 
19
- Register `bridge(fonderie)` as global middleware first, then use the
20
- re-exported guards (`requireAuth`, `requireWorkspace`, `requirePermission`,
21
- `requireFeature`) directly on routes.
27
+ // mount() builds the fonderie context for every request and falls back to
28
+ // fonderie's infra routes when no user route handled the request.
29
+ mount(app, fonderie);
30
+
31
+ const router = new Router();
32
+ router.get('/jobs', requireAuth, withWorkspace(store), (ctx) => {
33
+ const f = ctx.state._fonderie;
34
+ ctx.body = { user: f.user, workspace: f.workspace };
35
+ });
36
+ app.use(router.routes());
37
+
38
+ app.listen(3000);
39
+ ```
22
40
 
41
+ The guards `withWorkspace`, `requirePermission`, and `requireFeature` load
42
+ their peer package lazily on first request — install `@fonderie/workspaces`,
43
+ `@fonderie/permissions`, or `@fonderie/billing` only if you use the matching
44
+ guard. For custom Fonderie middleware, wrap it with `adapt()`.
23
45
  `koaContextToWeb` converts Koa contexts to web-standard `Request` objects
24
46
  for the Fonderie pipeline.
25
47
 
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,12 +17,20 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
23
- OPERATIONS: () => import_permissions2.OPERATIONS,
33
+ OPERATIONS: () => import_core.OPERATIONS,
24
34
  adapt: () => adapt,
25
35
  bridge: () => bridge,
26
36
  koaContextToWeb: () => koaContextToWeb,
@@ -33,10 +43,22 @@ __export(index_exports, {
33
43
  });
34
44
  module.exports = __toCommonJS(index_exports);
35
45
  var import_middlewares = require("@fonderie/core/middlewares");
36
- var import_workspaces = require("@fonderie/workspaces");
37
- var import_permissions = require("@fonderie/permissions");
38
- var import_billing = require("@fonderie/billing");
39
- var import_permissions2 = require("@fonderie/permissions");
46
+ var import_core = require("@fonderie/core");
47
+ async function loadOptionalPeer(load, pkg, api) {
48
+ try {
49
+ return await load();
50
+ } catch (err) {
51
+ const e = err;
52
+ const notFound = e?.code === "ERR_MODULE_NOT_FOUND" || e?.code === "MODULE_NOT_FOUND";
53
+ const missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? "")?.[1] : void 0;
54
+ if (missing === pkg || missing?.startsWith(pkg + "/")) {
55
+ throw new Error(
56
+ `[fonderie] ${api} requires the optional peer dependency "${pkg}". Install it: npm install ${pkg}`
57
+ );
58
+ }
59
+ throw err;
60
+ }
61
+ }
40
62
  function koaContextToWeb(ctx) {
41
63
  const encrypted = ctx.req.socket.encrypted;
42
64
  const protocol = encrypted ? "https" : "http";
@@ -89,13 +111,46 @@ function adapt(middleware) {
89
111
  }
90
112
  var requireAuth = adapt(import_middlewares.requireAuth);
91
113
  function withWorkspace(store) {
92
- return adapt((0, import_workspaces.withWorkspace)(store));
114
+ let inner;
115
+ return async (ctx, next) => {
116
+ if (!inner) {
117
+ const mod = await loadOptionalPeer(
118
+ () => import("@fonderie/workspaces"),
119
+ "@fonderie/workspaces",
120
+ "withWorkspace()"
121
+ );
122
+ inner = adapt(mod.withWorkspace(store));
123
+ }
124
+ return inner(ctx, next);
125
+ };
93
126
  }
94
127
  function requirePermission(operation, permissionKey) {
95
- return adapt((0, import_permissions.requirePermission)(operation, permissionKey));
128
+ let inner;
129
+ return async (ctx, next) => {
130
+ if (!inner) {
131
+ const mod = await loadOptionalPeer(
132
+ () => import("@fonderie/permissions"),
133
+ "@fonderie/permissions",
134
+ "requirePermission()"
135
+ );
136
+ inner = adapt(mod.requirePermission(operation, permissionKey));
137
+ }
138
+ return inner(ctx, next);
139
+ };
96
140
  }
97
141
  function requireFeature(key) {
98
- return adapt((0, import_billing.requireFeature)(key));
142
+ let inner;
143
+ return async (ctx, next) => {
144
+ if (!inner) {
145
+ const mod = await loadOptionalPeer(
146
+ () => import("@fonderie/billing"),
147
+ "@fonderie/billing",
148
+ "requireFeature()"
149
+ );
150
+ inner = adapt(mod.requireFeature(key));
151
+ }
152
+ return inner(ctx, next);
153
+ };
99
154
  }
100
155
  function mount(app, fonderie) {
101
156
  app.use(async (ctx, next) => {
@@ -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';\nimport { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport { requirePermission as _requirePermission } from '@fonderie/permissions';\nimport { requireFeature as _requireFeature } from '@fonderie/billing';\n\nexport { OPERATIONS } from '@fonderie/permissions';\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\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\treturn adapt(_withWorkspace(store));\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\treturn adapt(_requirePermission(operation, permissionKey));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function requireFeature(key: string): KoaMiddleware<any, any> {\n\treturn adapt(_requireFeature(key));\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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,yBAA4C;AAC5C,wBAAgD;AAChD,yBAAwD;AACxD,qBAAkD;AAElD,IAAAA,sBAA2B;AAwBpB,SAAS,gBAAgB,KAA0B;AACzD,QAAM,YAAa,IAAI,IAAI,OAAmC;AAC9D,QAAM,WAAW,YAAY,UAAU;AACvC,QAAM,OAAO,IAAI,Q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AAA,IACrB,CAAC;AAED,QAAI,WAAW;AACd,YAAM,KAAK;AAAA,IACZ,OAAO;AACN,YAAM,iBAAiB,QAAQ,GAA4B;AAAA,IAC5D;AAAA,EACD;AACD;AAWO,IAAM,cAAuC,MAAM,mBAAAC,WAAY;AAE/D,SAAS,cACf,OAE0B;AAC1B,SAAO,UAAM,kBAAAC,eAAe,KAAK,CAAC;AACnC;AAEO,SAAS,kBACf,WACA,eAE0B;AAC1B,SAAO,UAAM,mBAAAC,mBAAmB,WAAW,aAAa,CAAC;AAC1D;AAGO,SAAS,eAAe,KAAsC;AACpE,SAAO,UAAM,eAAAC,gBAAgB,GAAG,CAAC;AAClC;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":["import_permissions","_requireAuth","_withWorkspace","_requirePermission","_requireFeature"]}
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,yBAA4C;AAQ5C,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,W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AChC;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"]}
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { IncomingMessage } from 'node:http';
2
2
  import Koa from 'koa';
3
3
  import { Middleware, FonderieApp } from '@fonderie/core';
4
+ export { OPERATIONS } from '@fonderie/core';
4
5
  import { withWorkspace as withWorkspace$1 } from '@fonderie/workspaces';
5
6
  import { requirePermission as requirePermission$1 } from '@fonderie/permissions';
6
- export { OPERATIONS } from '@fonderie/permissions';
7
7
 
8
8
  type KoaMiddleware<S = any, C = any> = Koa.Middleware<S, C>;
9
9
 
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { IncomingMessage } from 'node:http';
2
2
  import Koa from 'koa';
3
3
  import { Middleware, FonderieApp } from '@fonderie/core';
4
+ export { OPERATIONS } from '@fonderie/core';
4
5
  import { withWorkspace as withWorkspace$1 } from '@fonderie/workspaces';
5
6
  import { requirePermission as requirePermission$1 } from '@fonderie/permissions';
6
- export { OPERATIONS } from '@fonderie/permissions';
7
7
 
8
8
  type KoaMiddleware<S = any, C = any> = Koa.Middleware<S, C>;
9
9
 
package/dist/index.js CHANGED
@@ -1,9 +1,21 @@
1
1
  // src/index.ts
2
2
  import { requireAuth as _requireAuth } from "@fonderie/core/middlewares";
3
- import { withWorkspace as _withWorkspace } from "@fonderie/workspaces";
4
- import { requirePermission as _requirePermission } from "@fonderie/permissions";
5
- import { requireFeature as _requireFeature } from "@fonderie/billing";
6
- import { OPERATIONS } from "@fonderie/permissions";
3
+ import { OPERATIONS } from "@fonderie/core";
4
+ async function loadOptionalPeer(load, pkg, api) {
5
+ try {
6
+ return await load();
7
+ } catch (err) {
8
+ const e = err;
9
+ const notFound = e?.code === "ERR_MODULE_NOT_FOUND" || e?.code === "MODULE_NOT_FOUND";
10
+ const missing = notFound ? /Cannot find (?:package|module) '([^']+)'/.exec(e?.message ?? "")?.[1] : void 0;
11
+ if (missing === pkg || missing?.startsWith(pkg + "/")) {
12
+ throw new Error(
13
+ `[fonderie] ${api} requires the optional peer dependency "${pkg}". Install it: npm install ${pkg}`
14
+ );
15
+ }
16
+ throw err;
17
+ }
18
+ }
7
19
  function koaContextToWeb(ctx) {
8
20
  const encrypted = ctx.req.socket.encrypted;
9
21
  const protocol = encrypted ? "https" : "http";
@@ -56,13 +68,46 @@ function adapt(middleware) {
56
68
  }
57
69
  var requireAuth = adapt(_requireAuth);
58
70
  function withWorkspace(store) {
59
- return adapt(_withWorkspace(store));
71
+ let inner;
72
+ return async (ctx, next) => {
73
+ if (!inner) {
74
+ const mod = await loadOptionalPeer(
75
+ () => import("@fonderie/workspaces"),
76
+ "@fonderie/workspaces",
77
+ "withWorkspace()"
78
+ );
79
+ inner = adapt(mod.withWorkspace(store));
80
+ }
81
+ return inner(ctx, next);
82
+ };
60
83
  }
61
84
  function requirePermission(operation, permissionKey) {
62
- return adapt(_requirePermission(operation, permissionKey));
85
+ let inner;
86
+ return async (ctx, next) => {
87
+ if (!inner) {
88
+ const mod = await loadOptionalPeer(
89
+ () => import("@fonderie/permissions"),
90
+ "@fonderie/permissions",
91
+ "requirePermission()"
92
+ );
93
+ inner = adapt(mod.requirePermission(operation, permissionKey));
94
+ }
95
+ return inner(ctx, next);
96
+ };
63
97
  }
64
98
  function requireFeature(key) {
65
- return adapt(_requireFeature(key));
99
+ let inner;
100
+ return async (ctx, next) => {
101
+ if (!inner) {
102
+ const mod = await loadOptionalPeer(
103
+ () => import("@fonderie/billing"),
104
+ "@fonderie/billing",
105
+ "requireFeature()"
106
+ );
107
+ inner = adapt(mod.requireFeature(key));
108
+ }
109
+ return inner(ctx, next);
110
+ };
66
111
  }
67
112
  function mount(app, fonderie) {
68
113
  app.use(async (ctx, next) => {
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';\nimport { withWorkspace as _withWorkspace } from '@fonderie/workspaces';\nimport { requirePermission as _requirePermission } from '@fonderie/permissions';\nimport { requireFeature as _requireFeature } from '@fonderie/billing';\n\nexport { OPERATIONS } from '@fonderie/permissions';\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\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\treturn adapt(_withWorkspace(store));\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\treturn adapt(_requirePermission(operation, permissionKey));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function requireFeature(key: string): KoaMiddleware<any, any> {\n\treturn adapt(_requireFeature(key));\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) {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,UAAM,SAAS,gBAAgB,GAA4B;AAC3D,QAAI,MAAM,WAAW,IAAI,MAAM,SAAS,aAAa,OAAO,MAAM,CAAC;AACnE,UAAM,KAAK;AAAA,EACZ;AACD;AASO,SAAS,MAAM,YAAiD;AACtE,SAAO,OAAO,KAAK,SAAS;AAC3B,UAAM,OAAQ,IAAI,MAAkC,WAAW;AAG/D,QAAI,CAAC,KAAM,OAAM,IAAI,MAAM,uDAAuD;AAElF,QAAI,YAAY;AAChB,UAAM,SAAS,MAAM,WAAW,MAAM,YAAY;AACjD,kBAAY;AACZ,aAAO,IAAI,SAAS;AAAA,IACrB,CAAC;AAED,QAAI,WAAW;AACd,YAAM,KAAK;AAAA,IACZ,OAAO;AACN,YAAM,iBAAiB,QAAQ,GAA4B;AAAA,IAC5D;AAAA,EACD;AACD;AAWO,IAAM,cAAuC,MAAM,YAAY;AAE/D,SAAS,cACf,OAE0B;AAC1B,SAAO,MAAM,eAAe,KAAK,CAAC;AACnC;AAEO,SAAS,kBACf,WACA,eAE0B;AAC1B,SAAO,MAAM,mBAAmB,WAAW,aAAa,CAAC;AAC1D;AAGO,SAAS,eAAe,KAAsC;AACpE,SAAO,MAAM,gBAAgB,GAAG,CAAC;AAClC;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 } 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,eAAe,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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":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fonderie/adapter-koa",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Koa adapter for fonderie-js — bridge(), adapt(), mount() to use fonderie middleware in native Koa routes.",
5
5
  "keywords": [
6
6
  "fonderie-js",
@@ -35,10 +35,10 @@
35
35
  "check": "biome check --write src"
36
36
  },
37
37
  "peerDependencies": {
38
- "@fonderie/core": "^0.1.0",
39
- "@fonderie/workspaces": "^1.0.0",
40
- "@fonderie/permissions": "^1.0.0",
41
- "@fonderie/billing": "^1.0.0",
38
+ "@fonderie/core": "^0.1.1",
39
+ "@fonderie/workspaces": "^1.0.1",
40
+ "@fonderie/permissions": "^1.0.1",
41
+ "@fonderie/billing": "^1.0.1",
42
42
  "koa": "^2.0.0"
43
43
  },
44
44
  "peerDependenciesMeta": {