@entifix/service-shell 0.10.2 → 0.12.0

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.
Files changed (103) hide show
  1. package/README.md +1 -4
  2. package/dist/auth/index.d.ts +1 -0
  3. package/dist/auth/index.d.ts.map +1 -1
  4. package/dist/auth/index.js +1 -0
  5. package/dist/auth/index.js.map +1 -1
  6. package/dist/auth/require-organization.d.ts +1 -1
  7. package/dist/auth/require-organization.d.ts.map +1 -1
  8. package/dist/auth/require-organization.js.map +1 -1
  9. package/dist/auth/require-principal.d.ts +9 -49
  10. package/dist/auth/require-principal.d.ts.map +1 -1
  11. package/dist/auth/require-principal.js +21 -15
  12. package/dist/auth/require-principal.js.map +1 -1
  13. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  14. package/dist/auth/require-service-crossing.js +3 -13
  15. package/dist/auth/require-service-crossing.js.map +1 -1
  16. package/dist/auth/shared-token.d.ts +2 -0
  17. package/dist/auth/shared-token.d.ts.map +1 -1
  18. package/dist/auth/shared-token.js +2 -2
  19. package/dist/auth/shared-token.js.map +1 -1
  20. package/dist/auth/verified-context.d.ts +24 -0
  21. package/dist/auth/verified-context.d.ts.map +1 -0
  22. package/dist/auth/verified-context.js +40 -0
  23. package/dist/auth/verified-context.js.map +1 -0
  24. package/dist/entity-facet-routes.d.ts +7 -1
  25. package/dist/entity-facet-routes.d.ts.map +1 -1
  26. package/dist/entity-facet-routes.js +8 -5
  27. package/dist/entity-facet-routes.js.map +1 -1
  28. package/dist/entity-metadata-route.d.ts +2 -1
  29. package/dist/entity-metadata-route.d.ts.map +1 -1
  30. package/dist/entity-metadata-route.js +20 -3
  31. package/dist/entity-metadata-route.js.map +1 -1
  32. package/dist/entity-route-guard.d.ts +5 -3
  33. package/dist/entity-route-guard.d.ts.map +1 -1
  34. package/dist/entity-route-guard.js +12 -6
  35. package/dist/entity-route-guard.js.map +1 -1
  36. package/dist/entity-routes.d.ts +13 -1
  37. package/dist/entity-routes.d.ts.map +1 -1
  38. package/dist/entity-routes.js +20 -6
  39. package/dist/entity-routes.js.map +1 -1
  40. package/dist/http-api/build-api.d.ts +78 -0
  41. package/dist/http-api/build-api.d.ts.map +1 -0
  42. package/dist/http-api/build-api.js +189 -0
  43. package/dist/http-api/build-api.js.map +1 -0
  44. package/dist/http-api/entity-api.d.ts +69 -0
  45. package/dist/http-api/entity-api.d.ts.map +1 -0
  46. package/dist/http-api/entity-api.js +522 -0
  47. package/dist/http-api/entity-api.js.map +1 -0
  48. package/dist/http-api/guards.d.ts +92 -0
  49. package/dist/http-api/guards.d.ts.map +1 -0
  50. package/dist/http-api/guards.js +131 -0
  51. package/dist/http-api/guards.js.map +1 -0
  52. package/dist/http-api/index.d.ts +6 -0
  53. package/dist/http-api/index.d.ts.map +1 -0
  54. package/dist/http-api/index.js +7 -0
  55. package/dist/http-api/index.js.map +1 -0
  56. package/dist/http-api/problem-codec.d.ts +14 -0
  57. package/dist/http-api/problem-codec.d.ts.map +1 -0
  58. package/dist/http-api/problem-codec.js +26 -0
  59. package/dist/http-api/problem-codec.js.map +1 -0
  60. package/dist/http-api/service-group.d.ts +74 -0
  61. package/dist/http-api/service-group.d.ts.map +1 -0
  62. package/dist/http-api/service-group.js +168 -0
  63. package/dist/http-api/service-group.js.map +1 -0
  64. package/dist/idempotency.d.ts +64 -0
  65. package/dist/idempotency.d.ts.map +1 -0
  66. package/dist/idempotency.js +112 -0
  67. package/dist/idempotency.js.map +1 -0
  68. package/dist/index.d.ts +4 -2
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/index.js.map +1 -1
  72. package/dist/make-service.d.ts +39 -6
  73. package/dist/make-service.d.ts.map +1 -1
  74. package/dist/make-service.js +54 -16
  75. package/dist/make-service.js.map +1 -1
  76. package/dist/metadata-composition.d.ts +28 -0
  77. package/dist/metadata-composition.d.ts.map +1 -0
  78. package/dist/metadata-composition.js +68 -0
  79. package/dist/metadata-composition.js.map +1 -0
  80. package/dist/narrowing.d.ts +13 -0
  81. package/dist/narrowing.d.ts.map +1 -0
  82. package/dist/narrowing.js +34 -0
  83. package/dist/narrowing.js.map +1 -0
  84. package/dist/respond.d.ts +6 -4
  85. package/dist/respond.d.ts.map +1 -1
  86. package/dist/respond.js +11 -7
  87. package/dist/respond.js.map +1 -1
  88. package/dist/serve-test-service.d.ts +2 -1
  89. package/dist/serve-test-service.d.ts.map +1 -1
  90. package/dist/serve-test-service.js.map +1 -1
  91. package/dist/sse.d.ts +7 -4
  92. package/dist/sse.d.ts.map +1 -1
  93. package/dist/sse.js +21 -5
  94. package/dist/sse.js.map +1 -1
  95. package/package.json +7 -6
  96. package/dist/health-routes.d.ts +0 -24
  97. package/dist/health-routes.d.ts.map +0 -1
  98. package/dist/health-routes.js +0 -86
  99. package/dist/health-routes.js.map +0 -1
  100. package/dist/service-description-route.d.ts +0 -66
  101. package/dist/service-description-route.d.ts.map +0 -1
  102. package/dist/service-description-route.js +0 -60
  103. package/dist/service-description-route.js.map +0 -1
@@ -4,6 +4,7 @@ import { envelopeEntityName, makeEntityFacetsEnvelope, parseFacetQueryParams } f
4
4
  import { Effect } from 'effect';
5
5
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
6
6
  import { guardRoute } from './entity-route-guard.js';
7
+ import { narrowingFor } from './narrowing.js';
7
8
  import { defaultFailurePolicy, respond } from './respond.js';
8
9
  import { legacyAnswer } from './route-responses.js';
9
10
  /**
@@ -30,19 +31,21 @@ import { legacyAnswer } from './route-responses.js';
30
31
  catch: (error)=>error
31
32
  });
32
33
  });
33
- const scoped = (queries, scope)=>scope === 'all' || scope === 'none' ? queries : queries.map((query)=>{
34
+ const narrowed = (queries, narrowing)=>narrowing === 'unscoped' ? queries : queries.map((query)=>{
34
35
  var _query_filtering;
35
36
  return _extends({}, query, {
36
37
  filtering: [
37
38
  ...(_query_filtering = query.filtering) != null ? _query_filtering : [],
38
- scope.filter
39
+ narrowing
39
40
  ]
40
41
  });
41
42
  });
43
+ if (options.narrowing !== undefined && options.scope !== undefined) throw new Error(`the facet route for '${envelopeEntityName(entityConstructor)}' names both ` + '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.');
44
+ /** A scope, as the narrowing this route applies. */ const asNarrowing = (scope)=>scope === 'all' ? 'unscoped' : scope === 'none' ? 'nothing' : scope.filter;
42
45
  const count = (context)=>Effect.gen(function*() {
43
46
  const queries = yield* readQueries;
44
- const scope = options.scope ? yield* options.scope(context) : 'all';
45
- if (scope === 'none') {
47
+ const narrowing = options.narrowing !== undefined && context.verified !== undefined ? narrowingFor(options.narrowing, context.verified) : asNarrowing(options.scope ? yield* options.scope(context) : 'all');
48
+ if (narrowing === 'nothing') {
46
49
  // Still parsed: whether a query is well-formed must not depend on who
47
50
  // asked.
48
51
  const empty = Object.fromEntries(queries.map(({ member })=>[
@@ -55,7 +58,7 @@ import { legacyAnswer } from './route-responses.js';
55
58
  const counter = yield* factory.for(entityConstructor, _extends({}, context.organizationId === undefined ? {} : {
56
59
  organizationId: context.organizationId
57
60
  }));
58
- const counts = yield* facetCountsUCFactory(scoped(queries, scope)).pipe(Effect.provideService(EntityFacetCounterTag, counter));
61
+ const counts = yield* facetCountsUCFactory(narrowed(queries, narrowing)).pipe(Effect.provideService(EntityFacetCounterTag, counter));
59
62
  return yield* HttpServerResponse.json(makeEntityFacetsEnvelope(entityConstructor, counts));
60
63
  }).pipe(Effect.catch(legacyAnswer('invalidQuery')));
61
64
  const handler = respond(guardRoute(entityConstructor, options.guard, 'read', count), (_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity-facet-routes.ts"],"sourcesContent":["import {\n EntityFacetCounterFactoryTag,\n EntityFacetCounterTag,\n facetCountsUCFactory,\n} from '@entifix/business';\nimport type { EntifixFailure } from '@entifix/core';\nimport {\n EntifixBuildError,\n type Entity,\n type EntityConstructor,\n type EntityFacetCounts,\n type EntityFacetQuery,\n envelopeEntityName,\n makeEntityFacetsEnvelope,\n parseFacetQueryParams,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport { legacyAnswer } from './route-responses.js';\n\nexport interface EntityFacetRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n /** Who may count: the guard the entity's `list` has, as a rule. */\n readonly guard: G;\n /** Defaults to `/api/<entity key>`; the route is `<basePath>/$facets`. */\n readonly basePath?: `/${string}`;\n /**\n * Narrows the counts to the records this caller may see — the same scope\n * the entity's `list` takes, so a count never reveals a record the list\n * would not.\n */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /** How the count's failures are answered and logged. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * `GET <base>/$facets` — how many of the entity's records hold each value of\n * each `facet` member, each under its own `rsql.<member>` filtering — bound to\n * storage through the host's {@link EntityFacetCounterFactoryTag}.\n *\n * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it\n * is the one route set that requires a counter: a host that mounts it without\n * binding one fails to compile, and a host that never counts binds nothing.\n *\n * The query is parsed against the entity's metadata, so only a `filterable`\n * member is counted and every malformed request is a `400`. A scope is\n * **conjoined into every facet's filtering**, never substituted, so no query\n * string can count past it; `'none'` answers every member empty.\n */\nexport const makeEntityFacetRoutes = <\n T extends Entity,\n R = never,\n // `never` for the reason `makeEntityRoutes` gives: a caller naming `R`\n // explicitly must not widen the guard to every kind there is.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityFacetRoutesOptions<T, R, G>,\n) => {\n const base: `/${string}` =\n options.basePath ?? `/api/${envelopeEntityName(entityConstructor)}`;\n\n const readQueries = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () => parseFacetQueryParams(entityConstructor, search),\n catch: error => error as EntifixBuildError,\n });\n });\n\n const scoped = (\n queries: EntityFacetQuery<T>[],\n scope: EntityReadScope<T>,\n ): EntityFacetQuery<T>[] =>\n scope === 'all' || scope === 'none'\n ? queries\n : queries.map(query => ({\n ...query,\n filtering: [...(query.filtering ?? []), scope.filter],\n }));\n\n const count = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const queries = yield* readQueries;\n const scope = options.scope\n ? yield* options.scope(context)\n : ('all' as const);\n if (scope === 'none') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked.\n const empty: EntityFacetCounts = Object.fromEntries(\n queries.map(({ member }) => [member, []]),\n );\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, empty),\n );\n }\n const factory = yield* EntityFacetCounterFactoryTag;\n const counter = yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n const counts = yield* facetCountsUCFactory<T>(\n scoped(queries, scope),\n ).pipe(Effect.provideService(EntityFacetCounterTag, counter));\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, counts),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const handler = respond(\n guardRoute(\n entityConstructor,\n options.guard,\n 'read',\n count,\n ) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n EntifixFailure,\n | R\n | EntityFacetCounterFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >,\n options.policy ?? defaultFailurePolicy,\n );\n\n return HttpRouter.addAll([\n HttpRouter.route('GET', `${base}/$facets`, handler),\n ]);\n};\n"],"names":["EntityFacetCounterFactoryTag","EntityFacetCounterTag","facetCountsUCFactory","envelopeEntityName","makeEntityFacetsEnvelope","parseFacetQueryParams","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","guardRoute","defaultFailurePolicy","respond","legacyAnswer","makeEntityFacetRoutes","entityConstructor","options","base","basePath","readQueries","gen","request","search","URL","url","searchParams","try","catch","error","scoped","queries","scope","map","query","filtering","filter","count","context","empty","Object","fromEntries","member","json","factory","counter","for","organizationId","undefined","counts","pipe","provideService","handler","guard","policy","addAll","route"],"mappings":";AAAA,SACEA,4BAA4B,EAC5BC,qBAAqB,EACrBC,oBAAoB,QACf,oBAAoB;AAE3B,SAMEC,kBAAkB,EAClBC,wBAAwB,EACxBC,qBAAqB,QAChB,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,UAAU,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEhF,SAIEC,UAAU,QAEL,0BAA0B;AACjC,SACEC,oBAAoB,EAEpBC,OAAO,QACF,eAAe;AACtB,SAASC,YAAY,QAAQ,uBAAuB;AAuBpD;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,wBAAwB,CAOnCC,mBACAC;QAGEA,mBAmEAA;IApEF,MAAMC,QACJD,oBAAAA,QAAQE,QAAQ,YAAhBF,oBAAoB,CAAC,KAAK,EAAEb,mBAAmBY,oBAAoB;IAErE,MAAMI,cAAcb,OAAOc,GAAG,CAAC;QAC7B,MAAMC,UAAU,OAAOb,kBAAkBA,iBAAiB;QAC1D,MAAMc,SAAS,IAAIC,IAAIF,QAAQG,GAAG,EAAE,oBAAoBC,YAAY;QACpE,OAAO,OAAOnB,OAAOoB,GAAG,CAAC;YACvBA,KAAK,IAAMrB,sBAAsBU,mBAAmBO;YACpDK,OAAOC,CAAAA,QAASA;QAClB;IACF;IAEA,MAAMC,SAAS,CACbC,SACAC,QAEAA,UAAU,SAASA,UAAU,SACzBD,UACAA,QAAQE,GAAG,CAACC,CAAAA;gBAEMA;mBAFI,aACjBA;gBACHC,WAAW;wBAAKD,mBAAAA,MAAMC,SAAS,YAAfD,mBAAmB,EAAE;oBAAGF,MAAMI,MAAM;iBAAC;;;IAG7D,MAAMC,QAAQ,CAACC,UACb/B,OAAOc,GAAG,CAAC;YACT,MAAMU,UAAU,OAAOX;YACvB,MAAMY,QAAQf,QAAQe,KAAK,GACvB,OAAOf,QAAQe,KAAK,CAACM,WACpB;YACL,IAAIN,UAAU,QAAQ;gBACpB,sEAAsE;gBACtE,SAAS;gBACT,MAAMO,QAA2BC,OAAOC,WAAW,CACjDV,QAAQE,GAAG,CAAC,CAAC,EAAES,MAAM,EAAE,GAAK;wBAACA;wBAAQ,EAAE;qBAAC;gBAE1C,OAAO,OAAOhC,mBAAmBiC,IAAI,CACnCtC,yBAAyBW,mBAAmBuB;YAEhD;YACA,MAAMK,UAAU,OAAO3C;YACvB,MAAM4C,UAAU,OAAOD,QAAQE,GAAG,CAAC9B,mBAAmB,aAChDsB,QAAQS,cAAc,KAAKC,YAC3B,CAAC,IACD;gBAAED,gBAAgBT,QAAQS,cAAc;YAAC;YAE/C,MAAME,SAAS,OAAO9C,qBACpB2B,OAAOC,SAASC,QAChBkB,IAAI,CAAC3C,OAAO4C,cAAc,CAACjD,uBAAuB2C;YACpD,OAAO,OAAOnC,mBAAmBiC,IAAI,CACnCtC,yBAAyBW,mBAAmBiC;QAEhD,GAAGC,IAAI,CAAC3C,OAAOqB,KAAK,CAACd,aAAa;IAEpC,MAAMsC,UAAUvC,QACdF,WACEK,mBACAC,QAAQoC,KAAK,EACb,QACAhB,SAUFpB,kBAAAA,QAAQqC,MAAM,YAAdrC,kBAAkBL;IAGpB,OAAOJ,WAAW+C,MAAM,CAAC;QACvB/C,WAAWgD,KAAK,CAAC,OAAO,GAAGtC,KAAK,QAAQ,CAAC,EAAEkC;KAC5C;AACH,EAAE"}
1
+ {"version":3,"sources":["../src/entity-facet-routes.ts"],"sourcesContent":["import type { Narrowing, NarrowingRules } from '@entifix/business';\nimport {\n EntityFacetCounterFactoryTag,\n EntityFacetCounterTag,\n facetCountsUCFactory,\n} from '@entifix/business';\nimport type { EntifixFailure } from '@entifix/core';\nimport {\n EntifixBuildError,\n type Entity,\n type EntityConstructor,\n type EntityFacetCounts,\n type EntityFacetQuery,\n envelopeEntityName,\n makeEntityFacetsEnvelope,\n parseFacetQueryParams,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport { narrowingFor } from './narrowing.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport { legacyAnswer } from './route-responses.js';\n\nexport interface EntityFacetRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n /** Who may count: the guard the entity's `list` has, as a rule. */\n readonly guard: G;\n /** Defaults to `/api/<entity key>`; the route is `<basePath>/$facets`. */\n readonly basePath?: `/${string}`;\n /**\n * Narrows the counts to the records this caller may see — the same scope\n * the entity's `list` takes, so a count never reveals a record the list\n * would not.\n */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /**\n * The same narrowing the entity's `list` takes, as resolver rules — so a\n * count equals the narrowed list. Replaces `scope`; naming both throws.\n */\n readonly narrowing?: NarrowingRules<T>;\n /** How the count's failures are answered and logged. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * `GET <base>/$facets` — how many of the entity's records hold each value of\n * each `facet` member, each under its own `rsql.<member>` filtering — bound to\n * storage through the host's {@link EntityFacetCounterFactoryTag}.\n *\n * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it\n * is the one route set that requires a counter: a host that mounts it without\n * binding one fails to compile, and a host that never counts binds nothing.\n *\n * The query is parsed against the entity's metadata, so only a `filterable`\n * member is counted and every malformed request is a `400`. A scope is\n * **conjoined into every facet's filtering**, never substituted, so no query\n * string can count past it; `'none'` answers every member empty.\n */\nexport const makeEntityFacetRoutes = <\n T extends Entity,\n R = never,\n // `never` for the reason `makeEntityRoutes` gives: a caller naming `R`\n // explicitly must not widen the guard to every kind there is.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityFacetRoutesOptions<T, R, G>,\n) => {\n const base: `/${string}` =\n options.basePath ?? `/api/${envelopeEntityName(entityConstructor)}`;\n\n const readQueries = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () => parseFacetQueryParams(entityConstructor, search),\n catch: error => error as EntifixBuildError,\n });\n });\n\n const narrowed = (\n queries: EntityFacetQuery<T>[],\n narrowing: Exclude<Narrowing<T>, 'nothing'>,\n ): EntityFacetQuery<T>[] =>\n narrowing === 'unscoped'\n ? queries\n : queries.map(query => ({\n ...query,\n filtering: [...(query.filtering ?? []), narrowing],\n }));\n\n if (options.narrowing !== undefined && options.scope !== undefined)\n throw new Error(\n `the facet route for '${envelopeEntityName(entityConstructor)}' names both ` +\n '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.',\n );\n\n /** A scope, as the narrowing this route applies. */\n const asNarrowing = (scope: EntityReadScope<T>): Narrowing<T> =>\n scope === 'all' ? 'unscoped' : scope === 'none' ? 'nothing' : scope.filter;\n\n const count = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const queries = yield* readQueries;\n const narrowing =\n options.narrowing !== undefined && context.verified !== undefined\n ? narrowingFor(options.narrowing, context.verified)\n : asNarrowing(\n options.scope ? yield* options.scope(context) : ('all' as const),\n );\n if (narrowing === 'nothing') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked.\n const empty: EntityFacetCounts = Object.fromEntries(\n queries.map(({ member }) => [member, []]),\n );\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, empty),\n );\n }\n const factory = yield* EntityFacetCounterFactoryTag;\n const counter = yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n const counts = yield* facetCountsUCFactory<T>(\n narrowed(queries, narrowing),\n ).pipe(Effect.provideService(EntityFacetCounterTag, counter));\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, counts),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const handler = respond(\n guardRoute(\n entityConstructor,\n options.guard,\n 'read',\n count,\n ) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n EntifixFailure,\n | R\n | EntityFacetCounterFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >,\n options.policy ?? defaultFailurePolicy,\n );\n\n return HttpRouter.addAll([\n HttpRouter.route('GET', `${base}/$facets`, handler),\n ]);\n};\n"],"names":["EntityFacetCounterFactoryTag","EntityFacetCounterTag","facetCountsUCFactory","envelopeEntityName","makeEntityFacetsEnvelope","parseFacetQueryParams","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","guardRoute","narrowingFor","defaultFailurePolicy","respond","legacyAnswer","makeEntityFacetRoutes","entityConstructor","options","base","basePath","readQueries","gen","request","search","URL","url","searchParams","try","catch","error","narrowed","queries","narrowing","map","query","filtering","undefined","scope","Error","asNarrowing","filter","count","context","verified","empty","Object","fromEntries","member","json","factory","counter","for","organizationId","counts","pipe","provideService","handler","guard","policy","addAll","route"],"mappings":";AACA,SACEA,4BAA4B,EAC5BC,qBAAqB,EACrBC,oBAAoB,QACf,oBAAoB;AAE3B,SAMEC,kBAAkB,EAClBC,wBAAwB,EACxBC,qBAAqB,QAChB,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,UAAU,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEhF,SAIEC,UAAU,QAEL,0BAA0B;AACjC,SAASC,YAAY,QAAQ,iBAAiB;AAC9C,SACEC,oBAAoB,EAEpBC,OAAO,QACF,eA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gBAC3B,sEAAsE;gBACtE,SAAS;gBACT,MAAMY,QAA2BC,OAAOC,WAAW,CACjDf,QAAQE,GAAG,CAAC,CAAC,EAAEc,MAAM,EAAE,GAAK;wBAACA;wBAAQ,EAAE;qBAAC;gBAE1C,OAAO,OAAOtC,mBAAmBuC,IAAI,CACnC5C,yBAAyBY,mBAAmB4B;YAEhD;YACA,MAAMK,UAAU,OAAOjD;YACvB,MAAMkD,UAAU,OAAOD,QAAQE,GAAG,CAACnC,mBAAmB,aAChD0B,QAAQU,cAAc,KAAKhB,YAC3B,CAAC,IACD;gBAAEgB,gBAAgBV,QAAQU,cAAc;YAAC;YAE/C,MAAMC,SAAS,OAAOnD,qBACpB4B,SAASC,SAASC,YAClBsB,IAAI,CAAChD,OAAOiD,cAAc,CAACtD,uBAAuBiD;YACpD,OAAO,OAAOzC,mBAAmBuC,IAAI,CACnC5C,yBAAyBY,mBAAmBqC;QAEhD,GAAGC,IAAI,CAAChD,OAAOsB,KAAK,CAACd,aAAa;IAEpC,MAAM0C,UAAU3C,QACdH,WACEM,mBACAC,QAAQwC,KAAK,EACb,QACAhB,SAUFxB,kBAAAA,QAAQyC,MAAM,YAAdzC,kBAAkBL;IAGpB,OAAOL,WAAWoD,MAAM,CAAC;QACvBpD,WAAWqD,KAAK,CAAC,OAAO,GAAG1C,KAAK,QAAQ,CAAC,EAAEsC;KAC5C;AACH,EAAE"}
@@ -2,6 +2,7 @@ import { PolicyDecisionTag } from '@entifix/authz';
2
2
  import { type Entity, type EntityConstructor } from '@entifix/core';
3
3
  import { Effect } from 'effect';
4
4
  import { HttpServerRequest, HttpServerResponse } from 'effect/http';
5
+ import { type MetadataCompositions } from './metadata-composition.js';
5
6
  /**
6
7
  * `GET /api/<entity>/$metadata` — what this caller may do with one entity.
7
8
  *
@@ -20,5 +21,5 @@ import { HttpServerRequest, HttpServerResponse } from 'effect/http';
20
21
  * database handle here would leave a vendor with no active organization unable
21
22
  * to see their own affordances.
22
23
  */
23
- export declare const entityMetadataRoute: <TEntity extends Entity>(entityConstructor: EntityConstructor<TEntity>) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, import("@entifix/business").TokenServiceTag | PolicyDecisionTag | HttpServerRequest.HttpServerRequest>;
24
+ export declare const entityMetadataRoute: <TEntity extends Entity>(entityConstructor: EntityConstructor<TEntity>, compositions?: MetadataCompositions) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, import("@entifix/business").TokenServiceTag | PolicyDecisionTag | HttpServerRequest.HttpServerRequest>;
24
25
  //# sourceMappingURL=entity-metadata-route.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entity-metadata-route.d.ts","sourceRoot":"","sources":["../src/entity-metadata-route.ts"],"names":[],"mappings":"AAEA,OAAO,EAKL,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,KAAK,MAAM,EAEX,KAAK,iBAAiB,EAKvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKpE;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB,GAAI,OAAO,SAAS,MAAM,EACxD,mBAAmB,iBAAiB,CAAC,OAAO,CAAC,uKA6D5C,CAAC"}
1
+ {"version":3,"file":"entity-metadata-route.d.ts","sourceRoot":"","sources":["../src/entity-metadata-route.ts"],"names":[],"mappings":"AAEA,OAAO,EAKL,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,KAAK,MAAM,EAEX,KAAK,iBAAiB,EAKvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGpE,OAAO,EAGL,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AAGnC;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB,GAAI,OAAO,SAAS,MAAM,EACxD,mBAAmB,iBAAiB,CAAC,OAAO,CAAC,EAC7C,eAAc,oBAAyB,uKAqFxC,CAAC"}
@@ -1,9 +1,11 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  import { createHash } from 'node:crypto';
2
3
  import { parsePermission, permissionForEntity, permissionForUseCase, PolicyDecisionTag } from '@entifix/authz';
3
4
  import { describeEntityUseCases, ENTITY_ACTIONS, extractMetaEntity, makeEntityMetadataEnvelope, NotFound } from '@entifix/core';
4
5
  import { Effect } from 'effect';
5
6
  import { HttpServerRequest, HttpServerResponse } from 'effect/http';
6
- import { requirePrincipal } from './auth/index.js';
7
+ import { requirePrincipal, withVerifiedContext } from './auth/index.js';
8
+ import { assertCompositionsDeclared, compositionFor } from './metadata-composition.js';
7
9
  import { respond } from './respond.js';
8
10
  /**
9
11
  * `GET /api/<entity>/$metadata` — what this caller may do with one entity.
@@ -22,7 +24,9 @@ import { respond } from './respond.js';
22
24
  * service: the document describes the model, not tenant data, and resolving a
23
25
  * database handle here would leave a vendor with no active organization unable
24
26
  * to see their own affordances.
25
- */ export const entityMetadataRoute = (entityConstructor)=>respond(requirePrincipal((principal)=>Effect.gen(function*() {
27
+ */ export const entityMetadataRoute = (entityConstructor, compositions = {})=>{
28
+ assertCompositionsDeclared(describeEntityUseCases(entityConstructor), compositions);
29
+ return respond(requirePrincipal((principal)=>Effect.gen(function*() {
26
30
  const policy = yield* PolicyDecisionTag;
27
31
  const allows = (permission)=>{
28
32
  const { resource, action } = parsePermission(permission);
@@ -45,7 +49,19 @@ import { respond } from './respond.js';
45
49
  }
46
50
  const document = {
47
51
  actions: ENTITY_ACTIONS.filter((action)=>allows(permissionForEntity(entityConstructor, action))),
48
- useCases: describeEntityUseCases(entityConstructor).filter((descriptor)=>allows(permissionForUseCase(entityConstructor, descriptor.key)))
52
+ useCases: yield* withVerifiedContext(principal, (verified)=>Effect.succeed(describeEntityUseCases(entityConstructor).filter((descriptor)=>allows(permissionForUseCase(entityConstructor, descriptor.key)))// A verb the caller resolves to nothing is omitted, like one
53
+ // they may not invoke; the rest carry what they resolve to.
54
+ .flatMap((descriptor)=>{
55
+ const composition = compositionFor(descriptor, verified, compositions);
56
+ if (composition === 'unreachable') return [];
57
+ return composition === undefined ? [
58
+ descriptor
59
+ ] : [
60
+ _extends({}, descriptor, {
61
+ composition
62
+ })
63
+ ];
64
+ })))
49
65
  };
50
66
  // The ETag hashes the *computed* document, not the descriptor set the
51
67
  // deployment declares. Two principals with different grants get different
@@ -68,6 +84,7 @@ import { respond } from './respond.js';
68
84
  headers: cacheHeaders(etag)
69
85
  });
70
86
  })));
87
+ };
71
88
  /**
72
89
  * The response varies by principal, so it must never land in a shared cache.
73
90
  * `Vary` names **both** credential carriers because the shell reads the access
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity-metadata-route.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport {\n parsePermission,\n type Permission,\n permissionForEntity,\n permissionForUseCase,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport {\n describeEntityUseCases,\n type Entity,\n ENTITY_ACTIONS,\n type EntityConstructor,\n type EntityMetadataDocument,\n extractMetaEntity,\n makeEntityMetadataEnvelope,\n NotFound,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { requirePrincipal } from './auth/index.js';\nimport { respond } from './respond.js';\n\n/**\n * `GET /api/<entity>/$metadata` — what this caller may do with one entity.\n *\n * Mounted **per entity, at a literal path**, not as a `/api/:entity/$metadata`\n * wildcard. `HttpRouter` resolves through `find-my-way-ts`, where a static\n * segment beats a parametric one and there is no backtracking once the\n * parametric branch has matched: alongside an existing `/api/<entity>/:id`, a\n * wildcard `$metadata` route never runs at all — the by-id handler wins with\n * `id === \"$metadata\"`, misses, and answers its own `404`. The endpoint would\n * read as \"this entity has no metadata\" while appearing mounted. A literal wins\n * regardless of registration order, which is why the base exports a route for\n * one entity and each service registers it for each of its own.\n *\n * Deliberately **not** behind `requireOrganization`, even on a tenant-plane\n * service: the document describes the model, not tenant data, and resolving a\n * database handle here would leave a vendor with no active organization unable\n * to see their own affordances.\n */\nexport const entityMetadataRoute = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n) =>\n respond(\n requirePrincipal(principal =>\n Effect.gen(function* () {\n const policy = yield* PolicyDecisionTag;\n const allows = (permission: Permission): boolean => {\n const { resource, action } = parsePermission(permission);\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\n };\n\n // SECURITY BOUNDARY. The document names domains, entity keys and verbs —\n // it is a map of the model — so an entity the caller may not read answers\n // exactly as one this service does not host. A `403` here would make the\n // endpoint an oracle: walk it and learn the shape of everything you are\n // not allowed to see. Same category as `redactConfiguration`, not\n // diagnostics polish.\n if (!allows(permissionForEntity(entityConstructor, 'read'))) {\n return yield* notFound(entityConstructor);\n }\n\n const document: EntityMetadataDocument = {\n actions: ENTITY_ACTIONS.filter(action =>\n allows(permissionForEntity(entityConstructor, action)),\n ),\n useCases: describeEntityUseCases(entityConstructor).filter(\n descriptor =>\n allows(permissionForUseCase(entityConstructor, descriptor.key)),\n ),\n };\n\n // The ETag hashes the *computed* document, not the descriptor set the\n // deployment declares. Two principals with different grants get different\n // documents from the same model, so a hash of the model would `304` one\n // caller onto another's affordances. Hashing the permission set instead\n // would read `ROLE_PERMISSIONS` directly and go around `PolicyDecisionTag`,\n // so an injected ABAC policy could change affordances without changing the\n // tag. Computing first costs a metadata read and a handful of pure\n // `decide` calls — no IO.\n const body = JSON.stringify(\n makeEntityMetadataEnvelope(entityConstructor, document),\n );\n const etag = `\"${createHash('sha256').update(body).digest('hex')}\"`;\n\n const request = yield* HttpServerRequest.HttpServerRequest;\n if (request.headers['if-none-match'] === etag) {\n return HttpServerResponse.empty({ status: 304 }).pipe(\n HttpServerResponse.setHeaders(cacheHeaders(etag)),\n );\n }\n\n return HttpServerResponse.text(body, {\n contentType: 'application/json',\n headers: cacheHeaders(etag),\n });\n }),\n ),\n );\n\n/**\n * The response varies by principal, so it must never land in a shared cache.\n * `Vary` names **both** credential carriers because the shell reads the access\n * token from the `entifix_at` cookie *or* an `Authorization: Bearer` header, and a\n * cache keyed on only one of them would serve across the other.\n */\nconst cacheHeaders = (etag: string) => ({\n etag,\n 'cache-control': 'private, no-cache',\n vary: 'Cookie, Authorization',\n});\n\n/** Indistinguishable from the `404` a service gives for an entity it does not host. */\nconst notFound = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n) =>\n Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n"],"names":["createHash","parsePermission","permissionForEntity","permissionForUseCase","PolicyDecisionTag","describeEntityUseCases","ENTITY_ACTIONS","extractMetaEntity","makeEntityMetadataEnvelope","NotFound","Effect","HttpServerRequest","HttpServerResponse","requirePrincipal","respond","entityMetadataRoute","entityConstructor","principal","gen","policy","allows","permission","resource","action","decide","subject","roles","notFound","document","actions","filter","useCases","descriptor","key","body","JSON","stringify","etag","update","digest","request","headers","empty","status","pipe","setHeaders","cacheHeaders","text","contentType","vary","fail","entity"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SACEC,eAAe,EAEfC,mBAAmB,EACnBC,oBAAoB,EACpBC,iBAAiB,QACZ,iBAAiB;AACxB,SACEC,sBAAsB,EAEtBC,cAAc,EAGdC,iBAAiB,EACjBC,0BAA0B,EAC1BC,QAAQ,QACH,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEpE,SAASC,gBAAgB,QAAQ,kBAAkB;AACnD,SAASC,OAAO,QAAQ,eAAe;AAEvC;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC,sBAAsB,CACjCC,oBAEAF,QACED,iBAAiBI,CAAAA,YACfP,OAAOQ,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AEF;AAEJ;;;;;CAKC,GACD,MAAMS,eAAe,CAACT,OAAkB,CAAA;QACtCA;QACA,iBAAiB;QACjBY,MAAM;IACR,CAAA;AAEA,qFAAqF,GACrF,MAAMtB,WAAW,CACfX,oBAEAN,OAAOwC,IAAI,CACT,IAAIzC,SAAS;QAAE0C,QAAQ5C,kBAAkBS,mBAAmBiB,GAAG;IAAC"}
1
+ {"version":3,"sources":["../src/entity-metadata-route.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport {\n parsePermission,\n type Permission,\n permissionForEntity,\n permissionForUseCase,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport {\n describeEntityUseCases,\n type Entity,\n ENTITY_ACTIONS,\n type EntityConstructor,\n type EntityMetadataDocument,\n extractMetaEntity,\n makeEntityMetadataEnvelope,\n NotFound,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { requirePrincipal, withVerifiedContext } from './auth/index.js';\nimport {\n assertCompositionsDeclared,\n compositionFor,\n type MetadataCompositions,\n} from './metadata-composition.js';\nimport { respond } from './respond.js';\n\n/**\n * `GET /api/<entity>/$metadata` — what this caller may do with one entity.\n *\n * Mounted **per entity, at a literal path**, not as a `/api/:entity/$metadata`\n * wildcard. `HttpRouter` resolves through `find-my-way-ts`, where a static\n * segment beats a parametric one and there is no backtracking once the\n * parametric branch has matched: alongside an existing `/api/<entity>/:id`, a\n * wildcard `$metadata` route never runs at all — the by-id handler wins with\n * `id === \"$metadata\"`, misses, and answers its own `404`. The endpoint would\n * read as \"this entity has no metadata\" while appearing mounted. A literal wins\n * regardless of registration order, which is why the base exports a route for\n * one entity and each service registers it for each of its own.\n *\n * Deliberately **not** behind `requireOrganization`, even on a tenant-plane\n * service: the document describes the model, not tenant data, and resolving a\n * database handle here would leave a vendor with no active organization unable\n * to see their own affordances.\n */\nexport const entityMetadataRoute = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n compositions: MetadataCompositions = {},\n) => {\n assertCompositionsDeclared(\n describeEntityUseCases(entityConstructor),\n compositions,\n );\n return respond(\n requirePrincipal(principal =>\n Effect.gen(function* () {\n const policy = yield* PolicyDecisionTag;\n const allows = (permission: Permission): boolean => {\n const { resource, action } = parsePermission(permission);\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\n };\n\n // SECURITY BOUNDARY. The document names domains, entity keys and verbs —\n // it is a map of the model — so an entity the caller may not read answers\n // exactly as one this service does not host. A `403` here would make the\n // endpoint an oracle: walk it and learn the shape of everything you are\n // not allowed to see. Same category as `redactConfiguration`, not\n // diagnostics polish.\n if (!allows(permissionForEntity(entityConstructor, 'read'))) {\n return yield* notFound(entityConstructor);\n }\n\n const document: EntityMetadataDocument = {\n actions: ENTITY_ACTIONS.filter(action =>\n allows(permissionForEntity(entityConstructor, action)),\n ),\n useCases: yield* withVerifiedContext(principal, verified =>\n Effect.succeed(\n describeEntityUseCases(entityConstructor)\n .filter(descriptor =>\n allows(\n permissionForUseCase(entityConstructor, descriptor.key),\n ),\n )\n // A verb the caller resolves to nothing is omitted, like one\n // they may not invoke; the rest carry what they resolve to.\n .flatMap(descriptor => {\n const composition = compositionFor(\n descriptor,\n verified,\n compositions,\n );\n if (composition === 'unreachable') return [];\n return composition === undefined\n ? [descriptor]\n : [{ ...descriptor, composition }];\n }),\n ),\n ),\n };\n\n // The ETag hashes the *computed* document, not the descriptor set the\n // deployment declares. Two principals with different grants get different\n // documents from the same model, so a hash of the model would `304` one\n // caller onto another's affordances. Hashing the permission set instead\n // would read `ROLE_PERMISSIONS` directly and go around `PolicyDecisionTag`,\n // so an injected ABAC policy could change affordances without changing the\n // tag. Computing first costs a metadata read and a handful of pure\n // `decide` calls — no IO.\n const body = JSON.stringify(\n makeEntityMetadataEnvelope(entityConstructor, document),\n );\n const etag = `\"${createHash('sha256').update(body).digest('hex')}\"`;\n\n const request = yield* HttpServerRequest.HttpServerRequest;\n if (request.headers['if-none-match'] === etag) {\n return HttpServerResponse.empty({ status: 304 }).pipe(\n HttpServerResponse.setHeaders(cacheHeaders(etag)),\n );\n }\n\n return HttpServerResponse.text(body, {\n contentType: 'application/json',\n headers: cacheHeaders(etag),\n });\n }),\n ),\n );\n};\n\n/**\n * The response varies by principal, so it must never land in a shared cache.\n * `Vary` names **both** credential carriers because the shell reads the access\n * token from the `entifix_at` cookie *or* an `Authorization: Bearer` header, and a\n * cache keyed on only one of them would serve across the other.\n */\nconst cacheHeaders = (etag: string) => ({\n etag,\n 'cache-control': 'private, no-cache',\n vary: 'Cookie, Authorization',\n});\n\n/** Indistinguishable from the `404` a service gives for an entity it does not host. */\nconst notFound = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n) =>\n Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n"],"names":["createHash","parsePermission","permissionForEntity","permissionForUseCase","PolicyDecisionTag","describeEntityUseCases","ENTITY_ACTIONS","extractMetaEntity","makeEntityMetadataEnvelope","NotFound","Effect","HttpServerRequest","HttpServerResponse","requirePrincipal","withVerifiedContext","assertCompositionsDeclared","compositionFor","respond","entityMetadataRoute","entityConstructor","compositions","principal","gen","policy","allows","permission","resource","action","decide","subject","roles","notFound","document","actions","filter","useCases","verified","succeed","descriptor","key","flatMap","composition","undefined","body","JSON","stringify","etag","update","digest","request","headers","empty","status","pipe","setHeaders","cacheHeaders","text","contentType","vary","fail","entity"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SACEC,eAAe,EAEfC,mBAAmB,EACnBC,oBAAoB,EACpBC,iBAAiB,QACZ,iBAAiB;AACxB,SACEC,sBAAsB,EAEtBC,cAAc,EAGdC,iBAAiB,EACjBC,0BAA0B,EAC1BC,QAAQ,QACH,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEpE,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,kBAA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wE;YACxE,wEAAwE;YACxE,4EAA4E;YAC5E,2EAA2E;YAC3E,mEAAmE;YACnE,0BAA0B;YAC1B,MAAME,OAAOC,KAAKC,SAAS,CACzBrC,2BAA2BW,mBAAmBa;YAEhD,MAAMc,OAAO,CAAC,CAAC,EAAE9C,WAAW,UAAU+C,MAAM,CAACJ,MAAMK,MAAM,CAAC,OAAO,CAAC,CAAC;YAEnE,MAAMC,UAAU,OAAOtC,kBAAkBA,iBAAiB;YAC1D,IAAIsC,QAAQC,OAAO,CAAC,gBAAgB,KAAKJ,MAAM;gBAC7C,OAAOlC,mBAAmBuC,KAAK,CAAC;oBAAEC,QAAQ;gBAAI,GAAGC,IAAI,CACnDzC,mBAAmB0C,UAAU,CAACC,aAAaT;YAE/C;YAEA,OAAOlC,mBAAmB4C,IAAI,CAACb,MAAM;gBACnCc,aAAa;gBACbP,SAASK,aAAaT;YACxB;QACF;AAGN,EAAE;AAEF;;;;;CAKC,GACD,MAAMS,eAAe,CAACT,OAAkB,CAAA;QACtCA;QACA,iBAAiB;QACjBY,MAAM;IACR,CAAA;AAEA,qFAAqF,GACrF,MAAM3B,WAAW,CACfZ,oBAEAT,OAAOiD,IAAI,CACT,IAAIlD,SAAS;QAAEmD,QAAQrD,kBAAkBY,mBAAmBoB,GAAG;IAAC"}
@@ -1,8 +1,8 @@
1
1
  import { type Action, type PolicyDecisionTag, type ServiceCrossingPolicyTag } from '@entifix/authz';
2
- import type { RepositoryScope, TokenServiceTag } from '@entifix/business';
2
+ import type { RepositoryScope, RequestPrincipal, TokenServiceTag, VerifiedContext } from '@entifix/business';
3
3
  import type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';
4
4
  import type { Effect } from 'effect';
5
- import { type RequestPrincipal, type ServiceCrossingTokenTag } from './auth/index.js';
5
+ import { type ServiceCrossingTokenTag } from './auth/index.js';
6
6
  /**
7
7
  * Who may reach a route, and where the organization a per-organization store
8
8
  * needs comes from.
@@ -29,6 +29,8 @@ export type EntityRouteGuard = {
29
29
  /** What a route learned about its caller from its guard. */
30
30
  export interface EntityRouteContext extends RepositoryScope {
31
31
  readonly principal?: RequestPrincipal;
32
+ /** The caller's verified context, built by the guard from the principal. */
33
+ readonly verified?: VerifiedContext;
32
34
  }
33
35
  /**
34
36
  * Which records of an entity a caller may see.
@@ -56,5 +58,5 @@ export type GuardServices<G extends EntityRouteGuard> = TokenServiceTag | Policy
56
58
  * check that enforces it, so the entity routes and the facet route cannot
57
59
  * enforce the same guard differently.
58
60
  */
59
- export declare const guardRoute: <T extends Entity, A, E, R>(entityConstructor: EntityConstructor<T>, guard: EntityRouteGuard, action: Action, use: (context: EntityRouteContext) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, TokenServiceTag | PolicyDecisionTag | import("effect/http/HttpServerRequest").HttpServerRequest | R> | Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, ServiceCrossingPolicyTag | import("effect/http/HttpServerRequest").HttpServerRequest | ServiceCrossingTokenTag | R>;
61
+ export declare const guardRoute: <T extends Entity, A, E, R>(entityConstructor: EntityConstructor<T>, guard: EntityRouteGuard, action: Action, use: (context: EntityRouteContext) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, TokenServiceTag | PolicyDecisionTag | import("effect/http/HttpServerRequest").HttpServerRequest | Exclude<R, import("@entifix/business").VerifiedContextTag>> | Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, ServiceCrossingPolicyTag | import("effect/http/HttpServerRequest").HttpServerRequest | ServiceCrossingTokenTag | Exclude<R, import("@entifix/business").VerifiedContextTag>>;
60
62
  //# sourceMappingURL=entity-route-guard.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entity-route-guard.d.ts","sourceRoot":"","sources":["../src/entity-route-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,MAAM,EAEX,KAAK,iBAAiB,EACtB,KAAK,wBAAwB,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AE,eAAe,CAAC;CACrC;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,MAAM,IACxC,KAAK,GACL,MAAM,GACN;IACE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC;IAChC,QAAQ,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,OAAO,CAAC;CAC3C,CAAC;AAEN;;;;GAIG;AACH,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,gBAAgB,IAChD,eAAe,GACf,iBAAiB,GACjB,CAAC,CAAC,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;CAAE,GACpC,uBAAuB,GAAG,wBAAwB,GAClD,KAAK,CAAC,CAAC;AAEf;;;;;GAKG;AACH,eAAO,MAAM,UAAU,GAAI,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAClD,mBAAmB,iBAAiB,CAAC,CAAC,CAAC,EACvC,OAAO,gBAAgB,EACvB,QAAQ,MAAM,EACd,KAAK,CAAC,OAAO,EAAE,kBAAkB,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,qfAyB7D,CAAC"}
@@ -1,5 +1,6 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  import { permissionForEntity } from '@entifix/authz';
2
- import { requireCrossing, requireOrganization, requirePermission, requireServiceCrossing } from './auth/index.js';
3
+ import { requireCrossing, requireOrganization, requirePermission, requireServiceCrossing, withVerifiedContext } from './auth/index.js';
3
4
  /**
4
5
  * Runs `use` behind `guard`, checking the permission the entity derives for
5
6
  * `action` — the one place a derived route turns a stated guard into the
@@ -7,22 +8,27 @@ import { requireCrossing, requireOrganization, requirePermission, requireService
7
8
  * enforce the same guard differently.
8
9
  */ export const guardRoute = (entityConstructor, guard, action, use)=>{
9
10
  const permission = permissionForEntity(entityConstructor, action);
11
+ // Every guard ends here: the context is built once, from what the guard
12
+ // verified, and provided to everything the route runs.
13
+ const verify = (context)=>withVerifiedContext(context.principal, (verified)=>use(_extends({}, context, {
14
+ verified
15
+ })));
10
16
  switch(guard.kind){
11
17
  case 'public':
12
- return use({});
18
+ return verify({});
13
19
  case 'permission':
14
- return requirePermission(permission)((principal)=>use({
20
+ return requirePermission(permission)((principal)=>verify({
15
21
  principal
16
22
  }));
17
23
  case 'organization':
18
- return requireOrganization(permission)((organizationId, principal)=>use({
24
+ return requireOrganization(permission)((organizationId, principal)=>verify({
19
25
  organizationId,
20
26
  principal
21
27
  }));
22
28
  case 'crossing':
23
- return guard.organization ? requireServiceCrossing(permission)((organizationId)=>use({
29
+ return guard.organization ? requireServiceCrossing(permission)((organizationId)=>verify({
24
30
  organizationId
25
- })) : requireCrossing(permission)(use({}));
31
+ })) : requireCrossing(permission)(verify({}));
26
32
  }
27
33
  };
28
34
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity-route-guard.ts"],"sourcesContent":["import {\n type Action,\n permissionForEntity,\n type PolicyDecisionTag,\n type ServiceCrossingPolicyTag,\n} from '@entifix/authz';\nimport type { RepositoryScope, TokenServiceTag } from '@entifix/business';\nimport type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';\nimport type { Effect } from 'effect';\n\nimport {\n type RequestPrincipal,\n requireCrossing,\n requireOrganization,\n requirePermission,\n requireServiceCrossing,\n type ServiceCrossingTokenTag,\n} from './auth/index.js';\n\n/**\n * Who may reach a route, and where the organization a per-organization store\n * needs comes from.\n *\n * - `public` — anybody; nothing is checked and no organization is known.\n * - `permission` — a verified session holding the permission the entity\n * derives for the verb.\n * - `organization` — the same, plus the session's active organization, which\n * is what a per-organization store opens.\n * - `crossing` — the fleet's crossing token and no session at all. With\n * `organization: true` the caller names the organization in a header, which\n * only a caller that has proved it is the fleet may do.\n */\nexport type EntityRouteGuard =\n | { readonly kind: 'public' }\n | { readonly kind: 'permission' }\n | { readonly kind: 'organization' }\n | { readonly kind: 'crossing'; readonly organization: boolean };\n\n/** What a route learned about its caller from its guard. */\nexport interface EntityRouteContext extends RepositoryScope {\n readonly principal?: RequestPrincipal;\n}\n\n/**\n * Which records of an entity a caller may see.\n *\n * `filter` narrows a list and `includes` decides a by-id read — both are\n * needed, because `id` is the one member no query can name. `'none'` is a\n * caller who holds the read grant and owns nothing: an empty page and a `404`,\n * never a `403`, because owning no records is not an error.\n */\nexport type EntityReadScope<T extends Entity> =\n | 'all'\n | 'none'\n | {\n readonly filter: FilterGroup<T>;\n readonly includes: (entity: T) => boolean;\n };\n\n/**\n * What a route needs from the host for its guard: a session's services always\n * (a `$metadata` read and a session guard both read the caller), the fleet's\n * crossing services only when a guard is a crossing.\n */\nexport type GuardServices<G extends EntityRouteGuard> =\n | TokenServiceTag\n | PolicyDecisionTag\n | (G extends { readonly kind: 'crossing' }\n ? ServiceCrossingTokenTag | ServiceCrossingPolicyTag\n : never);\n\n/**\n * Runs `use` behind `guard`, checking the permission the entity derives for\n * `action` — the one place a derived route turns a stated guard into the\n * check that enforces it, so the entity routes and the facet route cannot\n * enforce the same guard differently.\n */\nexport const guardRoute = <T extends Entity, A, E, R>(\n entityConstructor: EntityConstructor<T>,\n guard: EntityRouteGuard,\n action: Action,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, R>,\n) => {\n const permission = permissionForEntity(entityConstructor, action);\n switch (guard.kind) {\n case 'public':\n return use({});\n case 'permission':\n return requirePermission(permission)(principal => use({ principal }));\n case 'organization':\n return requireOrganization(permission)((organizationId, principal) =>\n use({ organizationId, principal }),\n );\n case 'crossing':\n return guard.organization\n ? requireServiceCrossing(permission)(organizationId =>\n use({ organizationId }),\n )\n : requireCrossing(permission)(use({}));\n }\n};\n"],"names":["permissionForEntity","requireCrossing","requireOrganization","requirePermission","requireServiceCrossing","guardRoute","entityConstructor","guard","action","use","permission","kind","principal","organizationId","organization"],"mappings":"AAAA,SAEEA,mBAAmB,QAGd,iBAAiB;AAKxB,SAEEC,eAAe,EACfC,mBAAmB,EACnBC,iBAAiB,EACjBC,sBAAsB,QAEjB,kBAAkB;AAsDzB;;;;;CAKC,GACD,OAAO,MAAMC,aAAa,CACxBC,mBACAC,OACAC,QACAC;IAEA,MAAMC,aAAaV,oBAAoBM,mBAAmBE;IAC1D,OAAQD,MAAMI,IAAI;QAChB,KAAK;YACH,OAAOF,IAAI,CAAC;QACd,KAAK;YACH,OAAON,kBAAkBO,YAAYE,CAAAA,YAAaH,IAAI;oBAAEG;gBAAU;QACpE,KAAK;YACH,OAAOV,oBAAoBQ,YAAY,CAACG,gBAAgBD,YACtDH,IAAI;oBAAEI;oBAAgBD;gBAAU;QAEpC,KAAK;YACH,OAAOL,MAAMO,YAAY,GACrBV,uBAAuBM,YAAYG,CAAAA,iBACjCJ,IAAI;oBAAEI;gBAAe,MAEvBZ,gBAAgBS,YAAYD,IAAI,CAAC;IACzC;AACF,EAAE"}
1
+ {"version":3,"sources":["../src/entity-route-guard.ts"],"sourcesContent":["import {\n type Action,\n permissionForEntity,\n type PolicyDecisionTag,\n type ServiceCrossingPolicyTag,\n} from '@entifix/authz';\nimport type {\n RepositoryScope,\n RequestPrincipal,\n TokenServiceTag,\n VerifiedContext,\n} from '@entifix/business';\nimport type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';\nimport type { Effect } from 'effect';\n\nimport {\n requireCrossing,\n requireOrganization,\n requirePermission,\n requireServiceCrossing,\n type ServiceCrossingTokenTag,\n withVerifiedContext,\n} from './auth/index.js';\n\n/**\n * Who may reach a route, and where the organization a per-organization store\n * needs comes from.\n *\n * - `public` — anybody; nothing is checked and no organization is known.\n * - `permission` — a verified session holding the permission the entity\n * derives for the verb.\n * - `organization` — the same, plus the session's active organization, which\n * is what a per-organization store opens.\n * - `crossing` — the fleet's crossing token and no session at all. With\n * `organization: true` the caller names the organization in a header, which\n * only a caller that has proved it is the fleet may do.\n */\nexport type EntityRouteGuard =\n | { readonly kind: 'public' }\n | { readonly kind: 'permission' }\n | { readonly kind: 'organization' }\n | { readonly kind: 'crossing'; readonly organization: boolean };\n\n/** What a route learned about its caller from its guard. */\nexport interface EntityRouteContext extends RepositoryScope {\n readonly principal?: RequestPrincipal;\n /** The caller's verified context, built by the guard from the principal. */\n readonly verified?: VerifiedContext;\n}\n\n/**\n * Which records of an entity a caller may see.\n *\n * `filter` narrows a list and `includes` decides a by-id read — both are\n * needed, because `id` is the one member no query can name. `'none'` is a\n * caller who holds the read grant and owns nothing: an empty page and a `404`,\n * never a `403`, because owning no records is not an error.\n */\nexport type EntityReadScope<T extends Entity> =\n | 'all'\n | 'none'\n | {\n readonly filter: FilterGroup<T>;\n readonly includes: (entity: T) => boolean;\n };\n\n/**\n * What a route needs from the host for its guard: a session's services always\n * (a `$metadata` read and a session guard both read the caller), the fleet's\n * crossing services only when a guard is a crossing.\n */\nexport type GuardServices<G extends EntityRouteGuard> =\n | TokenServiceTag\n | PolicyDecisionTag\n | (G extends { readonly kind: 'crossing' }\n ? ServiceCrossingTokenTag | ServiceCrossingPolicyTag\n : never);\n\n/**\n * Runs `use` behind `guard`, checking the permission the entity derives for\n * `action` — the one place a derived route turns a stated guard into the\n * check that enforces it, so the entity routes and the facet route cannot\n * enforce the same guard differently.\n */\nexport const guardRoute = <T extends Entity, A, E, R>(\n entityConstructor: EntityConstructor<T>,\n guard: EntityRouteGuard,\n action: Action,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, R>,\n) => {\n const permission = permissionForEntity(entityConstructor, action);\n // Every guard ends here: the context is built once, from what the guard\n // verified, and provided to everything the route runs.\n const verify = (context: EntityRouteContext) =>\n withVerifiedContext(context.principal, verified =>\n use({ ...context, verified }),\n );\n switch (guard.kind) {\n case 'public':\n return verify({});\n case 'permission':\n return requirePermission(permission)(principal => verify({ principal }));\n case 'organization':\n return requireOrganization(permission)((organizationId, principal) =>\n verify({ organizationId, principal }),\n );\n case 'crossing':\n return guard.organization\n ? requireServiceCrossing(permission)(organizationId =>\n verify({ organizationId }),\n )\n : requireCrossing(permission)(verify({}));\n }\n};\n"],"names":["permissionForEntity","requireCrossing","requireOrganization","requirePermission","requireServiceCrossing","withVerifiedContext","guardRoute","entityConstructor","guard","action","use","permission","verify","context","principal","verified","kind","organizationId","organization"],"mappings":";AAAA,SAEEA,mBAAmB,QAGd,iBAAiB;AAUxB,SACEC,eAAe,EACfC,mBAAmB,EACnBC,iBAAiB,EACjBC,sBAAsB,EAEtBC,mBAAmB,QACd,kBAAkB;AAwDzB;;;;;CAKC,GACD,OAAO,MAAMC,aAAa,CACxBC,mBACAC,OACAC,QACAC;IAEA,MAAMC,aAAaX,oBAAoBO,mBAAmBE;IAC1D,wEAAwE;IACxE,uDAAuD;IACvD,MAAMG,SAAS,CAACC,UACdR,oBAAoBQ,QAAQC,SAAS,EAAEC,CAAAA,WACrCL,IAAI,aAAKG;gBAASE;;IAEtB,OAAQP,MAAMQ,IAAI;QAChB,KAAK;YACH,OAAOJ,OAAO,CAAC;QACjB,KAAK;YACH,OAAOT,kBAAkBQ,YAAYG,CAAAA,YAAaF,OAAO;oBAAEE;gBAAU;QACvE,KAAK;YACH,OAAOZ,oBAAoBS,YAAY,CAACM,gBAAgBH,YACtDF,OAAO;oBAAEK;oBAAgBH;gBAAU;QAEvC,KAAK;YACH,OAAON,MAAMU,YAAY,GACrBd,uBAAuBO,YAAYM,CAAAA,iBACjCL,OAAO;oBAAEK;gBAAe,MAE1BhB,gBAAgBU,YAAYC,OAAO,CAAC;IAC5C;AACF,EAAE"}
@@ -1,8 +1,10 @@
1
+ import type { NarrowingRules } from '@entifix/business';
1
2
  import { EntityRepositoryFactoryTag } from '@entifix/business';
2
3
  import { type EntifixBuildError, type EntifixEnvelopeLink, type Entity, type EntityConstructor, type EntityId } from '@entifix/core';
3
4
  import { Effect } from 'effect';
4
5
  import { HttpRouter, HttpServerResponse } from 'effect/http';
5
6
  import { type EntityReadScope, type EntityRouteContext, type EntityRouteGuard } from './entity-route-guard.js';
7
+ import type { MetadataCompositions } from './metadata-composition.js';
6
8
  import { type FailurePolicy } from './respond.js';
7
9
  import { type EntityRouteRefusal, routeFailure } from './route-responses.js';
8
10
  /** The five generic verbs a route set can mount. */
@@ -25,7 +27,17 @@ export interface EntityRoutesOptions<T extends Entity, R, G extends EntityRouteG
25
27
  };
26
28
  /** Defaults to `/api/<entity key>`. */
27
29
  readonly basePath?: `/${string}`;
28
- /** Narrows the reads to what this caller may see. */
30
+ /**
31
+ * Narrows the reads to what this caller may see, as resolver rules over the
32
+ * verified context. Replaces `scope`; a route set naming both throws.
33
+ */
34
+ readonly narrowing?: NarrowingRules<T>;
35
+ /**
36
+ * The variant rules, recipes and catalog the entity's `@useCase()` verbs
37
+ * name, so `$metadata` can report what each resolves to for the caller.
38
+ */
39
+ readonly compositions?: MetadataCompositions;
40
+ /** Narrows the reads to what this caller may see. Superseded by `narrowing`. */
29
41
  readonly scope?: (context: EntityRouteContext) => Effect.Effect<EntityReadScope<T>, never, R>;
30
42
  /**
31
43
  * Runs on every create and update, after the body is read and before the
@@ -1 +1 @@
1
- {"version":3,"file":"entity-routes.d.ts","sourceRoot":"","sources":["../src/entity-routes.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,0BAA0B,EAM3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACxB,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EASd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAqB,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGhF,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EAGtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,KAAK,kBAAkB,EAEvB,YAAY,EACb,MAAM,sBAAsB,CAAC;AAE9B,oDAAoD;AACpD,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B,CAAC,CAAC,CAAC,WAC9B,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;;CAGzC,CAAC"}
@@ -5,6 +5,7 @@ import { Effect } from 'effect';
5
5
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
6
6
  import { entityMetadataRoute } from './entity-metadata-route.js';
7
7
  import { guardRoute } from './entity-route-guard.js';
8
+ import { narrowedByIdRequest, narrowingFor, narrowLoadRequest } from './narrowing.js';
8
9
  import { defaultFailurePolicy, respond } from './respond.js';
9
10
  import { legacyAnswer, routeFailure } from './route-responses.js';
10
11
  export { EntityRouteRefusal } from './route-responses.js';
@@ -34,7 +35,7 @@ const READS = new Set([
34
35
  * A path that is not one of these verbs is written by hand beside it, and a
35
36
  * verb whose generic form does not fit is replaced with `override`.
36
37
  */ const deriveEntityRoutes = (entityConstructor, options)=>{
37
- var _options_basePath;
38
+ var _options_basePath, _options_compositions;
38
39
  const key = envelopeEntityName(entityConstructor);
39
40
  const base = (_options_basePath = options.basePath) != null ? _options_basePath : `/api/${key}`;
40
41
  const mounted = new Set(options.verbs);
@@ -100,7 +101,9 @@ const READS = new Set([
100
101
  organizationId: context.organizationId
101
102
  }));
102
103
  });
104
+ if (options.narrowing !== undefined && options.scope !== undefined) throw new Error(`the routes for '${extractMetaEntity(entityConstructor).key}' name both ` + '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.');
103
105
  const scopeOf = (context)=>options.scope ? options.scope(context) : Effect.succeed('all');
106
+ /** The narrowing rules choose for this caller, or `undefined` without rules. */ const narrowingOf = (context)=>options.narrowing === undefined || context.verified === undefined ? undefined : narrowingFor(options.narrowing, context.verified);
104
107
  const readLoadRequest = Effect.gen(function*() {
105
108
  const request = yield* HttpServerRequest.HttpServerRequest;
106
109
  const search = new URL(request.url, 'http://localhost').searchParams;
@@ -115,10 +118,11 @@ const READS = new Set([
115
118
  const list = (context)=>Effect.gen(function*() {
116
119
  var _parsed_filtering;
117
120
  const parsed = yield* readLoadRequest;
118
- const scope = yield* scopeOf(context);
121
+ const narrowing = narrowingOf(context);
122
+ const scope = narrowing === undefined ? yield* scopeOf(context) : narrowing === 'nothing' ? 'none' : 'all';
119
123
  if (scope === 'none') {
120
124
  // Still parsed: whether a query is well-formed must not depend on who
121
- // asked.
125
+ // asked. `nothing` answers here without a query.
122
126
  return yield* HttpServerResponse.json(makeEntityPageEnvelope(entityConstructor, {
123
127
  items: [],
124
128
  total: 0,
@@ -128,7 +132,7 @@ const READS = new Set([
128
132
  // Conjoined, never substituted: the translator `$and`s every top-level
129
133
  // element, so an added element can only narrow, and no `or` in a query
130
134
  // string can escape it.
131
- const request = scope === 'all' ? parsed : _extends({}, parsed, {
135
+ const request = narrowing !== undefined && narrowing !== 'nothing' ? narrowLoadRequest(parsed, narrowing) : scope === 'all' ? parsed : _extends({}, parsed, {
132
136
  filtering: [
133
137
  ...(_parsed_filtering = parsed.filtering) != null ? _parsed_filtering : [],
134
138
  scope.filter
@@ -139,7 +143,17 @@ const READS = new Set([
139
143
  }).pipe(Effect.catch(legacyAnswer('invalidQuery')));
140
144
  const get = (context)=>Effect.gen(function*() {
141
145
  const params = yield* HttpRouter.params;
142
- const scope = yield* scopeOf(context);
146
+ const narrowing = narrowingOf(context);
147
+ if (narrowing === 'nothing') return yield* notFound;
148
+ // A filter narrowing reads by id as a narrowed load, so the read and the
149
+ // list apply one rule: there is no second, in-memory predicate to drift.
150
+ if (narrowing !== undefined && narrowing !== 'unscoped') {
151
+ const page = yield* loadUCFactory().pipe(Effect.provideService(EntityRepositoryTag, (yield* repository(context))), Effect.provideService(EntityLoadRequestTag, narrowedByIdRequest(narrowing, params.id)));
152
+ const [only] = page.items;
153
+ if (only === undefined) return yield* notFound;
154
+ return yield* HttpServerResponse.json(makeEntityEnvelope(entityConstructor, only, links.record(params.id)));
155
+ }
156
+ const scope = narrowing === undefined ? yield* scopeOf(context) : 'all';
143
157
  if (scope === 'none') return yield* notFound;
144
158
  const found = yield* getUCFactory().pipe(Effect.provideService(EntityRepositoryTag, (yield* repository(context))), Effect.provideService(EntityIdTag, params.id), Effect.option);
145
159
  // Out of scope answers exactly as absent does: a `403` would confirm the
@@ -235,7 +249,7 @@ const READS = new Set([
235
249
  };
236
250
  return HttpRouter.addAll([
237
251
  // A literal, so it wins over `/:id` regardless of order.
238
- HttpRouter.route('GET', `${base}/$metadata`, entityMetadataRoute(entityConstructor)),
252
+ HttpRouter.route('GET', `${base}/$metadata`, entityMetadataRoute(entityConstructor, (_options_compositions = options.compositions) != null ? _options_compositions : {})),
239
253
  ...options.verbs.map((verb)=>HttpRouter.route(ROUTES[verb].method, ROUTES[verb].path, handlerFor(verb)))
240
254
  ]);
241
255
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity-routes.ts"],"sourcesContent":["import type { Action } from '@entifix/authz';\nimport {\n deleteUCFactory,\n EntityIdTag,\n EntityLoadRequestTag,\n EntityRepositoryFactoryTag,\n EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n type EntifixBuildError,\n type EntifixEnvelopeLink,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n envelopeEntityName,\n extractMetaEntity,\n makeEntityEnvelope,\n makeEntityPageEnvelope,\n NotFound,\n parseLoadRequestParams,\n readEntityEnvelope,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { entityMetadataRoute } from './entity-metadata-route.js';\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport {\n type EntityRouteRefusal,\n legacyAnswer,\n routeFailure,\n} from './route-responses.js';\n\n/** The five generic verbs a route set can mount. */\nexport type EntityVerb = 'list' | 'get' | 'create' | 'update' | 'delete';\n\nexport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n} from './entity-route-guard.js';\nexport { EntityRouteRefusal } from './route-responses.js';\n\n/** A hand-written handler for one verb, mounted under the derived guard. */\nexport type EntityRouteOverride<R> = (\n context: EntityRouteContext,\n links: EntityRouteLinks,\n) => Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, R>;\n\n/** The affordances a route set derives from the verbs it mounts. */\nexport interface EntityRouteLinks {\n readonly record: (id: EntityId) => EntifixEnvelopeLink[];\n readonly collection: () => EntifixEnvelopeLink[];\n}\n\nexport interface EntityRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n readonly verbs: readonly EntityVerb[];\n /** One guard for every verb, or one for the reads and one for the writes. */\n readonly guard: G | { readonly read: G; readonly write: G };\n /** Defaults to `/api/<entity key>`. */\n readonly basePath?: `/${string}`;\n /** Narrows the reads to what this caller may see. */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /**\n * Runs on every create and update, after the body is read and before the\n * save — and may change what is saved, or refuse it.\n */\n readonly prepare?: (\n entity: T,\n context: EntityRouteContext & { readonly verb: 'create' | 'update' },\n ) => Effect.Effect<T, EntityRouteRefusal | EntifixBuildError, R>;\n /**\n * A hand-written handler in place of the generic one for a verb. It keeps\n * the derived guard and receives the derived links, so the escape hatch\n * cannot drift from the rest of the set.\n */\n readonly override?: Partial<Record<EntityVerb, EntityRouteOverride<R>>>;\n /**\n * How every verb's failures are answered and logged. Defaults to\n * {@link defaultFailurePolicy}; a host passes its fleet policy.\n */\n readonly policy?: FailurePolicy;\n}\n\nconst ACTION: Record<EntityVerb, Action> = {\n list: 'read',\n get: 'read',\n create: 'write',\n update: 'write',\n delete: 'delete',\n};\n\nconst READS: ReadonlySet<EntityVerb> = new Set(['list', 'get']);\n\n/**\n * The generic routes for one entity — list, read, create, update, delete and\n * its `$metadata` — derived from the entity and bound to storage through the\n * host's {@link EntityRepositoryFactoryTag}.\n *\n * What a route set varies on is stated, not written: which verbs exist, who may\n * reach them, which records a reader sees, and what a save must pass. What it\n * never varies on is the wire: the load request is parsed against the entity's\n * own metadata (so a query can only name a member the entity declared\n * filterable or sortable), every answer is an envelope, and the links name\n * exactly the verbs mounted — never one that would `404`.\n *\n * A path that is not one of these verbs is written by hand beside it, and a\n * verb whose generic form does not fit is replaced with `override`.\n */\nconst deriveEntityRoutes = <\n T extends Entity,\n R = never,\n // `never`, not the whole union: TypeScript infers no type argument once a\n // caller names one, so `makeEntityRoutes<T, R>(…)` used to default `G` to\n // every guard. Then the crossing tags became requirements of a route that\n // guards on a session, and the error surfaced at the host's `Layer.provide`\n // instead of here. Defaulting to `never` refuses that call at the guard\n // itself; `makeEntityRoutes.for<R>()` is the way to name `R` alone.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n) => {\n const key = envelopeEntityName(entityConstructor);\n const base: `/${string}` = options.basePath ?? `/api/${key}`;\n const mounted = new Set(options.verbs);\n\n const links: EntityRouteLinks = {\n record: id => {\n const href = `${base}/${String(id)}`;\n return [\n ...(mounted.has('get')\n ? [{ rel: 'self', href, method: 'GET' } as const]\n : []),\n ...(mounted.has('list')\n ? [{ rel: 'list', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('update')\n ? [{ rel: 'update', href, method: 'PUT' } as const]\n : []),\n ...(mounted.has('delete')\n ? [{ rel: 'delete', href, method: 'DELETE' } as const]\n : []),\n ];\n },\n collection: () => [\n ...(mounted.has('list')\n ? [{ rel: 'self', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('create')\n ? [{ rel: 'create', href: base, method: 'POST' } as const]\n : []),\n ],\n };\n\n const guardFor = (verb: EntityVerb): EntityRouteGuard => {\n const guard = options.guard as\n | EntityRouteGuard\n | { readonly read: EntityRouteGuard; readonly write: EntityRouteGuard };\n return 'kind' in guard ? guard : READS.has(verb) ? guard.read : guard.write;\n };\n\n const guarded = <A, E, RR>(\n verb: EntityVerb,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, RR>,\n ) => guardRoute(entityConstructor, guardFor(verb), ACTION[verb], use);\n\n const repository = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const factory = yield* EntityRepositoryFactoryTag;\n return yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n });\n\n const scopeOf = (context: EntityRouteContext) =>\n options.scope ? options.scope(context) : Effect.succeed('all' as const);\n\n const readLoadRequest = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () =>\n parseLoadRequestParams(\n entityConstructor,\n search,\n ) as unknown as EntityLoadRequest<T>,\n catch: error => error as EntifixBuildError,\n });\n });\n\n const notFound = Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n\n const list = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const parsed = yield* readLoadRequest;\n const scope = yield* scopeOf(context);\n if (scope === 'none') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked.\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(\n entityConstructor,\n { items: [], total: 0, request: parsed },\n links.collection(),\n ),\n );\n }\n // Conjoined, never substituted: the translator `$and`s every top-level\n // element, so an added element can only narrow, and no `or` in a query\n // string can escape it.\n const request: EntityLoadRequest<T> =\n scope === 'all'\n ? parsed\n : {\n ...parsed,\n filtering: [...(parsed.filtering ?? []), scope.filter],\n };\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(\n EntityLoadRequestTag,\n request as unknown as EntityLoadRequest,\n ),\n );\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(entityConstructor, page, links.collection()),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const get = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n const scope = yield* scopeOf(context);\n if (scope === 'none') return yield* notFound;\n const found = yield* getUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n Effect.option,\n );\n // Out of scope answers exactly as absent does: a `403` would confirm the\n // record exists to somebody who may not read it.\n if (\n found._tag === 'None' ||\n (scope !== 'all' && !scope.includes(found.value))\n ) {\n return yield* notFound;\n }\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(\n entityConstructor,\n found.value,\n links.record(params.id),\n ),\n );\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const save = (verb: 'create' | 'update') => (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const body = yield* request.json;\n let entity = yield* readEntityEnvelope(entityConstructor, body);\n\n // On update the URL is authoritative, so a record cannot be renamed\n // onto another one by editing its payload.\n if (verb === 'update') {\n const params = yield* HttpRouter.params;\n entity.id = params.id;\n }\n if (options.prepare) {\n entity = yield* options.prepare(entity, { ...context, verb });\n }\n\n const saved = yield* saveUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityTag, entity),\n );\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(entityConstructor, saved, links.record(saved.id)),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidBody')));\n\n /**\n * Answers with an envelope rather than a bare `204`: every message between\n * entifix artifacts is one, and the fetch client parses every response as\n * JSON.\n */\n const remove = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n yield* deleteUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n );\n return yield* HttpServerResponse.json({\n meta: { type: 'entity', entity: key, links: links.collection() },\n data: { id: params.id },\n });\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const generic = (verb: EntityVerb, context: EntityRouteContext) => {\n switch (verb) {\n case 'list':\n return list(context);\n case 'get':\n return get(context);\n case 'create':\n return save('create')(context);\n case 'update':\n return save('update')(context);\n case 'delete':\n return remove(context);\n }\n };\n\n /**\n * Each guard asks for different services, so the branches do not unify on\n * their own; the cast states the union every guard this set can reach\n * actually needs.\n */\n const handlerFor = (verb: EntityVerb) =>\n respond(\n (\n guarded(verb, context => {\n const override = options.override?.[verb];\n return override ? override(context, links) : generic(verb, context);\n }) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n unknown,\n | R\n | EntityRepositoryFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >\n ).pipe(Effect.catch(legacyAnswer('invalid'))),\n options.policy ?? defaultFailurePolicy,\n );\n\n const ROUTES: Record<\n EntityVerb,\n { method: 'GET' | 'POST' | 'PUT' | 'DELETE'; path: `/${string}` }\n > = {\n list: { method: 'GET', path: base },\n get: { method: 'GET', path: `${base}/:id` },\n create: { method: 'POST', path: base },\n update: { method: 'PUT', path: `${base}/:id` },\n delete: { method: 'DELETE', path: `${base}/:id` },\n };\n\n return HttpRouter.addAll([\n // A literal, so it wins over `/:id` regardless of order.\n HttpRouter.route(\n 'GET',\n `${base}/$metadata`,\n entityMetadataRoute(entityConstructor),\n ),\n ...options.verbs.map(verb =>\n HttpRouter.route(\n ROUTES[verb].method,\n ROUTES[verb].path,\n handlerFor(verb),\n ),\n ),\n ]);\n};\n\n/**\n * {@link deriveEntityRoutes}, with a curried form for a caller that has to\n * name the services its `override`, `scope` or `prepare` handlers need:\n * `makeEntityRoutes.for<R>()(Entity, options)` names `R` and still infers the\n * entity and the guard from the value, which a single call with explicit type\n * arguments cannot do.\n */\nexport { routeFailure };\n\nexport const makeEntityRoutes = Object.assign(deriveEntityRoutes, {\n for:\n <R>() =>\n <T extends Entity, const G extends EntityRouteGuard>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n ) =>\n deriveEntityRoutes<T, R, G>(entityConstructor, options),\n});\n"],"names":["deleteUCFactory","EntityIdTag","EntityLoadRequestTag","EntityRepositoryFactoryTag","EntityRepositoryTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","envelopeEntityName","extractMetaEntity","makeEntityEnvelope","makeEntityPageEnvelope","NotFound","parseLoadRequestParams","readEntityEnvelope","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","entityMetadataRoute","guardRoute","defaultFailurePolicy","respond","legacyAnswer","routeFailure","EntityRouteRefusal","ACTION","list","get","create","update","delete","READS","Set","deriveEntityRoutes","entityConstructor","options","key","base","basePath","mounted","verbs","links","record","id","href","String","has","rel","method","collection","guardFor","verb","guard","read","write","guarded","use","repository","context","gen","factory","for","organizationId","undefined","scopeOf","scope","succeed","readLoadRequest","request","search","URL","url","searchParams","try","catch","error","notFound","fail","entity","parsed","json","items","total","filtering","filter","page","pipe","provideService","params","found","option","_tag","includes","value","save","body","prepare","saved","remove","meta","type","data","generic","handlerFor","override","policy","ROUTES","path","addAll","route","map","makeEntityRoutes","Object","assign"],"mappings":";AACA,SACEA,eAAe,EACfC,WAAW,EACXC,oBAAoB,EACpBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SAOEC,kBAAkB,EAClBC,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,EACtBC,QAAQ,EACRC,sBAAsB,EACtBC,kBAAkB,QACb,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,UAAU,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEhF,SAASC,mBAAmB,QAAQ,6BAA6B;AACjE,SAIEC,UAAU,QAEL,0BAA0B;AACjC,SACEC,oBAAoB,EAEpBC,OAAO,QACF,eAAe;AACtB,SAEEC,YAAY,EACZC,YAAY,QACP,uBAAuB;AAU9B,SAASC,kBAAkB,QAAQ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8F,KAAK,CACdH,MAAM,CAACvD,KAAK,CAACH,MAAM,EACnB0D,MAAM,CAACvD,KAAK,CAACwD,IAAI,EACjBJ,WAAWpD;KAGhB;AACH;AAEA;;;;;;CAMC,GACD,SAAS5B,YAAY,GAAG;AAExB,OAAO,MAAMwF,mBAAmBC,OAAOC,MAAM,CAAChF,oBAAoB;IAChE4B,KACE,IACA,CACE3B,mBACAC,UAEAF,mBAA4BC,mBAAmBC;AACrD,GAAG"}
1
+ {"version":3,"sources":["../src/entity-routes.ts"],"sourcesContent":["import type { Action } from '@entifix/authz';\nimport type { NarrowingRules } from '@entifix/business';\nimport {\n deleteUCFactory,\n EntityIdTag,\n EntityLoadRequestTag,\n EntityRepositoryFactoryTag,\n EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n type EntifixBuildError,\n type EntifixEnvelopeLink,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n envelopeEntityName,\n extractMetaEntity,\n makeEntityEnvelope,\n makeEntityPageEnvelope,\n NotFound,\n parseLoadRequestParams,\n readEntityEnvelope,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { entityMetadataRoute } from './entity-metadata-route.js';\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport type { MetadataCompositions } from './metadata-composition.js';\nimport {\n narrowedByIdRequest,\n narrowingFor,\n narrowLoadRequest,\n} from './narrowing.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport {\n type EntityRouteRefusal,\n legacyAnswer,\n routeFailure,\n} from './route-responses.js';\n\n/** The five generic verbs a route set can mount. */\nexport type EntityVerb = 'list' | 'get' | 'create' | 'update' | 'delete';\n\nexport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n} from './entity-route-guard.js';\nexport { EntityRouteRefusal } from './route-responses.js';\n\n/** A hand-written handler for one verb, mounted under the derived guard. */\nexport type EntityRouteOverride<R> = (\n context: EntityRouteContext,\n links: EntityRouteLinks,\n) => Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, R>;\n\n/** The affordances a route set derives from the verbs it mounts. */\nexport interface EntityRouteLinks {\n readonly record: (id: EntityId) => EntifixEnvelopeLink[];\n readonly collection: () => EntifixEnvelopeLink[];\n}\n\nexport interface EntityRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n readonly verbs: readonly EntityVerb[];\n /** One guard for every verb, or one for the reads and one for the writes. */\n readonly guard: G | { readonly read: G; readonly write: G };\n /** Defaults to `/api/<entity key>`. */\n readonly basePath?: `/${string}`;\n /**\n * Narrows the reads to what this caller may see, as resolver rules over the\n * verified context. Replaces `scope`; a route set naming both throws.\n */\n readonly narrowing?: NarrowingRules<T>;\n /**\n * The variant rules, recipes and catalog the entity's `@useCase()` verbs\n * name, so `$metadata` can report what each resolves to for the caller.\n */\n readonly compositions?: MetadataCompositions;\n /** Narrows the reads to what this caller may see. Superseded by `narrowing`. */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /**\n * Runs on every create and update, after the body is read and before the\n * save — and may change what is saved, or refuse it.\n */\n readonly prepare?: (\n entity: T,\n context: EntityRouteContext & { readonly verb: 'create' | 'update' },\n ) => Effect.Effect<T, EntityRouteRefusal | EntifixBuildError, R>;\n /**\n * A hand-written handler in place of the generic one for a verb. It keeps\n * the derived guard and receives the derived links, so the escape hatch\n * cannot drift from the rest of the set.\n */\n readonly override?: Partial<Record<EntityVerb, EntityRouteOverride<R>>>;\n /**\n * How every verb's failures are answered and logged. Defaults to\n * {@link defaultFailurePolicy}; a host passes its fleet policy.\n */\n readonly policy?: FailurePolicy;\n}\n\nconst ACTION: Record<EntityVerb, Action> = {\n list: 'read',\n get: 'read',\n create: 'write',\n update: 'write',\n delete: 'delete',\n};\n\nconst READS: ReadonlySet<EntityVerb> = new Set(['list', 'get']);\n\n/**\n * The generic routes for one entity — list, read, create, update, delete and\n * its `$metadata` — derived from the entity and bound to storage through the\n * host's {@link EntityRepositoryFactoryTag}.\n *\n * What a route set varies on is stated, not written: which verbs exist, who may\n * reach them, which records a reader sees, and what a save must pass. What it\n * never varies on is the wire: the load request is parsed against the entity's\n * own metadata (so a query can only name a member the entity declared\n * filterable or sortable), every answer is an envelope, and the links name\n * exactly the verbs mounted — never one that would `404`.\n *\n * A path that is not one of these verbs is written by hand beside it, and a\n * verb whose generic form does not fit is replaced with `override`.\n */\nconst deriveEntityRoutes = <\n T extends Entity,\n R = never,\n // `never`, not the whole union: TypeScript infers no type argument once a\n // caller names one, so `makeEntityRoutes<T, R>(…)` used to default `G` to\n // every guard. Then the crossing tags became requirements of a route that\n // guards on a session, and the error surfaced at the host's `Layer.provide`\n // instead of here. Defaulting to `never` refuses that call at the guard\n // itself; `makeEntityRoutes.for<R>()` is the way to name `R` alone.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n) => {\n const key = envelopeEntityName(entityConstructor);\n const base: `/${string}` = options.basePath ?? `/api/${key}`;\n const mounted = new Set(options.verbs);\n\n const links: EntityRouteLinks = {\n record: id => {\n const href = `${base}/${String(id)}`;\n return [\n ...(mounted.has('get')\n ? [{ rel: 'self', href, method: 'GET' } as const]\n : []),\n ...(mounted.has('list')\n ? [{ rel: 'list', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('update')\n ? [{ rel: 'update', href, method: 'PUT' } as const]\n : []),\n ...(mounted.has('delete')\n ? [{ rel: 'delete', href, method: 'DELETE' } as const]\n : []),\n ];\n },\n collection: () => [\n ...(mounted.has('list')\n ? [{ rel: 'self', href: base, method: 'GET' } as const]\n : []),\n ...(mounted.has('create')\n ? [{ rel: 'create', href: base, method: 'POST' } as const]\n : []),\n ],\n };\n\n const guardFor = (verb: EntityVerb): EntityRouteGuard => {\n const guard = options.guard as\n | EntityRouteGuard\n | { readonly read: EntityRouteGuard; readonly write: EntityRouteGuard };\n return 'kind' in guard ? guard : READS.has(verb) ? guard.read : guard.write;\n };\n\n const guarded = <A, E, RR>(\n verb: EntityVerb,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, RR>,\n ) => guardRoute(entityConstructor, guardFor(verb), ACTION[verb], use);\n\n const repository = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const factory = yield* EntityRepositoryFactoryTag;\n return yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n });\n\n if (options.narrowing !== undefined && options.scope !== undefined)\n throw new Error(\n `the routes for '${extractMetaEntity(entityConstructor).key}' name both ` +\n '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.',\n );\n\n const scopeOf = (context: EntityRouteContext) =>\n options.scope ? options.scope(context) : Effect.succeed('all' as const);\n\n /** The narrowing rules choose for this caller, or `undefined` without rules. */\n const narrowingOf = (context: EntityRouteContext) =>\n options.narrowing === undefined || context.verified === undefined\n ? undefined\n : narrowingFor(options.narrowing, context.verified);\n\n const readLoadRequest = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () =>\n parseLoadRequestParams(\n entityConstructor,\n search,\n ) as unknown as EntityLoadRequest<T>,\n catch: error => error as EntifixBuildError,\n });\n });\n\n const notFound = Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n\n const list = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const parsed = yield* readLoadRequest;\n const narrowing = narrowingOf(context);\n const scope =\n narrowing === undefined\n ? yield* scopeOf(context)\n : narrowing === 'nothing'\n ? ('none' as const)\n : ('all' as const);\n if (scope === 'none') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked. `nothing` answers here without a query.\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(\n entityConstructor,\n { items: [], total: 0, request: parsed },\n links.collection(),\n ),\n );\n }\n // Conjoined, never substituted: the translator `$and`s every top-level\n // element, so an added element can only narrow, and no `or` in a query\n // string can escape it.\n const request: EntityLoadRequest<T> =\n narrowing !== undefined && narrowing !== 'nothing'\n ? narrowLoadRequest(parsed, narrowing)\n : scope === 'all'\n ? parsed\n : {\n ...parsed,\n filtering: [...(parsed.filtering ?? []), scope.filter],\n };\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(\n EntityLoadRequestTag,\n request as unknown as EntityLoadRequest,\n ),\n );\n return yield* HttpServerResponse.json(\n makeEntityPageEnvelope(entityConstructor, page, links.collection()),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const get = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n const narrowing = narrowingOf(context);\n if (narrowing === 'nothing') return yield* notFound;\n // A filter narrowing reads by id as a narrowed load, so the read and the\n // list apply one rule: there is no second, in-memory predicate to drift.\n if (narrowing !== undefined && narrowing !== 'unscoped') {\n const page = yield* loadUCFactory<T>().pipe(\n Effect.provideService(\n EntityRepositoryTag,\n yield* repository(context),\n ),\n Effect.provideService(\n EntityLoadRequestTag,\n narrowedByIdRequest<T>(\n narrowing,\n params.id,\n ) as unknown as EntityLoadRequest,\n ),\n );\n const [only] = page.items;\n if (only === undefined) return yield* notFound;\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(entityConstructor, only, links.record(params.id)),\n );\n }\n const scope = narrowing === undefined ? yield* scopeOf(context) : 'all';\n if (scope === 'none') return yield* notFound;\n const found = yield* getUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n Effect.option,\n );\n // Out of scope answers exactly as absent does: a `403` would confirm the\n // record exists to somebody who may not read it.\n if (\n found._tag === 'None' ||\n (scope !== 'all' && !scope.includes(found.value))\n ) {\n return yield* notFound;\n }\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(\n entityConstructor,\n found.value,\n links.record(params.id),\n ),\n );\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const save = (verb: 'create' | 'update') => (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const body = yield* request.json;\n let entity = yield* readEntityEnvelope(entityConstructor, body);\n\n // On update the URL is authoritative, so a record cannot be renamed\n // onto another one by editing its payload.\n if (verb === 'update') {\n const params = yield* HttpRouter.params;\n entity.id = params.id;\n }\n if (options.prepare) {\n entity = yield* options.prepare(entity, { ...context, verb });\n }\n\n const saved = yield* saveUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityTag, entity),\n );\n return yield* HttpServerResponse.json(\n makeEntityEnvelope(entityConstructor, saved, links.record(saved.id)),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidBody')));\n\n /**\n * Answers with an envelope rather than a bare `204`: every message between\n * entifix artifacts is one, and the fetch client parses every response as\n * JSON.\n */\n const remove = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const params = yield* HttpRouter.params;\n yield* deleteUCFactory<T>().pipe(\n Effect.provideService(EntityRepositoryTag, yield* repository(context)),\n Effect.provideService(EntityIdTag, params.id),\n );\n return yield* HttpServerResponse.json({\n meta: { type: 'entity', entity: key, links: links.collection() },\n data: { id: params.id },\n });\n }).pipe(Effect.catch(legacyAnswer('invalid')));\n\n const generic = (verb: EntityVerb, context: EntityRouteContext) => {\n switch (verb) {\n case 'list':\n return list(context);\n case 'get':\n return get(context);\n case 'create':\n return save('create')(context);\n case 'update':\n return save('update')(context);\n case 'delete':\n return remove(context);\n }\n };\n\n /**\n * Each guard asks for different services, so the branches do not unify on\n * their own; the cast states the union every guard this set can reach\n * actually needs.\n */\n const handlerFor = (verb: EntityVerb) =>\n respond(\n (\n guarded(verb, context => {\n const override = options.override?.[verb];\n return override ? override(context, links) : generic(verb, context);\n }) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n unknown,\n | R\n | EntityRepositoryFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >\n ).pipe(Effect.catch(legacyAnswer('invalid'))),\n options.policy ?? defaultFailurePolicy,\n );\n\n const ROUTES: Record<\n EntityVerb,\n { method: 'GET' | 'POST' | 'PUT' | 'DELETE'; path: `/${string}` }\n > = {\n list: { method: 'GET', path: base },\n get: { method: 'GET', path: `${base}/:id` },\n create: { method: 'POST', path: base },\n update: { method: 'PUT', path: `${base}/:id` },\n delete: { method: 'DELETE', path: `${base}/:id` },\n };\n\n return HttpRouter.addAll([\n // A literal, so it wins over `/:id` regardless of order.\n HttpRouter.route(\n 'GET',\n `${base}/$metadata`,\n entityMetadataRoute(entityConstructor, options.compositions ?? {}),\n ),\n ...options.verbs.map(verb =>\n HttpRouter.route(\n ROUTES[verb].method,\n ROUTES[verb].path,\n handlerFor(verb),\n ),\n ),\n ]);\n};\n\n/**\n * {@link deriveEntityRoutes}, with a curried form for a caller that has to\n * name the services its `override`, `scope` or `prepare` handlers need:\n * `makeEntityRoutes.for<R>()(Entity, options)` names `R` and still infers the\n * entity and the guard from the value, which a single call with explicit type\n * arguments cannot do.\n */\nexport { routeFailure };\n\nexport const makeEntityRoutes = Object.assign(deriveEntityRoutes, {\n for:\n <R>() =>\n <T extends Entity, const G extends EntityRouteGuard>(\n entityConstructor: EntityConstructor<T>,\n options: EntityRoutesOptions<T, R, G>,\n ) =>\n deriveEntityRoutes<T, R, G>(entityConstructor, options),\n});\n"],"names":["deleteUCFactory","EntityIdTag","EntityLoadRequestTag","EntityRepositoryFactoryTag","EntityRepositoryTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","envelopeEntityName","extractMetaEntity","makeEntityEnvelope","makeEntityPageEnvelope","NotFound","parseLoadRequestParams","readEntityEnvelope","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","entityMetadataRoute","guardRoute","narrowedByIdRequest","narrowingFor","narrowLoadRequest","defaultFailurePolicy","respond","legacyAnswer","routeFailure","EntityRouteRefusal","ACTION","list","get","create","update","delete","READS","Set","deriveEntityRoutes","entityConstructor","options","key","base","basePath","mounted","verbs","links","record","id","href","String","has","rel","method","collection","guardFor","verb","guard","read","write","guarded","use","repository","context","gen","factory","for","organizationId","undefined","narrowing","scope","Error","scopeOf","succeed","narrowingOf","verified","readLoadRequest","request","search","URL","url","searchParams","try","catch","error","notFound","fail","entity","parsed","json","items","total","filtering","filter","page","pipe","provideService","params","only","found","option","_tag","includes","value","save","body","prepare","saved","remove","meta","type","data","generic","handlerFor","override","policy","ROUTES","path","addAll","route","compositions","map","makeEntityRoutes","Object","assign"],"mappings":";AAEA,SACEA,eAAe,EACfC,WAAW,EACXC,oBAAoB,EACpBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SAOEC,kBAAkB,EAClBC,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,EACtBC,QAAQ,EACRC,sBAAsB,EACtBC,kBAAkB,QACb,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,UAAU,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEhF,SAASC,mBAAmB,QAAQ,6BAA6B;AACjE,SAIEC,UAAU,QAEL,0BAA0B;AAEjC,SACEC,mBAAmB,EACnBC,YAAY,EACZC,iBAAiB,QACZ,iBAAiB;AACxB,SACEC,oBAAoB,EAEpBC,OAAO,QACF,eAAe;AACtB,SAEEC,YAAY,EACZC,YAAY,QACP,uBAAuB;AAU9B,SAASC,kBAAkB,QAAQ,uBAAuB;AA2D1D,MAAMC,SAAqC;IACzCC,MAAM;IACNC,KAAK;IACLC,QAAQ;IACRC,QAAQ;I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