@entifix/service-shell 0.13.0 → 0.15.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 (83) hide show
  1. package/README.md +7 -7
  2. package/dist/auth/failures.d.ts +0 -12
  3. package/dist/auth/failures.d.ts.map +1 -1
  4. package/dist/auth/failures.js +0 -10
  5. package/dist/auth/failures.js.map +1 -1
  6. package/dist/auth/index.d.ts +0 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js +0 -1
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/auth/require-principal.d.ts +0 -16
  11. package/dist/auth/require-principal.d.ts.map +1 -1
  12. package/dist/auth/require-principal.js +1 -38
  13. package/dist/auth/require-principal.js.map +1 -1
  14. package/dist/auth/require-service-crossing.d.ts +2 -73
  15. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  16. package/dist/auth/require-service-crossing.js +2 -117
  17. package/dist/auth/require-service-crossing.js.map +1 -1
  18. package/dist/auth/shared-token.d.ts +0 -15
  19. package/dist/auth/shared-token.d.ts.map +1 -1
  20. package/dist/auth/shared-token.js +0 -25
  21. package/dist/auth/shared-token.js.map +1 -1
  22. package/dist/http-api/build-api.d.ts.map +1 -1
  23. package/dist/http-api/build-api.js +1 -1
  24. package/dist/http-api/build-api.js.map +1 -1
  25. package/dist/http-api/entity-api.d.ts.map +1 -1
  26. package/dist/http-api/entity-api.js +6 -2
  27. package/dist/http-api/entity-api.js.map +1 -1
  28. package/dist/index.d.ts +0 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +0 -4
  31. package/dist/index.js.map +1 -1
  32. package/dist/load-remote-configuration.d.ts +4 -4
  33. package/dist/load-remote-configuration.d.ts.map +1 -1
  34. package/dist/load-remote-configuration.js +7 -14
  35. package/dist/load-remote-configuration.js.map +1 -1
  36. package/dist/observability.d.ts +2 -2
  37. package/dist/observability.d.ts.map +1 -1
  38. package/dist/observability.js.map +1 -1
  39. package/dist/push/index.d.ts +9 -0
  40. package/dist/push/index.d.ts.map +1 -0
  41. package/dist/push/index.js +9 -0
  42. package/dist/push/index.js.map +1 -0
  43. package/dist/push/server-push.d.ts +82 -0
  44. package/dist/push/server-push.d.ts.map +1 -0
  45. package/dist/push/server-push.js +48 -0
  46. package/dist/push/server-push.js.map +1 -0
  47. package/dist/push/sse.d.ts +62 -0
  48. package/dist/push/sse.d.ts.map +1 -0
  49. package/dist/push/sse.js +120 -0
  50. package/dist/push/sse.js.map +1 -0
  51. package/dist/respond.d.ts +1 -7
  52. package/dist/respond.d.ts.map +1 -1
  53. package/dist/respond.js +1 -8
  54. package/dist/respond.js.map +1 -1
  55. package/package.json +23 -13
  56. package/dist/auth/require-organization.d.ts +0 -32
  57. package/dist/auth/require-organization.d.ts.map +0 -1
  58. package/dist/auth/require-organization.js +0 -52
  59. package/dist/auth/require-organization.js.map +0 -1
  60. package/dist/entity-facet-routes.d.ts +0 -44
  61. package/dist/entity-facet-routes.d.ts.map +0 -1
  62. package/dist/entity-facet-routes.js +0 -70
  63. package/dist/entity-facet-routes.js.map +0 -1
  64. package/dist/entity-metadata-route.d.ts +0 -25
  65. package/dist/entity-metadata-route.d.ts.map +0 -1
  66. package/dist/entity-metadata-route.js +0 -102
  67. package/dist/entity-metadata-route.js.map +0 -1
  68. package/dist/entity-route-guard.d.ts +0 -62
  69. package/dist/entity-route-guard.d.ts.map +0 -1
  70. package/dist/entity-route-guard.js +0 -35
  71. package/dist/entity-route-guard.js.map +0 -1
  72. package/dist/entity-routes.d.ts +0 -76
  73. package/dist/entity-routes.d.ts.map +0 -1
  74. package/dist/entity-routes.js +0 -267
  75. package/dist/entity-routes.js.map +0 -1
  76. package/dist/route-responses.d.ts +0 -44
  77. package/dist/route-responses.d.ts.map +0 -1
  78. package/dist/route-responses.js +0 -104
  79. package/dist/route-responses.js.map +0 -1
  80. package/dist/sse.d.ts +0 -43
  81. package/dist/sse.d.ts.map +0 -1
  82. package/dist/sse.js +0 -78
  83. package/dist/sse.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/respond.ts"],"sourcesContent":["import {\n DEADLINE_HEADER,\n deadlineFromHeader,\n DeadlineTag,\n type EntifixFailure,\n type FailureCategory,\n Internal,\n isFailure,\n NotFound,\n PROBLEM_CONTENT_TYPE,\n problemOf,\n} from '@entifix/core';\nimport { Cause, Clock, Effect, Option } from 'effect';\nimport type { HttpBody } from 'effect/http';\nimport {\n HttpRouter,\n HttpServerError,\n HttpServerRequest,\n HttpServerResponse,\n} from 'effect/http';\nimport type { Severity } from 'effect/LogLevel';\n\n/**\n * What a mounted handler may fail with: a categorised failure, or the\n * response body failing to encode. Anything else — a plain `Error`, a string —\n * does not compile at the mount, which is the point: a failure the shell cannot\n * categorise is one it cannot answer honestly\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n */\nexport type RouteFailure = EntifixFailure | HttpBody.HttpBodyError;\n\n/**\n * How a host answers and logs its failures: the status a category answers with\n * and the level it is logged at, each overridable per tag.\n *\n * The composition root owns it. A cell never decides a status, a retry or a\n * log line; it fails, and the shell's policy says what that means.\n */\nexport interface FailurePolicy {\n readonly categoryStatus: Readonly<Record<FailureCategory, number>>;\n readonly tagStatus: Readonly<Record<string, number>>;\n readonly categoryLogLevel: Readonly<Record<FailureCategory, Severity>>;\n readonly tagLogLevel: Readonly<Record<string, Severity>>;\n}\n\n/**\n * The defaults: the category table's statuses, business failures at `Debug`\n * because an answer is not an incident, the transient technical categories at\n * `Warn`, and what is broken — a peer speaking nonsense, a bug — at `Error`.\n */\nexport const defaultFailurePolicy: FailurePolicy = {\n categoryStatus: {\n invalid: 400,\n unauthenticated: 401,\n forbidden: 403,\n notFound: 404,\n conflict: 409,\n declined: 422,\n contention: 409,\n exhausted: 429,\n unavailable: 503,\n timeout: 504,\n protocol: 502,\n internal: 500,\n },\n tagStatus: {},\n categoryLogLevel: {\n invalid: 'Debug',\n unauthenticated: 'Debug',\n forbidden: 'Debug',\n notFound: 'Debug',\n conflict: 'Debug',\n declined: 'Debug',\n contention: 'Warn',\n exhausted: 'Warn',\n unavailable: 'Warn',\n timeout: 'Warn',\n protocol: 'Error',\n internal: 'Error',\n },\n tagLogLevel: {},\n};\n\nexport interface FailurePolicyOverrides {\n readonly categoryStatus?: Partial<Record<FailureCategory, number>>;\n readonly tagStatus?: Readonly<Record<string, number>>;\n readonly categoryLogLevel?: Partial<Record<FailureCategory, Severity>>;\n readonly tagLogLevel?: Readonly<Record<string, Severity>>;\n}\n\n/** A policy with some of its entries replaced — how a slice extends the fleet's. */\nexport const extendFailurePolicy = (\n base: FailurePolicy,\n overrides: FailurePolicyOverrides,\n): FailurePolicy => ({\n categoryStatus: { ...base.categoryStatus, ...overrides.categoryStatus },\n tagStatus: { ...base.tagStatus, ...overrides.tagStatus },\n categoryLogLevel: {\n ...base.categoryLogLevel,\n ...overrides.categoryLogLevel,\n },\n tagLogLevel: { ...base.tagLogLevel, ...overrides.tagLogLevel },\n});\n\nexport const statusFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failure._tag] ?? policy.categoryStatus[failure.category];\n\nexport const logLevelFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): Severity =>\n policy.tagLogLevel[failure._tag] ?? policy.categoryLogLevel[failure.category];\n\nexport interface ProblemResponseOptions {\n readonly traceId?: string | undefined;\n readonly instance?: string | undefined;\n}\n\nconst retryAfterOf = (failure: EntifixFailure): number | undefined => {\n const seconds = (failure as { readonly retryAfterSeconds?: unknown })\n .retryAfterSeconds;\n return typeof seconds === 'number' ? seconds : undefined;\n};\n\n/**\n * The `application/problem+json` answer to a failure, with the policy's\n * status. Built synchronously — the body is already plain data — so it cannot\n * itself fail to encode.\n */\nexport const problemResponse = (\n failure: EntifixFailure,\n policy: FailurePolicy = defaultFailurePolicy,\n options: ProblemResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const status = statusFor(failure, policy);\n const retryAfter = retryAfterOf(failure);\n return HttpServerResponse.text(\n JSON.stringify(\n problemOf(failure, {\n status,\n ...(options.traceId === undefined ? {} : { traceId: options.traceId }),\n ...(options.instance === undefined\n ? {}\n : { instance: options.instance }),\n }),\n ),\n {\n status,\n contentType: PROBLEM_CONTENT_TYPE,\n ...(retryAfter === undefined\n ? {}\n : { headers: { 'retry-after': String(retryAfter) } }),\n },\n );\n};\n\n/** The current span's trace id, when a span is open. */\nconst currentTraceId: Effect.Effect<string | undefined> = Effect.option(\n Effect.currentSpan,\n).pipe(\n Effect.map(span => Option.getOrUndefined(Option.map(span, s => s.traceId))),\n);\n\n/** The path being answered, when a request is in scope. */\nconst currentInstance: Effect.Effect<string | undefined> = Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n).pipe(\n Effect.map(request =>\n Option.getOrUndefined(Option.map(request, r => r.url.split('?')[0])),\n ),\n);\n\nconst answerFailure = (failure: EntifixFailure, policy: FailurePolicy) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logWithLevel(logLevelFor(failure, policy))(\n 'request failed',\n ).pipe(\n Effect.annotateLogs({\n code: failure.code,\n category: failure.category,\n tag: failure._tag,\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(failure, policy, { traceId, instance });\n });\n\n/**\n * The opaque `500` for anything nobody categorised. The defect is logged in\n * full here, where it was caught; the body carries the trace id to find that\n * line by, and nothing of the defect itself.\n */\nconst answerDefect = (defect: unknown) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logError('request defect').pipe(\n Effect.annotateLogs({\n code: 'internal',\n category: 'internal',\n cause: Cause.pretty(Cause.die(defect)),\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(new Internal(), defaultFailurePolicy, {\n traceId,\n instance,\n });\n });\n\n/**\n * The request's deadline, when its caller sent one, provided to the handler\n * so a retry below it never starts past it and an outbound call forwards what\n * is left ([ADR 0014](../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst withRequestDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n );\n const now = yield* Clock.currentTimeMillis;\n const deadline = Option.isSome(request)\n ? deadlineFromHeader(request.value.headers[DEADLINE_HEADER], now)\n : undefined;\n return yield* deadline === undefined\n ? effect\n : Effect.provideService(effect, DeadlineTag, deadline);\n });\n\n/**\n * The terminal reaction: every failure answered as a problem body with the\n * policy's status and logged at the policy's level, every defect answered as\n * an opaque `500`. Interruption is left alone — a request whose client went\n * away has nobody to answer.\n */\nexport const respond = <E extends RouteFailure, R>(\n effect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n policy: FailurePolicy = defaultFailurePolicy,\n): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R> =>\n withRequestDeadline(effect).pipe(\n Effect.catch((failure: E) =>\n isFailure(failure)\n ? answerFailure(failure, policy)\n : answerDefect(failure),\n ),\n Effect.catchDefect(answerDefect),\n );\n\n/**\n * Mounts a set of routes with every handler wrapped in {@link respond}, once,\n * at the composition root. A route whose handler fails with anything but a\n * {@link RouteFailure} does not compile here.\n */\nexport const mountRoutes = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Routes extends ReadonlyArray<HttpRouter.Route<RouteFailure, any>>,\n>(\n routes: Routes,\n policy: FailurePolicy = defaultFailurePolicy,\n) =>\n HttpRouter.addAll(\n routes.map(route =>\n HttpRouter.route(\n route.method,\n route.path,\n respond(route.handler, policy),\n {\n uninterruptible: route.uninterruptible,\n },\n ),\n ) as unknown as {\n readonly [K in keyof Routes]: HttpRouter.Route<\n never,\n HttpRouter.Route.Context<Routes[K]>\n >;\n },\n );\n\n/**\n * The router's last net. A path no route matches answers a `404` problem\n * rather than an empty body, and a defect that escaped every route — one not\n * mounted through {@link mountRoutes}, or one thrown while a response was\n * being written — answers the same opaque `500` problem. It catches those two\n * and nothing else, never the whole cause, so an interruption still\n * interrupts.\n */\nexport const problemNet = HttpRouter.middleware(\n effect =>\n effect.pipe(\n Effect.catchIf(\n (error: unknown) =>\n HttpServerError.isHttpServerError(error) &&\n error.reason._tag === 'RouteNotFound',\n () =>\n Effect.map(currentInstance, instance =>\n problemResponse(new NotFound({}), defaultFailurePolicy, {\n instance,\n }),\n ),\n ),\n Effect.catchDefect(answerDefect),\n ),\n { global: true },\n);\n\n/**\n * What a mechanism reports instead of logging — a relay pass, a shutdown drain\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n * Structural, so the shell can log an outcome from a package it does not\n * depend on.\n */\nexport interface MechanismOutcome {\n readonly _tag: string;\n readonly failure?: unknown;\n readonly [field: string]: unknown;\n}\n\n/** The level each outcome is logged at; anything unnamed is `Debug`. */\nexport const MECHANISM_OUTCOME_LEVELS: Readonly<Record<string, Severity>> = {\n quarantined: 'Error',\n sweepFailed: 'Error',\n hookFailed: 'Error',\n drainFailed: 'Warn',\n draining: 'Info',\n drained: 'Debug',\n};\n\n/**\n * The fork site's logger for a mechanism's outcomes: the level from the\n * outcome's tag, the outcome's own fields as annotations, and a typed\n * failure's code and category beside them — never `String(error)`.\n */\nexport const logMechanismOutcome = (\n outcome: MechanismOutcome,\n): Effect.Effect<void> => {\n const { _tag, failure, ...fields } = outcome;\n const typed = isFailure(failure)\n ? { code: failure.code, category: failure.category, tag: failure._tag }\n : failure === undefined\n ? {}\n : { code: 'internal', category: 'internal' };\n return Effect.logWithLevel(MECHANISM_OUTCOME_LEVELS[_tag] ?? 'Debug')(\n _tag,\n ).pipe(Effect.annotateLogs({ ...fields, ...typed }));\n};\n"],"names":["DEADLINE_HEADER","deadlineFromHeader","DeadlineTag","Internal","isFailure","NotFound","PROBLEM_CONTENT_TYPE","problemOf","Cause","Clock","Effect","Option","HttpRouter","HttpServerError","HttpServerRequest","HttpServerResponse","defaultFailurePolicy","categoryStatus","invalid","unauthenticated","forbidden","notFound","conflict","declined","contention","exhausted","unavailable","timeout","protocol","internal","tagStatus","categoryLogLevel","tagLogLevel","extendFailurePolicy","base","overrides","statusFor","failure","policy","_tag","category","logLevelFor","retryAfterOf","seconds","retryAfterSeconds","undefined","problemResponse","options","status","retryAfter","text","JSON","stringify","traceId","instance","contentType","headers","String","currentTraceId","option","currentSpan","pipe","map","span","getOrUndefined","s","currentInstance","serviceOption","request","r","url","split","answerFailure","gen","logWithLevel","annotateLogs","code","tag","answerDefect","defect","logError","cause","pretty","die","withRequestDeadline","effect","now","currentTimeMillis","deadline","isSome","value","provideService","respond","catch","catchDefect","mountRoutes","routes","addAll","route","method","path","handler","uninterruptible","problemNet","middleware","catchIf","error","isHttpServerError","reason","global","MECHANISM_OUTCOME_LEVELS","quarantined","sweepFailed","hookFailed","drainFailed","draining","drained","logMechanismOutcome","outcome","fields","typed"],"mappings":";;AAAA,SACEA,eAAe,EACfC,kBAAkB,EAClBC,WAAW,EAGXC,QAAQ,EACRC,SAAS,EACTC,QAAQ,EACRC,oBAAoB,EACpBC,SAAS,QACJ,gBAAgB;AACvB,SAASC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAEtD,SACEC,UAAU,EACVC,eAAe,EACfC,iBAAiB,EACjBC,kBAAkB,QACb,cAAc;AA0BrB;;;;CAIC,GACD,OAAO,MAAMC,uBAAsC;IACjDC,gBAAgB;QACdC,SAAS;QACTC,iBAAiB;QACjBC,WAAW;QACXC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,YAAY;QACZC,WAAW;QACXC,aAAa;QACbC,SAAS;QACTC,UAAU;QACVC,UAAU;IACZ;IACAC,WAAW,CAAC;IACZC,kBAAkB;QAChBb,SAAS;QACTC,iBAAiB;QACjBC,WAAW;QACXC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,YAAY;QACZC,WAAW;QACXC,aAAa;QACbC,SAAS;QACTC,UA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8F,iBAAiB,CAACD,UAClCA,MAAME,MAAM,CAACrE,IAAI,KAAK,iBACxB,IACE7B,OAAOoD,GAAG,CAACI,iBAAiBZ,CAAAA,WAC1BR,gBAAgB,IAAIzC,SAAS,CAAC,IAAIW,sBAAsB;gBACtDsC;YACF,MAGN5C,OAAOoF,WAAW,CAAChB,gBAEvB;IAAE+B,QAAQ;AAAK,GACf;AAcF,sEAAsE,GACtE,OAAO,MAAMC,2BAA+D;IAC1EC,aAAa;IACbC,aAAa;IACbC,YAAY;IACZC,aAAa;IACbC,UAAU;IACVC,SAAS;AACX,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAMC,sBAAsB,CACjCC;QAQ2BR;IAN3B,MAAM,EAAEvE,IAAI,EAAEF,OAAO,EAAa,GAAGiF,SAAXC,0CAAWD;;;;IACrC,MAAME,QAAQpH,UAAUiC,WACpB;QAAEuC,MAAMvC,QAAQuC,IAAI;QAAEpC,UAAUH,QAAQG,QAAQ;QAAEqC,KAAKxC,QAAQE,IAAI;IAAC,IACpEF,YAAYQ,YACV,CAAC,IACD;QAAE+B,MAAM;QAAYpC,UAAU;IAAW;IAC/C,OAAO9B,OAAOgE,YAAY,EAACoC,iCAAAA,wBAAwB,CAACvE,KAAK,YAA9BuE,iCAAkC,SAC3DvE,MACAsB,IAAI,CAACnD,OAAOiE,YAAY,CAAC,aAAK4C,QAAWC;AAC7C,EAAE"}
1
+ {"version":3,"sources":["../src/respond.ts"],"sourcesContent":["import {\n DEADLINE_HEADER,\n deadlineFromHeader,\n DeadlineTag,\n type EntifixFailure,\n type FailureCategory,\n Internal,\n isFailure,\n NotFound,\n PROBLEM_CONTENT_TYPE,\n problemOf,\n} from '@entifix/core';\nimport { Cause, Clock, Effect, Option } from 'effect';\nimport type { HttpBody } from 'effect/http';\nimport {\n HttpRouter,\n HttpServerError,\n HttpServerRequest,\n HttpServerResponse,\n} from 'effect/http';\nimport type { Severity } from 'effect/LogLevel';\n\n/**\n * What a mounted handler may fail with: a categorised failure, or the\n * response body failing to encode. Anything else — a plain `Error`, a string —\n * does not compile at the mount, which is the point: a failure the shell cannot\n * categorise is one it cannot answer honestly\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n */\nexport type RouteFailure = EntifixFailure | HttpBody.HttpBodyError;\n\n/**\n * How a host answers and logs its failures: the status a category answers with\n * and the level it is logged at, each overridable per tag.\n *\n * The composition root owns it. A cell never decides a status, a retry or a\n * log line; it fails, and the shell's policy says what that means.\n */\nexport interface FailurePolicy {\n readonly categoryStatus: Readonly<Record<FailureCategory, number>>;\n readonly tagStatus: Readonly<Record<string, number>>;\n readonly categoryLogLevel: Readonly<Record<FailureCategory, Severity>>;\n readonly tagLogLevel: Readonly<Record<string, Severity>>;\n}\n\n/**\n * The defaults: the category table's statuses, business failures at `Debug`\n * because an answer is not an incident, the transient technical categories at\n * `Warn`, and what is broken — a peer speaking nonsense, a bug — at `Error`.\n */\nexport const defaultFailurePolicy: FailurePolicy = {\n categoryStatus: {\n invalid: 400,\n unauthenticated: 401,\n forbidden: 403,\n notFound: 404,\n conflict: 409,\n declined: 422,\n contention: 409,\n exhausted: 429,\n unavailable: 503,\n timeout: 504,\n protocol: 502,\n internal: 500,\n },\n tagStatus: {},\n categoryLogLevel: {\n invalid: 'Debug',\n unauthenticated: 'Debug',\n forbidden: 'Debug',\n notFound: 'Debug',\n conflict: 'Debug',\n declined: 'Debug',\n contention: 'Warn',\n exhausted: 'Warn',\n unavailable: 'Warn',\n timeout: 'Warn',\n protocol: 'Error',\n internal: 'Error',\n },\n tagLogLevel: {},\n};\n\nexport interface FailurePolicyOverrides {\n readonly categoryStatus?: Partial<Record<FailureCategory, number>>;\n readonly tagStatus?: Readonly<Record<string, number>>;\n readonly categoryLogLevel?: Partial<Record<FailureCategory, Severity>>;\n readonly tagLogLevel?: Readonly<Record<string, Severity>>;\n}\n\n/** A policy with some of its entries replaced — how a slice extends the fleet's. */\nexport const extendFailurePolicy = (\n base: FailurePolicy,\n overrides: FailurePolicyOverrides,\n): FailurePolicy => ({\n categoryStatus: { ...base.categoryStatus, ...overrides.categoryStatus },\n tagStatus: { ...base.tagStatus, ...overrides.tagStatus },\n categoryLogLevel: {\n ...base.categoryLogLevel,\n ...overrides.categoryLogLevel,\n },\n tagLogLevel: { ...base.tagLogLevel, ...overrides.tagLogLevel },\n});\n\nexport const statusFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failure._tag] ?? policy.categoryStatus[failure.category];\n\nexport const logLevelFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): Severity =>\n policy.tagLogLevel[failure._tag] ?? policy.categoryLogLevel[failure.category];\n\nexport interface ProblemResponseOptions {\n readonly traceId?: string | undefined;\n readonly instance?: string | undefined;\n}\n\nconst retryAfterOf = (failure: EntifixFailure): number | undefined => {\n const seconds = (failure as { readonly retryAfterSeconds?: unknown })\n .retryAfterSeconds;\n return typeof seconds === 'number' ? seconds : undefined;\n};\n\n/**\n * The `application/problem+json` answer to a failure, with the policy's\n * status. Built synchronously — the body is already plain data — so it cannot\n * itself fail to encode.\n */\nexport const problemResponse = (\n failure: EntifixFailure,\n policy: FailurePolicy = defaultFailurePolicy,\n options: ProblemResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const status = statusFor(failure, policy);\n const retryAfter = retryAfterOf(failure);\n return HttpServerResponse.text(\n JSON.stringify(\n problemOf(failure, {\n status,\n ...(options.traceId === undefined ? {} : { traceId: options.traceId }),\n ...(options.instance === undefined\n ? {}\n : { instance: options.instance }),\n }),\n ),\n {\n status,\n contentType: PROBLEM_CONTENT_TYPE,\n ...(retryAfter === undefined\n ? {}\n : { headers: { 'retry-after': String(retryAfter) } }),\n },\n );\n};\n\n/** The current span's trace id, when a span is open. */\nconst currentTraceId: Effect.Effect<string | undefined> = Effect.option(\n Effect.currentSpan,\n).pipe(\n Effect.map(span => Option.getOrUndefined(Option.map(span, s => s.traceId))),\n);\n\n/** The path being answered, when a request is in scope. */\nconst currentInstance: Effect.Effect<string | undefined> = Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n).pipe(\n Effect.map(request =>\n Option.getOrUndefined(Option.map(request, r => r.url.split('?')[0])),\n ),\n);\n\nconst answerFailure = (failure: EntifixFailure, policy: FailurePolicy) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logWithLevel(logLevelFor(failure, policy))(\n 'request failed',\n ).pipe(\n Effect.annotateLogs({\n code: failure.code,\n category: failure.category,\n tag: failure._tag,\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(failure, policy, { traceId, instance });\n });\n\n/**\n * The opaque `500` for anything nobody categorised. The defect is logged in\n * full here, where it was caught; the body carries the trace id to find that\n * line by, and nothing of the defect itself.\n */\nconst answerDefect = (defect: unknown) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logError('request defect').pipe(\n Effect.annotateLogs({\n code: 'internal',\n category: 'internal',\n cause: Cause.pretty(Cause.die(defect)),\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(new Internal(), defaultFailurePolicy, {\n traceId,\n instance,\n });\n });\n\n/**\n * The request's deadline, when its caller sent one, provided to the handler\n * so a retry below it never starts past it and an outbound call forwards what\n * is left ([ADR 0014](../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst withRequestDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n );\n const now = yield* Clock.currentTimeMillis;\n const deadline = Option.isSome(request)\n ? deadlineFromHeader(request.value.headers[DEADLINE_HEADER], now)\n : undefined;\n return yield* deadline === undefined\n ? effect\n : Effect.provideService(effect, DeadlineTag, deadline);\n });\n\n/**\n * The terminal reaction: every failure answered as a problem body with the\n * policy's status and logged at the policy's level, every defect answered as\n * an opaque `500`. Interruption is left alone — a request whose client went\n * away has nobody to answer.\n */\nexport const respond = <E extends RouteFailure, R>(\n effect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n policy: FailurePolicy = defaultFailurePolicy,\n): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R> =>\n withRequestDeadline(effect).pipe(\n Effect.catch((failure: E) =>\n isFailure(failure)\n ? answerFailure(failure, policy)\n : answerDefect(failure),\n ),\n Effect.catchDefect(answerDefect),\n );\n\n/**\n * The router's last net. A path no route matches answers a `404` problem\n * rather than an empty body, and a defect that escaped every route — one not\n * wrapped in {@link respond}, or one thrown while a response was\n * being written — answers the same opaque `500` problem. It catches those two\n * and nothing else, never the whole cause, so an interruption still\n * interrupts.\n */\nexport const problemNet = HttpRouter.middleware(\n effect =>\n effect.pipe(\n Effect.catchIf(\n (error: unknown) =>\n HttpServerError.isHttpServerError(error) &&\n error.reason._tag === 'RouteNotFound',\n () =>\n Effect.map(currentInstance, instance =>\n problemResponse(new NotFound({}), defaultFailurePolicy, {\n instance,\n }),\n ),\n ),\n Effect.catchDefect(answerDefect),\n ),\n { global: true },\n);\n\n/**\n * What a mechanism reports instead of logging — a relay pass, a shutdown drain\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n * Structural, so the shell can log an outcome from a package it does not\n * depend on.\n */\nexport interface MechanismOutcome {\n readonly _tag: string;\n readonly failure?: unknown;\n readonly [field: string]: unknown;\n}\n\n/** The level each outcome is logged at; anything unnamed is `Debug`. */\nexport const MECHANISM_OUTCOME_LEVELS: Readonly<Record<string, Severity>> = {\n quarantined: 'Error',\n sweepFailed: 'Error',\n hookFailed: 'Error',\n drainFailed: 'Warn',\n draining: 'Info',\n drained: 'Debug',\n};\n\n/**\n * The fork site's logger for a mechanism's outcomes: the level from the\n * outcome's tag, the outcome's own fields as annotations, and a typed\n * failure's code and category beside them — never `String(error)`.\n */\nexport const logMechanismOutcome = (\n outcome: MechanismOutcome,\n): Effect.Effect<void> => {\n const { _tag, failure, ...fields } = outcome;\n const typed = isFailure(failure)\n ? { code: failure.code, category: failure.category, tag: failure._tag }\n : failure === undefined\n ? {}\n : { code: 'internal', category: 'internal' };\n return Effect.logWithLevel(MECHANISM_OUTCOME_LEVELS[_tag] ?? 'Debug')(\n _tag,\n ).pipe(Effect.annotateLogs({ ...fields, ...typed }));\n};\n"],"names":["DEADLINE_HEADER","deadlineFromHeader","DeadlineTag","Internal","isFailure","NotFound","PROBLEM_CONTENT_TYPE","problemOf","Cause","Clock","Effect","Option","HttpRouter","HttpServerError","HttpServerRequest","HttpServerResponse","defaultFailurePolicy","categoryStatus","invalid","unauthenticated","forbidden","notFound","conflict","declined","contention","exhausted","unavailable","timeout","protocol","internal","tagStatus","categoryLogLevel","tagLogLevel","extendFailurePolicy","base","overrides","statusFor","failure","policy","_tag","category","logLevelFor","retryAfterOf","seconds","retryAfterSeconds","undefined","problemResponse","options","status","retryAfter","text","JSON","stringify","traceId","instance","contentType","headers","String","currentTraceId","option","currentSpan","pipe","map","span","getOrUndefined","s","currentInstance","serviceOption","request","r","url","split","answerFailure","gen","logWithLevel","annotateLogs","code","tag","answerDefect","defect","logError","cause","pretty","die","withRequestDeadline","effect","now","currentTimeMillis","deadline","isSome","value","provideService","respond","catch","catchDefect","problemNet","middleware","catchIf","error","isHttpServerError","reason","global","MECHANISM_OUTCOME_LEVELS","quarantined","sweepFailed","hookFailed","drainFailed","draining","drained","logMechanismOutcome","outcome","fields","typed"],"mappings":";;AAAA,SACEA,eAAe,EACfC,kBAAkB,EAClBC,WAAW,EAGXC,QAAQ,EACRC,SAAS,EACTC,QAAQ,EACRC,oBAAoB,EACpBC,SAAS,QACJ,gBAAgB;AACvB,SAASC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAEtD,SACEC,UAAU,EACVC,eAAe,EACfC,iBAAiB,EACjBC,kBAAkB,QACb,cAAc;AA0BrB;;;;CAIC,GACD,OAA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AAA,SACEA,OAAOxB,IAAI,CACTnD,OAAOuF,OAAO,CACZ,CAACC,QACCrF,gBAAgBsF,iBAAiB,CAACD,UAClCA,MAAME,MAAM,CAAC7D,IAAI,KAAK,iBACxB,IACE7B,OAAOoD,GAAG,CAACI,iBAAiBZ,CAAAA,WAC1BR,gBAAgB,IAAIzC,SAAS,CAAC,IAAIW,sBAAsB;gBACtDsC;YACF,MAGN5C,OAAOoF,WAAW,CAAChB,gBAEvB;IAAEuB,QAAQ;AAAK,GACf;AAcF,sEAAsE,GACtE,OAAO,MAAMC,2BAA+D;IAC1EC,aAAa;IACbC,aAAa;IACbC,YAAY;IACZC,aAAa;IACbC,UAAU;IACVC,SAAS;AACX,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAMC,sBAAsB,CACjCC;QAQ2BR;IAN3B,MAAM,EAAE/D,IAAI,EAAEF,OAAO,EAAa,GAAGyE,SAAXC,0CAAWD;;;;IACrC,MAAME,QAAQ5G,UAAUiC,WACpB;QAAEuC,MAAMvC,QAAQuC,IAAI;QAAEpC,UAAUH,QAAQG,QAAQ;QAAEqC,KAAKxC,QAAQE,IAAI;IAAC,IACpEF,YAAYQ,YACV,CAAC,IACD;QAAE+B,MAAM;QAAYpC,UAAU;IAAW;IAC/C,OAAO9B,OAAOgE,YAAY,EAAC4B,iCAAAA,wBAAwB,CAAC/D,KAAK,YAA9B+D,iCAAkC,SAC3D/D,MACAsB,IAAI,CAACnD,OAAOiE,YAAY,CAAC,aAAKoC,QAAWC;AAC7C,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/service-shell",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Effect HTTP service skeleton: server layer, health and metadata routes, permission guards, remote configuration and OpenTelemetry.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,6 +37,16 @@
37
37
  "import": "./dist/observability.js",
38
38
  "default": "./dist/observability.js"
39
39
  },
40
+ "./push": {
41
+ "types": "./dist/push/index.d.ts",
42
+ "import": "./dist/push/index.js",
43
+ "default": "./dist/push/index.js"
44
+ },
45
+ "./push/sse": {
46
+ "types": "./dist/push/sse.d.ts",
47
+ "import": "./dist/push/sse.js",
48
+ "default": "./dist/push/sse.js"
49
+ },
40
50
  "./testing": {
41
51
  "types": "./dist/testing.d.ts",
42
52
  "import": "./dist/testing.js",
@@ -66,34 +76,34 @@
66
76
  },
67
77
  "dependencies": {
68
78
  "@swc/helpers": "0.5.23",
69
- "@entifix/authz": "0.13.0",
70
- "@entifix/business": "0.13.0",
71
- "@entifix/core": "0.13.0",
72
- "@entifix/tooling": "0.13.0"
79
+ "@entifix/business": "0.15.0",
80
+ "@entifix/core": "0.15.0",
81
+ "@entifix/tooling": "0.15.0",
82
+ "@entifix/authz": "0.15.0"
73
83
  },
74
84
  "devDependencies": {
75
- "@effect/opentelemetry": "4.0.6",
76
- "@effect/platform-node": "4.0.6",
85
+ "@effect/opentelemetry": "4.0.7",
86
+ "@effect/platform-node": "4.0.7",
77
87
  "@opentelemetry/api": "1.9.1",
78
88
  "@opentelemetry/context-async-hooks": "2.12.0",
79
89
  "@opentelemetry/exporter-metrics-otlp-http": "0.223.0",
80
90
  "@opentelemetry/exporter-trace-otlp-http": "0.223.0",
81
91
  "@opentelemetry/sdk-metrics": "2.12.0",
82
92
  "@opentelemetry/sdk-trace-base": "2.12.0",
83
- "effect": "4.0.6",
84
- "@entifix/rest": "0.13.0",
85
- "@entifix/testing-unit": "0.13.0"
93
+ "effect": "4.0.7",
94
+ "@entifix/rest": "0.15.0",
95
+ "@entifix/testing-unit": "0.15.0"
86
96
  },
87
97
  "peerDependencies": {
88
- "@effect/opentelemetry": "^4.0.6",
89
- "@effect/platform-node": "^4.0.6",
98
+ "@effect/opentelemetry": "^4.0.7",
99
+ "@effect/platform-node": "^4.0.7",
90
100
  "@opentelemetry/api": ">=1.9 <2",
91
101
  "@opentelemetry/context-async-hooks": ">=2.12 <3",
92
102
  "@opentelemetry/exporter-metrics-otlp-http": ">=0.223 <0.224",
93
103
  "@opentelemetry/exporter-trace-otlp-http": ">=0.223 <0.224",
94
104
  "@opentelemetry/sdk-metrics": ">=2.12 <3",
95
105
  "@opentelemetry/sdk-trace-base": ">=2.12 <3",
96
- "effect": "^4.0.6"
106
+ "effect": "^4.0.7"
97
107
  },
98
108
  "peerDependenciesMeta": {
99
109
  "@effect/opentelemetry": {
@@ -1,32 +0,0 @@
1
- import type { Permission } from '@entifix/authz';
2
- import type { RequestPrincipal } from '@entifix/business';
3
- import { Effect } from 'effect';
4
- /**
5
- * Guard a **tenant-plane** handler: authenticate, check the permission, and
6
- * require that the session names an organization.
7
- *
8
- * **This is the first of exactly two ways a request resolves the organization
9
- * it acts for, and the only *user-facing* one**.
10
- * The second is {@link requireServiceCrossing}: an explicit `organizationId`
11
- * presented with a service token *and* a narrow route permission, for a
12
- * platform-plane caller acting for an organization it was handed rather than one
13
- * it picked.
14
- *
15
- * There is no third path, no fallback and no operator branch. A request
16
- * satisfying neither guard never reaches a tenant handle at all, which is what
17
- * keeps the most sensitive capability in the system from being the *absence* of
18
- * a condition.
19
- *
20
- * The organization is handed to the handler so it can resolve its own storage
21
- * through a `TenantDatabaseResolver`. Resolution happens **inside the request**
22
- * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would
23
- * rebuild the pool per request.
24
- *
25
- * Here the value comes from the verified token and nowhere else. A route
26
- * parameter or a body field naming an organization would be caller-controlled,
27
- * which is the whole failure this guard exists to prevent — and is exactly why
28
- * the other path honours a caller-named organization only *after* the caller has
29
- * proved it is the fleet.
30
- */
31
- export declare const requireOrganization: (permission: Permission) => <A, E, R>(use: (organizationId: string, principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, import("@entifix/business").TokenServiceTag | import("@entifix/authz").PolicyDecisionTag | import("effect/http/HttpServerRequest").HttpServerRequest | R>;
32
- //# sourceMappingURL=require-organization.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"require-organization.d.ts","sourceRoot":"","sources":["../../src/auth/require-organization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAkBhC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,mBAAmB,GAC7B,YAAY,UAAU,MACtB,CAAC,EAAE,CAAC,EAAE,CAAC,EACN,KAAK,CACH,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,gBAAgB,KACxB,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,gPAa1B,CAAC"}
@@ -1,52 +0,0 @@
1
- import { Effect } from 'effect';
2
- import { NoActiveOrganization, refuse } from './failures.js';
3
- import { requirePermission } from './require-principal.js';
4
- /**
5
- * `409` rather than `403`: the caller is authenticated and permitted, but the
6
- * session names no organization, so there is no storage to read. An operator
7
- * hits this by design — crossing into a tenant is an explicit, audited
8
- * act-as-organization re-mint, never a widening of the default —
9
- * and a member of several organizations hits it before choosing one. The `code`
10
- * is a key in the shared `errors` catalog, so a client renders "select an
11
- * organization" instead of "forbidden" — a claim a host has to check its
12
- * catalog against, because for a while it was simply false and the code
13
- * reached the browser as its own literal text.
14
- */ const noOrganization = refuse(new NoActiveOrganization());
15
- /**
16
- * Guard a **tenant-plane** handler: authenticate, check the permission, and
17
- * require that the session names an organization.
18
- *
19
- * **This is the first of exactly two ways a request resolves the organization
20
- * it acts for, and the only *user-facing* one**.
21
- * The second is {@link requireServiceCrossing}: an explicit `organizationId`
22
- * presented with a service token *and* a narrow route permission, for a
23
- * platform-plane caller acting for an organization it was handed rather than one
24
- * it picked.
25
- *
26
- * There is no third path, no fallback and no operator branch. A request
27
- * satisfying neither guard never reaches a tenant handle at all, which is what
28
- * keeps the most sensitive capability in the system from being the *absence* of
29
- * a condition.
30
- *
31
- * The organization is handed to the handler so it can resolve its own storage
32
- * through a `TenantDatabaseResolver`. Resolution happens **inside the request**
33
- * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would
34
- * rebuild the pool per request.
35
- *
36
- * Here the value comes from the verified token and nowhere else. A route
37
- * parameter or a body field naming an organization would be caller-controlled,
38
- * which is the whole failure this guard exists to prevent — and is exactly why
39
- * the other path honours a caller-named organization only *after* the caller has
40
- * proved it is the fleet.
41
- */ export const requireOrganization = (permission)=>(use)=>requirePermission(permission)((principal)=>// `Effect.gen` rather than a ternary: the two branches have different
42
- // success types, and a conditional expression would unify them against
43
- // the first one instead of widening. `requirePrincipal` yields for the
44
- // same reason.
45
- Effect.gen(function*() {
46
- if (principal.organizationId === undefined) {
47
- return yield* noOrganization;
48
- }
49
- return yield* use(principal.organizationId, principal);
50
- }));
51
-
52
- //# sourceMappingURL=require-organization.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/auth/require-organization.ts"],"sourcesContent":["import type { Permission } from '@entifix/authz';\nimport type { RequestPrincipal } from '@entifix/business';\nimport { Effect } from 'effect';\n\nimport { NoActiveOrganization, refuse } from './failures.js';\nimport { requirePermission } from './require-principal.js';\n\n/**\n * `409` rather than `403`: the caller is authenticated and permitted, but the\n * session names no organization, so there is no storage to read. An operator\n * hits this by design — crossing into a tenant is an explicit, audited\n * act-as-organization re-mint, never a widening of the default —\n * and a member of several organizations hits it before choosing one. The `code`\n * is a key in the shared `errors` catalog, so a client renders \"select an\n * organization\" instead of \"forbidden\" — a claim a host has to check its\n * catalog against, because for a while it was simply false and the code\n * reached the browser as its own literal text.\n */\nconst noOrganization = refuse(new NoActiveOrganization());\n\n/**\n * Guard a **tenant-plane** handler: authenticate, check the permission, and\n * require that the session names an organization.\n *\n * **This is the first of exactly two ways a request resolves the organization\n * it acts for, and the only *user-facing* one**.\n * The second is {@link requireServiceCrossing}: an explicit `organizationId`\n * presented with a service token *and* a narrow route permission, for a\n * platform-plane caller acting for an organization it was handed rather than one\n * it picked.\n *\n * There is no third path, no fallback and no operator branch. A request\n * satisfying neither guard never reaches a tenant handle at all, which is what\n * keeps the most sensitive capability in the system from being the *absence* of\n * a condition.\n *\n * The organization is handed to the handler so it can resolve its own storage\n * through a `TenantDatabaseResolver`. Resolution happens **inside the request**\n * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would\n * rebuild the pool per request.\n *\n * Here the value comes from the verified token and nowhere else. A route\n * parameter or a body field naming an organization would be caller-controlled,\n * which is the whole failure this guard exists to prevent — and is exactly why\n * the other path honours a caller-named organization only *after* the caller has\n * proved it is the fleet.\n */\nexport const requireOrganization =\n (permission: Permission) =>\n <A, E, R>(\n use: (\n organizationId: string,\n principal: RequestPrincipal,\n ) => Effect.Effect<A, E, R>,\n ) =>\n requirePermission(permission)(principal =>\n // `Effect.gen` rather than a ternary: the two branches have different\n // success types, and a conditional expression would unify them against\n // the first one instead of widening. `requirePrincipal` yields for the\n // same reason.\n Effect.gen(function* () {\n if (principal.organizationId === undefined) {\n return yield* noOrganization;\n }\n return yield* use(principal.organizationId, principal);\n }),\n );\n"],"names":["Effect","NoActiveOrganization","refuse","requirePermission","noOrganization","requireOrganization","permission","use","principal","gen","organizationId","undefined"],"mappings":"AAEA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAASC,oBAAoB,EAAEC,MAAM,QAAQ,gBAAgB;AAC7D,SAASC,iBAAiB,QAAQ,yBAAyB;AAE3D;;;;;;;;;;CAUC,GACD,MAAMC,iBAAiBF,OAAO,IAAID;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,MAAMI,sBACX,CAACC,aACD,CACEC,MAKAJ,kBAAkBG,YAAYE,CAAAA,YAC5B,sEAAsE;YACtE,uEAAuE;YACvE,uEAAuE;YACvE,eAAe;YACfR,OAAOS,GAAG,CAAC;gBACT,IAAID,UAAUE,cAAc,KAAKC,WAAW;oBAC1C,OAAO,OAAOP;gBAChB;gBACA,OAAO,OAAOG,IAAIC,UAAUE,cAAc,EAAEF;YAC9C,IACA"}
@@ -1,44 +0,0 @@
1
- import type { NarrowingRules } from '@entifix/business';
2
- import { EntityFacetCounterFactoryTag } from '@entifix/business';
3
- import { type Entity, type EntityConstructor } from '@entifix/core';
4
- import { Effect } from 'effect';
5
- import { HttpRouter } from 'effect/http';
6
- import { type EntityReadScope, type EntityRouteContext, type EntityRouteGuard } from './entity-route-guard.js';
7
- import { type FailurePolicy } from './respond.js';
8
- export interface EntityFacetRoutesOptions<T extends Entity, R, G extends EntityRouteGuard = EntityRouteGuard> {
9
- /** Who may count: the guard the entity's `list` has, as a rule. */
10
- readonly guard: G;
11
- /** Defaults to `/api/<entity key>`; the route is `<basePath>/$facets`. */
12
- readonly basePath?: `/${string}`;
13
- /**
14
- * Narrows the counts to the records this caller may see — the same scope
15
- * the entity's `list` takes, so a count never reveals a record the list
16
- * would not.
17
- */
18
- readonly scope?: (context: EntityRouteContext) => Effect.Effect<EntityReadScope<T>, never, R>;
19
- /**
20
- * The same narrowing the entity's `list` takes, as resolver rules — so a
21
- * count equals the narrowed list. Replaces `scope`; naming both throws.
22
- */
23
- readonly narrowing?: NarrowingRules<T>;
24
- /** How the count's failures are answered and logged. */
25
- readonly policy?: FailurePolicy;
26
- }
27
- /**
28
- * `GET <base>/$facets` — how many of the entity's records hold each value of
29
- * each `facet` member, each under its own `rsql.<member>` filtering — bound to
30
- * storage through the host's {@link EntityFacetCounterFactoryTag}.
31
- *
32
- * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it
33
- * is the one route set that requires a counter: a host that mounts it without
34
- * binding one fails to compile, and a host that never counts binds nothing.
35
- *
36
- * The query is parsed against the entity's metadata, so only a `filterable`
37
- * member is counted and every malformed request is a `400`. A scope is
38
- * **conjoined into every facet's filtering**, never substituted, so no query
39
- * string can count past it; `'none'` answers every member empty.
40
- */
41
- export declare const makeEntityFacetRoutes: <T extends Entity, R = never, const G extends EntityRouteGuard = never>(entityConstructor: EntityConstructor<T>, options: EntityFacetRoutesOptions<T, R, G>) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", import("@entifix/business").TokenServiceTag> | HttpRouter.Request<"Requires", EntityFacetCounterFactoryTag> | HttpRouter.Request<"Requires", import("@entifix/authz").PolicyDecisionTag> | HttpRouter.Request.From<"Requires", Exclude<Exclude<R, HttpRouter.Provided>, HttpRouter.Provided>> | HttpRouter.Request.From<"Requires", Exclude<Exclude<G extends {
42
- readonly kind: "crossing";
43
- } ? import("@entifix/authz").ServiceCrossingPolicyTag | import("./index.js").ServiceCrossingTokenTag : never, HttpRouter.Provided>, HttpRouter.Provided>>>;
44
- //# sourceMappingURL=entity-facet-routes.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"entity-facet-routes.d.ts","sourceRoot":"","sources":["../src/entity-facet-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EACL,4BAA4B,EAG7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,iBAAiB,EAMvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAyC,MAAM,aAAa,CAAC;AAEhF,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EAGtB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,cAAc,CAAC;AAGtB,MAAM,WAAW,wBAAwB,CACvC,CAAC,SAAS,MAAM,EAChB,CAAC,EACD,CAAC,SAAS,gBAAgB,GAAG,gBAAgB;IAE7C,mEAAmE;IACnE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAClB,0EAA0E;IAC1E,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,MAAM,EAAE,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,CACf,OAAO,EAAE,kBAAkB,KACxB,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IACjD;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC;IACvC,wDAAwD;IACxD,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;CACjC;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,qBAAqB,GAChC,CAAC,SAAS,MAAM,EAChB,CAAC,GAAG,KAAK,EAGT,KAAK,CAAC,CAAC,SAAS,gBAAgB,GAAG,KAAK,EAExC,mBAAmB,iBAAiB,CAAC,CAAC,CAAC,EACvC,SAAS,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;0JAyF3C,CAAC"}
@@ -1,70 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { EntityFacetCounterFactoryTag, EntityFacetCounterTag, facetCountsUCFactory } from '@entifix/business';
3
- import { envelopeEntityName, makeEntityFacetsEnvelope, parseFacetQueryParams } from '@entifix/core';
4
- import { Effect } from 'effect';
5
- import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
6
- import { guardRoute } from './entity-route-guard.js';
7
- import { narrowingFor } from './narrowing.js';
8
- import { defaultFailurePolicy, respond } from './respond.js';
9
- import { legacyAnswer } from './route-responses.js';
10
- /**
11
- * `GET <base>/$facets` — how many of the entity's records hold each value of
12
- * each `facet` member, each under its own `rsql.<member>` filtering — bound to
13
- * storage through the host's {@link EntityFacetCounterFactoryTag}.
14
- *
15
- * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it
16
- * is the one route set that requires a counter: a host that mounts it without
17
- * binding one fails to compile, and a host that never counts binds nothing.
18
- *
19
- * The query is parsed against the entity's metadata, so only a `filterable`
20
- * member is counted and every malformed request is a `400`. A scope is
21
- * **conjoined into every facet's filtering**, never substituted, so no query
22
- * string can count past it; `'none'` answers every member empty.
23
- */ export const makeEntityFacetRoutes = (entityConstructor, options)=>{
24
- var _options_basePath, _options_policy;
25
- const base = (_options_basePath = options.basePath) != null ? _options_basePath : `/api/${envelopeEntityName(entityConstructor)}`;
26
- const readQueries = Effect.gen(function*() {
27
- const request = yield* HttpServerRequest.HttpServerRequest;
28
- const search = new URL(request.url, 'http://localhost').searchParams;
29
- return yield* Effect.try({
30
- try: ()=>parseFacetQueryParams(entityConstructor, search),
31
- catch: (error)=>error
32
- });
33
- });
34
- const narrowed = (queries, narrowing)=>narrowing === 'unscoped' ? queries : queries.map((query)=>{
35
- var _query_filtering;
36
- return _extends({}, query, {
37
- filtering: [
38
- ...(_query_filtering = query.filtering) != null ? _query_filtering : [],
39
- narrowing
40
- ]
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;
45
- const count = (context)=>Effect.gen(function*() {
46
- const queries = yield* readQueries;
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') {
49
- // Still parsed: whether a query is well-formed must not depend on who
50
- // asked.
51
- const empty = Object.fromEntries(queries.map(({ member })=>[
52
- member,
53
- []
54
- ]));
55
- return yield* HttpServerResponse.json(makeEntityFacetsEnvelope(entityConstructor, empty));
56
- }
57
- const factory = yield* EntityFacetCounterFactoryTag;
58
- const counter = yield* factory.for(entityConstructor, _extends({}, context.organizationId === undefined ? {} : {
59
- organizationId: context.organizationId
60
- }));
61
- const counts = yield* facetCountsUCFactory(narrowed(queries, narrowing)).pipe(Effect.provideService(EntityFacetCounterTag, counter));
62
- return yield* HttpServerResponse.json(makeEntityFacetsEnvelope(entityConstructor, counts));
63
- }).pipe(Effect.catch(legacyAnswer('invalidQuery')));
64
- const handler = respond(guardRoute(entityConstructor, options.guard, 'read', count), (_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy);
65
- return HttpRouter.addAll([
66
- HttpRouter.route('GET', `${base}/$facets`, handler)
67
- ]);
68
- };
69
-
70
- //# sourceMappingURL=entity-facet-routes.js.map
@@ -1 +0,0 @@
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,eAAe;AACtB,SAASC,YAAY,QAAQ,uBAAuB;AA4BpD;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,wBAAwB,CAOnCC,mBACAC;QAGEA,mBAgFAA;IAjFF,MAAMC,QACJD,oBAAAA,QAAQE,QAAQ,YAAhBF,oBAAoB,CAAC,KAAK,EAAEd,mBAAmBa,oBAAoB;IAErE,MAAMI,cAAcd,OAAOe,GAAG,CAAC;QAC7B,MAAMC,UAAU,OAAOd,kBAAkBA,iBAAiB;QAC1D,MAAMe,SAAS,IAAIC,IAAIF,QAAQG,GAAG,EAAE,oBAAoBC,YAAY;QACpE,OAAO,OAAOpB,OAAOqB,GAAG,CAAC;YACvBA,KAAK,IAAMtB,sBAAsBW,mBAAmBO;YACpDK,OAAOC,CAAAA,QAASA;QAClB;IACF;IAEA,MAAMC,WAAW,CACfC,SACAC,YAEAA,cAAc,aACVD,UACAA,QAAQE,GAAG,CAACC,CAAAA;gBAEMA;mBAFI,aACjBA;gBACHC,WAAW;wBAAKD,mBAAAA,MAAMC,SAAS,YAAfD,mBAAmB,EAAE;oBAAGF;iBAAU;;;IAG1D,IAAIf,QAAQe,SAAS,KAAKI,aAAanB,QAAQ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AAkBL;IAGpB,OAAOL,WAAWoD,MAAM,CAAC;QACvBpD,WAAWqD,KAAK,CAAC,OAAO,GAAG1C,KAAK,QAAQ,CAAC,EAAEsC;KAC5C;AACH,EAAE"}
@@ -1,25 +0,0 @@
1
- import { PolicyDecisionTag } from '@entifix/authz';
2
- import { type Entity, type EntityConstructor } from '@entifix/core';
3
- import { Effect } from 'effect';
4
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
5
- import { type MetadataCompositions } from './metadata-composition.js';
6
- /**
7
- * `GET /api/<entity>/$metadata` — what this caller may do with one entity.
8
- *
9
- * Mounted **per entity, at a literal path**, not as a `/api/:entity/$metadata`
10
- * wildcard. `HttpRouter` resolves through `find-my-way-ts`, where a static
11
- * segment beats a parametric one and there is no backtracking once the
12
- * parametric branch has matched: alongside an existing `/api/<entity>/:id`, a
13
- * wildcard `$metadata` route never runs at all — the by-id handler wins with
14
- * `id === "$metadata"`, misses, and answers its own `404`. The endpoint would
15
- * read as "this entity has no metadata" while appearing mounted. A literal wins
16
- * regardless of registration order, which is why the base exports a route for
17
- * one entity and each service registers it for each of its own.
18
- *
19
- * Deliberately **not** behind `requireOrganization`, even on a tenant-plane
20
- * service: the document describes the model, not tenant data, and resolving a
21
- * database handle here would leave a vendor with no active organization unable
22
- * to see their own affordances.
23
- */
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>;
25
- //# sourceMappingURL=entity-metadata-route.d.ts.map
@@ -1 +0,0 @@
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,102 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { createHash } from 'node:crypto';
3
- import { parsePermission, permissionForEntity, permissionForUseCase, PolicyDecisionTag } from '@entifix/authz';
4
- import { describeEntityUseCases, ENTITY_ACTIONS, extractMetaEntity, makeEntityMetadataEnvelope, NotFound } from '@entifix/core';
5
- import { Effect } from 'effect';
6
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
7
- import { requirePrincipal, withVerifiedContext } from './auth/index.js';
8
- import { assertCompositionsDeclared, compositionFor } from './metadata-composition.js';
9
- import { respond } from './respond.js';
10
- /**
11
- * `GET /api/<entity>/$metadata` — what this caller may do with one entity.
12
- *
13
- * Mounted **per entity, at a literal path**, not as a `/api/:entity/$metadata`
14
- * wildcard. `HttpRouter` resolves through `find-my-way-ts`, where a static
15
- * segment beats a parametric one and there is no backtracking once the
16
- * parametric branch has matched: alongside an existing `/api/<entity>/:id`, a
17
- * wildcard `$metadata` route never runs at all — the by-id handler wins with
18
- * `id === "$metadata"`, misses, and answers its own `404`. The endpoint would
19
- * read as "this entity has no metadata" while appearing mounted. A literal wins
20
- * regardless of registration order, which is why the base exports a route for
21
- * one entity and each service registers it for each of its own.
22
- *
23
- * Deliberately **not** behind `requireOrganization`, even on a tenant-plane
24
- * service: the document describes the model, not tenant data, and resolving a
25
- * database handle here would leave a vendor with no active organization unable
26
- * to see their own affordances.
27
- */ export const entityMetadataRoute = (entityConstructor, compositions = {})=>{
28
- assertCompositionsDeclared(describeEntityUseCases(entityConstructor), compositions);
29
- return respond(requirePrincipal((principal)=>Effect.gen(function*() {
30
- const policy = yield* PolicyDecisionTag;
31
- const allows = (permission)=>{
32
- const { resource, action } = parsePermission(permission);
33
- return policy.decide({
34
- subject: {
35
- roles: principal.roles
36
- },
37
- resource,
38
- action
39
- });
40
- };
41
- // SECURITY BOUNDARY. The document names domains, entity keys and verbs —
42
- // it is a map of the model — so an entity the caller may not read answers
43
- // exactly as one this service does not host. A `403` here would make the
44
- // endpoint an oracle: walk it and learn the shape of everything you are
45
- // not allowed to see. Same category as `redactConfiguration`, not
46
- // diagnostics polish.
47
- if (!allows(permissionForEntity(entityConstructor, 'read'))) {
48
- return yield* notFound(entityConstructor);
49
- }
50
- const document = {
51
- actions: ENTITY_ACTIONS.filter((action)=>allows(permissionForEntity(entityConstructor, action))),
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
- })))
65
- };
66
- // The ETag hashes the *computed* document, not the descriptor set the
67
- // deployment declares. Two principals with different grants get different
68
- // documents from the same model, so a hash of the model would `304` one
69
- // caller onto another's affordances. Hashing the permission set instead
70
- // would read `ROLE_PERMISSIONS` directly and go around `PolicyDecisionTag`,
71
- // so an injected ABAC policy could change affordances without changing the
72
- // tag. Computing first costs a metadata read and a handful of pure
73
- // `decide` calls — no IO.
74
- const body = JSON.stringify(makeEntityMetadataEnvelope(entityConstructor, document));
75
- const etag = `"${createHash('sha256').update(body).digest('hex')}"`;
76
- const request = yield* HttpServerRequest.HttpServerRequest;
77
- if (request.headers['if-none-match'] === etag) {
78
- return HttpServerResponse.empty({
79
- status: 304
80
- }).pipe(HttpServerResponse.setHeaders(cacheHeaders(etag)));
81
- }
82
- return HttpServerResponse.text(body, {
83
- contentType: 'application/json',
84
- headers: cacheHeaders(etag)
85
- });
86
- })));
87
- };
88
- /**
89
- * The response varies by principal, so it must never land in a shared cache.
90
- * `Vary` names **both** credential carriers because the shell reads the access
91
- * token from the `entifix_at` cookie *or* an `Authorization: Bearer` header, and a
92
- * cache keyed on only one of them would serve across the other.
93
- */ const cacheHeaders = (etag)=>({
94
- etag,
95
- 'cache-control': 'private, no-cache',
96
- vary: 'Cookie, Authorization'
97
- });
98
- /** Indistinguishable from the `404` a service gives for an entity it does not host. */ const notFound = (entityConstructor)=>Effect.fail(new NotFound({
99
- entity: extractMetaEntity(entityConstructor).key
100
- }));
101
-
102
- //# sourceMappingURL=entity-metadata-route.js.map
@@ -1 +0,0 @@
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","c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