@entifix/service-shell 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -4
- package/dist/auth/require-organization.d.ts +1 -1
- package/dist/auth/require-organization.d.ts.map +1 -1
- package/dist/auth/require-organization.js.map +1 -1
- package/dist/auth/require-principal.d.ts +9 -55
- package/dist/auth/require-principal.d.ts.map +1 -1
- package/dist/auth/require-principal.js +15 -13
- package/dist/auth/require-principal.js.map +1 -1
- package/dist/auth/require-service-crossing.d.ts.map +1 -1
- package/dist/auth/require-service-crossing.js +3 -13
- package/dist/auth/require-service-crossing.js.map +1 -1
- package/dist/auth/shared-token.d.ts +2 -0
- package/dist/auth/shared-token.d.ts.map +1 -1
- package/dist/auth/shared-token.js +2 -2
- package/dist/auth/shared-token.js.map +1 -1
- package/dist/auth/verified-context.d.ts +1 -2
- package/dist/auth/verified-context.d.ts.map +1 -1
- package/dist/auth/verified-context.js.map +1 -1
- package/dist/entity-facet-routes.d.ts +2 -2
- package/dist/entity-facet-routes.d.ts.map +1 -1
- package/dist/entity-facet-routes.js.map +1 -1
- package/dist/entity-route-guard.d.ts +2 -2
- package/dist/entity-route-guard.d.ts.map +1 -1
- package/dist/entity-route-guard.js.map +1 -1
- package/dist/entity-routes.d.ts +1 -1
- package/dist/entity-routes.d.ts.map +1 -1
- package/dist/entity-routes.js.map +1 -1
- package/dist/http-api/build-api.d.ts +78 -0
- package/dist/http-api/build-api.d.ts.map +1 -0
- package/dist/http-api/build-api.js +189 -0
- package/dist/http-api/build-api.js.map +1 -0
- package/dist/http-api/entity-api.d.ts +69 -0
- package/dist/http-api/entity-api.d.ts.map +1 -0
- package/dist/http-api/entity-api.js +522 -0
- package/dist/http-api/entity-api.js.map +1 -0
- package/dist/http-api/guards.d.ts +92 -0
- package/dist/http-api/guards.d.ts.map +1 -0
- package/dist/http-api/guards.js +131 -0
- package/dist/http-api/guards.js.map +1 -0
- package/dist/http-api/index.d.ts +6 -0
- package/dist/http-api/index.d.ts.map +1 -0
- package/dist/http-api/index.js +7 -0
- package/dist/http-api/index.js.map +1 -0
- package/dist/http-api/problem-codec.d.ts +14 -0
- package/dist/http-api/problem-codec.d.ts.map +1 -0
- package/dist/http-api/problem-codec.js +26 -0
- package/dist/http-api/problem-codec.js.map +1 -0
- package/dist/http-api/service-group.d.ts +74 -0
- package/dist/http-api/service-group.d.ts.map +1 -0
- package/dist/http-api/service-group.js +168 -0
- package/dist/http-api/service-group.js.map +1 -0
- package/dist/idempotency.d.ts +9 -4
- package/dist/idempotency.d.ts.map +1 -1
- package/dist/idempotency.js +11 -6
- package/dist/idempotency.js.map +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/make-service.d.ts +39 -6
- package/dist/make-service.d.ts.map +1 -1
- package/dist/make-service.js +54 -16
- package/dist/make-service.js.map +1 -1
- package/dist/narrowing.d.ts +1 -15
- package/dist/narrowing.d.ts.map +1 -1
- package/dist/narrowing.js.map +1 -1
- package/dist/respond.d.ts +6 -4
- package/dist/respond.d.ts.map +1 -1
- package/dist/respond.js +11 -7
- package/dist/respond.js.map +1 -1
- package/dist/serve-test-service.d.ts +2 -1
- package/dist/serve-test-service.d.ts.map +1 -1
- package/dist/serve-test-service.js.map +1 -1
- package/package.json +7 -6
- package/dist/health-routes.d.ts +0 -24
- package/dist/health-routes.d.ts.map +0 -1
- package/dist/health-routes.js +0 -86
- package/dist/health-routes.js.map +0 -1
- package/dist/service-description-route.d.ts +0 -66
- package/dist/service-description-route.d.ts.map +0 -1
- package/dist/service-description-route.js +0 -60
- package/dist/service-description-route.js.map +0 -1
|
@@ -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 {\n RepositoryScope,\n TokenServiceTag,\n VerifiedContext,\n} from '@entifix/business';\nimport type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';\nimport type { Effect } from 'effect';\n\nimport {\n
|
|
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"}
|
package/dist/entity-routes.d.ts
CHANGED
|
@@ -1,10 +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';
|
|
6
7
|
import type { MetadataCompositions } from './metadata-composition.js';
|
|
7
|
-
import { type NarrowingRules } from './narrowing.js';
|
|
8
8
|
import { type FailurePolicy } from './respond.js';
|
|
9
9
|
import { type EntityRouteRefusal, routeFailure } from './route-responses.js';
|
|
10
10
|
/** The five generic verbs a route set can mount. */
|
|
@@ -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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AC,OAAO,CAAC,EAAE,CACjB,MAAM,EAAE,CAAC,EACT,OAAO,EAAE,kBAAkB,GAAG;QAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,QAAQ,CAAA;KAAE,KACjE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,kBAAkB,GAAG,iBAAiB,EAAE,CAAC,CAAC,CAAC;IACjE;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACxE;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;CACjC;AA6UD;;;;;;GAMG;AACH,OAAO,EAAE,YAAY,EAAE,CAAC;AAExB,eAAO,MAAM,gBAAgB,IA1T3B,CAAC,SAAS,MAAM,EAChB,CAAC,gBAOK,CAAC,SAAS,gBAAgB,6BAEb,iBAAiB,CAAC,CAAC,CAAC,WAC9B,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;;UAiTlC,CAAC,QACD,CAAC,SAAS,MAAM,QAAQ,CAAC,SAAS,gBAAgB,qBAC9B,iBAAiB,CAAC,CAAC,CAAC,WAC9B,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;;CAGzC,CAAC"}
|
|
@@ -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 type { MetadataCompositions } from './metadata-composition.js';\nimport {\n narrowedByIdRequest,\n narrowingFor,\n type NarrowingRules,\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":";AACA,SACEA,eAAe,EACfC,WAAW,EACXC,oBAAoB,EACpBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR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AAC;QAAC;QAC7CP,QAAQ;YAAEkB,QAAQ;YAAUgE,MAAM,GAAG3E,KAAK,IAAI,CAAC;QAAC;IAClD;IAEA,OAAOzB,WAAWqG,MAAM,CAAC;QACvB,yDAAyD;QACzDrG,WAAWsG,KAAK,CACd,OACA,GAAG7E,KAAK,UAAU,CAAC,EACnBtB,oBAAoBmB,oBAAmBC,wBAAAA,QAAQgF,YAAY,YAApBhF,wBAAwB,CAAC;WAE/DA,QAAQK,KAAK,CAAC4E,GAAG,CAACjE,CAAAA,OACnBvC,WAAWsG,KAAK,CACdH,MAAM,CAAC5D,KAAK,CAACH,MAAM,EACnB+D,MAAM,CAAC5D,KAAK,CAAC6D,IAAI,EACjBJ,WAAWzD;KAGhB;AACH;AAEA;;;;;;CAMC,GACD,SAAS5B,YAAY,GAAG;AAExB,OAAO,MAAM8F,mBAAmBC,OAAOC,MAAM,CAACtF,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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BmB,oBAAmBC,wBAAAA,QAAQgF,YAAY,YAApBhF,wBAAwB,CAAC;WAE/DA,QAAQK,KAAK,CAAC4E,GAAG,CAACjE,CAAAA,OACnBvC,WAAWsG,KAAK,CACdH,MAAM,CAAC5D,KAAK,CAACH,MAAM,EACnB+D,MAAM,CAAC5D,KAAK,CAAC6D,IAAI,EACjBJ,WAAWzD;KAGhB;AACH;AAEA;;;;;;CAMC,GACD,SAAS5B,YAAY,GAAG;AAExB,OAAO,MAAM8F,mBAAmBC,OAAOC,MAAM,CAACtF,oBAAoB;IAChE4B,KACE,IACA,CACE3B,mBACAC,UAEAF,mBAA4BC,mBAAmBC;AACrD,GAAG"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { IdempotencyKeyTag, OrganizationIdTag, RequestPrincipalTag, VerifiedContextTag } from '@entifix/business';
|
|
2
|
+
import { type AnyEndpoint, type DeadlineTag, type FailureClass, type Implemented, Invalid } from '@entifix/core';
|
|
3
|
+
import { type FileSystem, Layer, type Path } from 'effect';
|
|
4
|
+
import type { Etag, HttpPlatform, HttpRouter } from 'effect/http';
|
|
5
|
+
import { HttpApi, HttpApiError, HttpApiMiddleware } from 'effect/http-api';
|
|
6
|
+
import { type FailurePolicy } from '../respond.js';
|
|
7
|
+
import { type GuardServices, type IdempotencyServices } from './guards.js';
|
|
8
|
+
/**
|
|
9
|
+
* A named set of implemented endpoints — one `HttpApiGroup` once built. A slice
|
|
10
|
+
* groups by entity or by concern; the name is what an OpenAPI document and a
|
|
11
|
+
* client namespace it under.
|
|
12
|
+
*/
|
|
13
|
+
export interface EndpointGroup<Endpoint extends AnyEndpoint = AnyEndpoint, R = never> {
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly endpoints: ReadonlyArray<Implemented<Endpoint, R>>;
|
|
16
|
+
}
|
|
17
|
+
/** Any group, whatever its handlers need — the constraint a builder takes. */
|
|
18
|
+
export type AnyEndpointGroup = EndpointGroup<AnyEndpoint, any>;
|
|
19
|
+
type EndpointOf<I> = I extends Implemented<infer D, any> ? D : never;
|
|
20
|
+
type RequirementsOf<I> = I extends Implemented<any, infer R> ? R : never;
|
|
21
|
+
/** Group implemented endpoints under one name. */
|
|
22
|
+
export declare const endpointGroup: <const Endpoints extends ReadonlyArray<Implemented<any, any>>>(name: string, ...endpoints: Endpoints) => EndpointGroup<EndpointOf<Endpoints[number]>, RequirementsOf<Endpoints[number]>>;
|
|
23
|
+
/** What the shell provides a handler: the verified request context. */
|
|
24
|
+
export type ProvidedToHandlers = RequestPrincipalTag | OrganizationIdTag | IdempotencyKeyTag | VerifiedContextTag | DeadlineTag;
|
|
25
|
+
/**
|
|
26
|
+
* What serving `Groups` requires of the composition root: what the handlers
|
|
27
|
+
* need beyond the request context, plus what each declared guard and
|
|
28
|
+
* idempotency mode reads. A host that omits one does not compile.
|
|
29
|
+
*/
|
|
30
|
+
export type ServedRequirements<Groups extends ReadonlyArray<AnyEndpointGroup>> = GroupRequirements<Groups[number]>;
|
|
31
|
+
type GroupRequirements<Group> = Group extends EndpointGroup<infer Endpoint, infer R> ? Exclude<R, ProvidedToHandlers> | GuardServices<Endpoint['guard']['kind']> | IdempotencyServices<Endpoint['idempotent']> : never;
|
|
32
|
+
/** What serving an API needs from the HTTP server itself. */
|
|
33
|
+
export type ServedPlatform = HttpRouter.HttpRouter | Etag.Generator | FileSystem.FileSystem | HttpPlatform.HttpPlatform | Path.Path;
|
|
34
|
+
/** `METHOD /path` for every endpoint — what a register diffs a service against. */
|
|
35
|
+
export declare const endpointsOf: (groups: ReadonlyArray<AnyEndpointGroup>) => readonly string[];
|
|
36
|
+
/** The status a failure class answers with under `policy`. */
|
|
37
|
+
export declare const statusForClass: (failureClass: FailureClass, policy: FailurePolicy) => number;
|
|
38
|
+
declare const Respond_base: HttpApiMiddleware.ServiceClass<Respond, "@entifix/service-shell/Respond", {
|
|
39
|
+
requires: never;
|
|
40
|
+
provides: never;
|
|
41
|
+
error: never;
|
|
42
|
+
clientError: never;
|
|
43
|
+
requiredForClient: false;
|
|
44
|
+
security: never;
|
|
45
|
+
}, HttpApiMiddleware.HttpApiMiddleware<never, never, never>>;
|
|
46
|
+
/**
|
|
47
|
+
* The outermost middleware of every endpoint: `respond` under the API's
|
|
48
|
+
* policy, after a schema error has become `invalid` with one entry per broken
|
|
49
|
+
* field. A response that fails to encode is the service's own fault and stays
|
|
50
|
+
* a defect.
|
|
51
|
+
*/
|
|
52
|
+
export declare class Respond extends Respond_base {
|
|
53
|
+
}
|
|
54
|
+
/** The `invalid` failure a request that fails its schema answers with. */
|
|
55
|
+
export declare const invalidRequest: (error: HttpApiError.HttpApiSchemaError) => Invalid;
|
|
56
|
+
export interface ApiOptions {
|
|
57
|
+
/** The status and log table; the framework's defaults when absent. */
|
|
58
|
+
readonly policy?: FailurePolicy;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The `HttpApi` a set of groups describes. Every endpoint's failures carry the
|
|
62
|
+
* status the policy gives them, and two endpoints that share a method and
|
|
63
|
+
* path throw here rather than shadowing each other at runtime.
|
|
64
|
+
*/
|
|
65
|
+
export declare const buildApi: (name: string, groups: ReadonlyArray<AnyEndpointGroup>, options?: ApiOptions) => HttpApi.Top;
|
|
66
|
+
/**
|
|
67
|
+
* Serve `groups` under one API: the routes, every guard, the respond
|
|
68
|
+
* middleware. The layer requires what the handlers, guards and idempotency
|
|
69
|
+
* modes read, plus the HTTP platform the server provides.
|
|
70
|
+
*/
|
|
71
|
+
export declare const serveApi: <const Groups extends ReadonlyArray<AnyEndpointGroup>>(api: HttpApi.Top, groups: Groups, options?: ApiOptions) => Layer.Layer<never, never, ServedRequirements<Groups> | ServedPlatform>;
|
|
72
|
+
/** Build and serve in one call, for a host that needs nothing between. */
|
|
73
|
+
export declare const serveEndpoints: <const Groups extends ReadonlyArray<AnyEndpointGroup>>(name: string, groups: Groups, options?: ApiOptions) => {
|
|
74
|
+
readonly api: HttpApi.Top;
|
|
75
|
+
readonly layer: Layer.Layer<never, never, ServedPlatform | GroupRequirements<Groups[number]>>;
|
|
76
|
+
};
|
|
77
|
+
export {};
|
|
78
|
+
//# sourceMappingURL=build-api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-api.d.ts","sourceRoot":"","sources":["../../src/http-api/build-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,WAAW,EAGhB,KAAK,WAAW,EAGhB,KAAK,YAAY,EAKjB,KAAK,WAAW,EAEhB,OAAO,EAOR,MAAM,eAAe,CAAC;AACvB,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,EACL,KAAK,IAAI,EAGV,MAAM,QAAQ,CAAC;AAChB,OAAO,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAElE,OAAO,EACL,OAAO,EAGP,YAAY,EAEZ,iBAAiB,EAElB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,eAAe,CAAC;AACvB,OAAO,EAKL,KAAK,aAAa,EAElB,KAAK,mBAAmB,EACzB,MAAM,aAAa,CAAC;AAGrB;;;;GAIG;AACH,MAAM,WAAW,aAAa,CAC5B,QAAQ,SAAS,WAAW,GAAG,WAAW,EAC1C,CAAC,GAAG,KAAK;IAET,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;CAC7D;AAED,8EAA8E;AAE9E,MAAM,MAAM,gBAAgB,GAAG,aAAa,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;AAG/D,KAAK,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,WAAW,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,GAAG,CAA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AS,MAAM,EAKf,CAAC;AA+BJ,8DAA8D;AAC9D,eAAO,MAAM,cAAc,GACzB,cAAc,YAAY,EAC1B,QAAQ,aAAa,KACpB,MAIA,CAAC;;;;;;;;;AAyCJ;;;;;GAKG;AACH,qBAAa,OAAQ,SAAQ,YAE5B;CAAG;AAIJ,0EAA0E;AAC1E,eAAO,MAAM,cAAc,GACzB,OAAO,YAAY,CAAC,kBAAkB,KACrC,OAYF,CAAC;AA8DF,MAAM,WAAW,UAAU;IACzB,sEAAsE;IACtE,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;CACjC;AAED;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GACnB,MAAM,MAAM,EACZ,QAAQ,aAAa,CAAC,gBAAgB,CAAC,EACvC,UAAS,UAAe,KACvB,OAAO,CAAC,GA+BV,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,gBAAgB,CAAC,EAC3E,KAAK,OAAO,CAAC,GAAG,EAChB,QAAQ,MAAM,EACd,UAAS,UAAe,KACvB,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,kBAAkB,CAAC,MAAM,CAAC,GAAG,cAAc,CAsBvE,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,cAAc,GACzB,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,gBAAgB,CAAC,EAEpD,MAAM,MAAM,EACZ,QAAQ,MAAM,EACd,UAAS,UAAe;;;CAIzB,CAAC"}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { bodyEncodingOf, Contention, Forbidden, IdempotencyKeyInFlight, IdempotencyKeyMissing, IdempotencyKeyReused, Internal, Invalid, Overloaded, ProtocolFailure, Timeout, Unauthenticated, Unavailable, UpstreamUnavailable } from '@entifix/core';
|
|
3
|
+
import { Effect, Layer, Schema, SchemaIssue } from 'effect';
|
|
4
|
+
import { HttpServerResponse } from 'effect/http';
|
|
5
|
+
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiError, HttpApiGroup, HttpApiMiddleware, HttpApiSchema } from 'effect/http-api';
|
|
6
|
+
import { NoActiveOrganization } from '../auth/failures.js';
|
|
7
|
+
import { defaultFailurePolicy, respond } from '../respond.js';
|
|
8
|
+
import { EndpointGuardAnnotation, EndpointIdempotencyAnnotation, GUARD_MIDDLEWARE, guardLayers, IdempotencyGuard } from './guards.js';
|
|
9
|
+
import { problemCodec } from './problem-codec.js';
|
|
10
|
+
/* eslint-enable @typescript-eslint/no-explicit-any */ /** Group implemented endpoints under one name. */ export const endpointGroup = (name, ...endpoints)=>({
|
|
11
|
+
name,
|
|
12
|
+
endpoints: endpoints
|
|
13
|
+
});
|
|
14
|
+
/** `METHOD /path` for every endpoint — what a register diffs a service against. */ export const endpointsOf = (groups)=>groups.flatMap((group)=>group.endpoints.map(({ descriptor })=>`${descriptor.method} ${descriptor.path}`));
|
|
15
|
+
/** The failures every endpoint may answer, whether or not it declares them. */ const TECHNICAL = [
|
|
16
|
+
Invalid,
|
|
17
|
+
Internal,
|
|
18
|
+
Unavailable,
|
|
19
|
+
UpstreamUnavailable,
|
|
20
|
+
Timeout,
|
|
21
|
+
Overloaded,
|
|
22
|
+
Contention,
|
|
23
|
+
ProtocolFailure
|
|
24
|
+
];
|
|
25
|
+
const GUARD_FAILURES = {
|
|
26
|
+
public: [],
|
|
27
|
+
session: [
|
|
28
|
+
Unauthenticated
|
|
29
|
+
],
|
|
30
|
+
permission: [
|
|
31
|
+
Unauthenticated,
|
|
32
|
+
Forbidden
|
|
33
|
+
],
|
|
34
|
+
organization: [
|
|
35
|
+
Unauthenticated,
|
|
36
|
+
Forbidden,
|
|
37
|
+
NoActiveOrganization
|
|
38
|
+
],
|
|
39
|
+
crossing: [
|
|
40
|
+
Unauthenticated,
|
|
41
|
+
Forbidden
|
|
42
|
+
],
|
|
43
|
+
fleet: [
|
|
44
|
+
Unauthenticated
|
|
45
|
+
]
|
|
46
|
+
};
|
|
47
|
+
const IDEMPOTENCY_FAILURES = [
|
|
48
|
+
IdempotencyKeyMissing,
|
|
49
|
+
IdempotencyKeyReused,
|
|
50
|
+
IdempotencyKeyInFlight
|
|
51
|
+
];
|
|
52
|
+
/** The status a failure class answers with under `policy`. */ export const statusForClass = (failureClass, policy)=>{
|
|
53
|
+
var _policy_tagStatus_failureClass_identifier;
|
|
54
|
+
return (_policy_tagStatus_failureClass_identifier = policy.tagStatus[failureClass.identifier]) != null ? _policy_tagStatus_failureClass_identifier : policy.categoryStatus[failureClass.prototype.category];
|
|
55
|
+
};
|
|
56
|
+
const errorSchemas = (descriptor, policy)=>[
|
|
57
|
+
...new Set([
|
|
58
|
+
...descriptor.errors,
|
|
59
|
+
...GUARD_FAILURES[descriptor.guard.kind],
|
|
60
|
+
...descriptor.idempotent === undefined ? [] : IDEMPOTENCY_FAILURES,
|
|
61
|
+
...TECHNICAL
|
|
62
|
+
])
|
|
63
|
+
].map((failureClass)=>problemCodec(failureClass, statusForClass(failureClass, policy)));
|
|
64
|
+
const toSchema = (schema)=>schema === undefined ? undefined : Schema.isSchema(schema) ? schema : Schema.Struct(schema);
|
|
65
|
+
/** A payload on the wire it declared: JSON unless it said text or a form. */ const toPayload = (schema)=>{
|
|
66
|
+
const payload = toSchema(schema);
|
|
67
|
+
if (payload === undefined) return undefined;
|
|
68
|
+
const encoding = bodyEncodingOf(payload);
|
|
69
|
+
switch(encoding == null ? void 0 : encoding.kind){
|
|
70
|
+
case 'text':
|
|
71
|
+
// A `textBody` is a string schema; the marker is what says so here.
|
|
72
|
+
return payload.pipe(HttpApiSchema.asText({
|
|
73
|
+
contentType: encoding.contentType
|
|
74
|
+
}));
|
|
75
|
+
case 'form':
|
|
76
|
+
return payload.pipe(HttpApiSchema.asFormUrlEncoded({
|
|
77
|
+
contentType: encoding.contentType
|
|
78
|
+
}));
|
|
79
|
+
default:
|
|
80
|
+
return payload;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* The outermost middleware of every endpoint: `respond` under the API's
|
|
85
|
+
* policy, after a schema error has become `invalid` with one entry per broken
|
|
86
|
+
* field. A response that fails to encode is the service's own fault and stays
|
|
87
|
+
* a defect.
|
|
88
|
+
*/ export class Respond extends HttpApiMiddleware.Service()('@entifix/service-shell/Respond') {
|
|
89
|
+
}
|
|
90
|
+
const formatIssues = SchemaIssue.makeFormatterStandardSchemaV1();
|
|
91
|
+
/** The `invalid` failure a request that fails its schema answers with. */ export const invalidRequest = (error)=>{
|
|
92
|
+
const where = error.kind.toLowerCase();
|
|
93
|
+
const { issues } = formatIssues(error.cause.issue);
|
|
94
|
+
return new Invalid({
|
|
95
|
+
errors: issues.map((issue)=>({
|
|
96
|
+
// Effect's formatter always sets the path — `[]` for the part itself —
|
|
97
|
+
// though the Standard Schema type it answers with leaves it optional.
|
|
98
|
+
pointer: `/${[
|
|
99
|
+
where,
|
|
100
|
+
...issue.path.map(String)
|
|
101
|
+
].join('/')}`,
|
|
102
|
+
detail: issue.message,
|
|
103
|
+
code: 'schema'
|
|
104
|
+
}))
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
const REQUEST_PARTS = new Set([
|
|
108
|
+
'Params',
|
|
109
|
+
'Query',
|
|
110
|
+
'Payload',
|
|
111
|
+
'Headers'
|
|
112
|
+
]);
|
|
113
|
+
const respondLayer = (policy)=>Layer.succeed(Respond)((httpEffect)=>respond(httpEffect.pipe(Effect.catchIf((error)=>HttpApiError.HttpApiSchemaError.is(error) && REQUEST_PARTS.has(error.kind), (error)=>Effect.fail(invalidRequest(error)))), policy).pipe(Effect.map(uncachedByDefault)));
|
|
114
|
+
/**
|
|
115
|
+
* Every answer `no-store` unless its endpoint chose a cache policy of its own.
|
|
116
|
+
* An API answer carries a principal, a token or a tenant's records far more
|
|
117
|
+
* often than anything a cache could share, and a token response must not be
|
|
118
|
+
* stored at all (RFC 6749 §5.1) — so the safe default is the shell's, and an
|
|
119
|
+
* endpoint that wants caching (an `ETag`ed metadata document) says so.
|
|
120
|
+
*/ const uncachedByDefault = (response)=>response.headers['cache-control'] === undefined ? HttpServerResponse.setHeader(response, 'cache-control', 'no-store') : response;
|
|
121
|
+
const toEndpoint = (descriptor, policy)=>{
|
|
122
|
+
const params = toSchema(descriptor.params);
|
|
123
|
+
const query = toSchema(descriptor.query);
|
|
124
|
+
const payload = toPayload(descriptor.payload);
|
|
125
|
+
const headers = toSchema(descriptor.headers);
|
|
126
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime
|
|
127
|
+
let endpoint = HttpApiEndpoint.make(descriptor.method)(descriptor.name, descriptor.path, _extends({}, params === undefined ? {} : {
|
|
128
|
+
params
|
|
129
|
+
}, query === undefined ? {} : {
|
|
130
|
+
query
|
|
131
|
+
}, payload === undefined ? {} : {
|
|
132
|
+
payload
|
|
133
|
+
}, headers === undefined ? {} : {
|
|
134
|
+
headers
|
|
135
|
+
}, {
|
|
136
|
+
success: descriptor.success,
|
|
137
|
+
error: errorSchemas(descriptor, policy)
|
|
138
|
+
})).annotate(EndpointGuardAnnotation, descriptor.guard);
|
|
139
|
+
// Order is outermost last: idempotency runs inside the guard, so it sees
|
|
140
|
+
// the principal the guard verified; `Respond` wraps everything.
|
|
141
|
+
if (descriptor.idempotent !== undefined) endpoint = endpoint.annotate(EndpointIdempotencyAnnotation, descriptor.idempotent).middleware(IdempotencyGuard);
|
|
142
|
+
const guard = GUARD_MIDDLEWARE[descriptor.guard.kind];
|
|
143
|
+
if (guard !== undefined) endpoint = endpoint.middleware(guard);
|
|
144
|
+
return endpoint.middleware(Respond);
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* The `HttpApi` a set of groups describes. Every endpoint's failures carry the
|
|
148
|
+
* status the policy gives them, and two endpoints that share a method and
|
|
149
|
+
* path throw here rather than shadowing each other at runtime.
|
|
150
|
+
*/ export const buildApi = (name, groups, options = {})=>{
|
|
151
|
+
var _options_policy;
|
|
152
|
+
const policy = (_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy;
|
|
153
|
+
const seen = new Set();
|
|
154
|
+
for (const target of endpointsOf(groups)){
|
|
155
|
+
if (seen.has(target)) throw new Error(`'${name}' declares ${target} twice`);
|
|
156
|
+
seen.add(target);
|
|
157
|
+
}
|
|
158
|
+
// A group serves its endpoints by name, so a second one under a name would
|
|
159
|
+
// silently replace the first rather than fail.
|
|
160
|
+
for (const group of groups){
|
|
161
|
+
const names = new Set();
|
|
162
|
+
for (const { descriptor } of group.endpoints){
|
|
163
|
+
if (names.has(descriptor.name)) throw new Error(`'${name}' names two endpoints '${descriptor.name}' in '${group.name}'`);
|
|
164
|
+
names.add(descriptor.name);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return groups.reduce((api, group)=>api.add(group.endpoints.reduce(// eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime
|
|
168
|
+
(built, { descriptor })=>built.add(toEndpoint(descriptor, policy)), HttpApiGroup.make(group.name))), HttpApi.make(name));
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* Serve `groups` under one API: the routes, every guard, the respond
|
|
172
|
+
* middleware. The layer requires what the handlers, guards and idempotency
|
|
173
|
+
* modes read, plus the HTTP platform the server provides.
|
|
174
|
+
*/ export const serveApi = (api, groups, options = {})=>{
|
|
175
|
+
var _options_policy;
|
|
176
|
+
const handlers = groups.map((group)=>HttpApiBuilder.group(api, group.name, // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime
|
|
177
|
+
(handle)=>group.endpoints.reduce(// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
178
|
+
(built, { descriptor, handler })=>built.handle(descriptor.name, handler), handle)));
|
|
179
|
+
return HttpApiBuilder.layer(api).pipe(Layer.provide(Layer.mergeAll(...handlers)), Layer.provide(guardLayers), Layer.provide(respondLayer((_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy)));
|
|
180
|
+
};
|
|
181
|
+
/** Build and serve in one call, for a host that needs nothing between. */ export const serveEndpoints = (name, groups, options = {})=>{
|
|
182
|
+
const api = buildApi(name, groups, options);
|
|
183
|
+
return {
|
|
184
|
+
api,
|
|
185
|
+
layer: serveApi(api, groups, options)
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
//# sourceMappingURL=build-api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/http-api/build-api.ts"],"sourcesContent":["import type {\n IdempotencyKeyTag,\n OrganizationIdTag,\n RequestPrincipalTag,\n VerifiedContextTag,\n} from '@entifix/business';\nimport {\n type AnyEndpoint,\n bodyEncodingOf,\n Contention,\n type DeadlineTag,\n type EndpointSchema,\n type EntifixFailure,\n type FailureClass,\n Forbidden,\n IdempotencyKeyInFlight,\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n type Implemented,\n Internal,\n Invalid,\n Overloaded,\n ProtocolFailure,\n Timeout,\n Unauthenticated,\n Unavailable,\n UpstreamUnavailable,\n} from '@entifix/core';\nimport {\n Effect,\n type FileSystem,\n Layer,\n type Path,\n Schema,\n SchemaIssue,\n} from 'effect';\nimport type { Etag, HttpPlatform, HttpRouter } from 'effect/http';\nimport { HttpServerResponse } from 'effect/http';\nimport {\n HttpApi,\n HttpApiBuilder,\n HttpApiEndpoint,\n HttpApiError,\n HttpApiGroup,\n HttpApiMiddleware,\n HttpApiSchema,\n} from 'effect/http-api';\n\nimport { NoActiveOrganization } from '../auth/failures.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from '../respond.js';\nimport {\n EndpointGuardAnnotation,\n EndpointIdempotencyAnnotation,\n GUARD_MIDDLEWARE,\n guardLayers,\n type GuardServices,\n IdempotencyGuard,\n type IdempotencyServices,\n} from './guards.js';\nimport { problemCodec } from './problem-codec.js';\n\n/**\n * A named set of implemented endpoints — one `HttpApiGroup` once built. A slice\n * groups by entity or by concern; the name is what an OpenAPI document and a\n * client namespace it under.\n */\nexport interface EndpointGroup<\n Endpoint extends AnyEndpoint = AnyEndpoint,\n R = never,\n> {\n readonly name: string;\n readonly endpoints: ReadonlyArray<Implemented<Endpoint, R>>;\n}\n\n/** Any group, whatever its handlers need — the constraint a builder takes. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a constraint\nexport type AnyEndpointGroup = EndpointGroup<AnyEndpoint, any>;\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- inference sites */\ntype EndpointOf<I> = I extends Implemented<infer D, any> ? D : never;\ntype RequirementsOf<I> = I extends Implemented<any, infer R> ? R : never;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/** Group implemented endpoints under one name. */\nexport const endpointGroup = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Endpoints extends ReadonlyArray<Implemented<any, any>>,\n>(\n name: string,\n ...endpoints: Endpoints\n): EndpointGroup<\n EndpointOf<Endpoints[number]>,\n RequirementsOf<Endpoints[number]>\n> => ({\n name,\n endpoints: endpoints as never,\n});\n\n/** What the shell provides a handler: the verified request context. */\nexport type ProvidedToHandlers =\n | RequestPrincipalTag\n | OrganizationIdTag\n | IdempotencyKeyTag\n | VerifiedContextTag\n | DeadlineTag;\n\n/**\n * What serving `Groups` requires of the composition root: what the handlers\n * need beyond the request context, plus what each declared guard and\n * idempotency mode reads. A host that omits one does not compile.\n */\nexport type ServedRequirements<Groups extends ReadonlyArray<AnyEndpointGroup>> =\n GroupRequirements<Groups[number]>;\n\n// Distributive over the groups, and `never` for none.\ntype GroupRequirements<Group> =\n Group extends EndpointGroup<infer Endpoint, infer R>\n ? | Exclude<R, ProvidedToHandlers>\n | GuardServices<Endpoint['guard']['kind']>\n | IdempotencyServices<Endpoint['idempotent']>\n : never;\n\n/** What serving an API needs from the HTTP server itself. */\nexport type ServedPlatform =\n | HttpRouter.HttpRouter\n | Etag.Generator\n | FileSystem.FileSystem\n | HttpPlatform.HttpPlatform\n | Path.Path;\n\n/** `METHOD /path` for every endpoint — what a register diffs a service against. */\nexport const endpointsOf = (\n groups: ReadonlyArray<AnyEndpointGroup>,\n): readonly string[] =>\n groups.flatMap(group =>\n group.endpoints.map(\n ({ descriptor }) => `${descriptor.method} ${descriptor.path}`,\n ),\n );\n\n/** The failures every endpoint may answer, whether or not it declares them. */\nconst TECHNICAL: readonly FailureClass[] = [\n Invalid,\n Internal,\n Unavailable,\n UpstreamUnavailable,\n Timeout,\n Overloaded,\n Contention,\n ProtocolFailure,\n];\n\nconst GUARD_FAILURES: Readonly<\n Record<AnyEndpoint['guard']['kind'], readonly FailureClass[]>\n> = {\n public: [],\n session: [Unauthenticated],\n permission: [Unauthenticated, Forbidden],\n organization: [Unauthenticated, Forbidden, NoActiveOrganization],\n crossing: [Unauthenticated, Forbidden],\n fleet: [Unauthenticated],\n};\n\nconst IDEMPOTENCY_FAILURES: readonly FailureClass[] = [\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n IdempotencyKeyInFlight,\n];\n\n/** The status a failure class answers with under `policy`. */\nexport const statusForClass = (\n failureClass: FailureClass,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failureClass.identifier] ??\n policy.categoryStatus[\n (failureClass.prototype as unknown as EntifixFailure).category\n ];\n\nconst errorSchemas = (descriptor: AnyEndpoint, policy: FailurePolicy) =>\n [\n ...new Set([\n ...descriptor.errors,\n ...GUARD_FAILURES[descriptor.guard.kind],\n ...(descriptor.idempotent === undefined ? [] : IDEMPOTENCY_FAILURES),\n ...TECHNICAL,\n ]),\n ].map(failureClass =>\n problemCodec(failureClass, statusForClass(failureClass, policy)),\n );\n\nconst toSchema = (schema: EndpointSchema | undefined) =>\n schema === undefined\n ? undefined\n : Schema.isSchema(schema)\n ? schema\n : Schema.Struct(schema);\n\n/** A payload on the wire it declared: JSON unless it said text or a form. */\nconst toPayload = (schema: EndpointSchema | undefined) => {\n const payload = toSchema(schema);\n if (payload === undefined) return undefined;\n const encoding = bodyEncodingOf(payload);\n switch (encoding?.kind) {\n case 'text':\n // A `textBody` is a string schema; the marker is what says so here.\n return (payload as Schema.String).pipe(\n HttpApiSchema.asText({ contentType: encoding.contentType }),\n );\n case 'form':\n return payload.pipe(\n HttpApiSchema.asFormUrlEncoded({ contentType: encoding.contentType }),\n );\n default:\n return payload;\n }\n};\n\n/**\n * The outermost middleware of every endpoint: `respond` under the API's\n * policy, after a schema error has become `invalid` with one entry per broken\n * field. A response that fails to encode is the service's own fault and stays\n * a defect.\n */\nexport class Respond extends HttpApiMiddleware.Service<Respond>()(\n '@entifix/service-shell/Respond',\n) {}\n\nconst formatIssues = SchemaIssue.makeFormatterStandardSchemaV1();\n\n/** The `invalid` failure a request that fails its schema answers with. */\nexport const invalidRequest = (\n error: HttpApiError.HttpApiSchemaError,\n): Invalid => {\n const where = error.kind.toLowerCase();\n const { issues } = formatIssues(error.cause.issue);\n return new Invalid({\n errors: issues.map(issue => ({\n // Effect's formatter always sets the path — `[]` for the part itself —\n // though the Standard Schema type it answers with leaves it optional.\n pointer: `/${[where, ...(issue.path as readonly PropertyKey[]).map(String)].join('/')}`,\n detail: issue.message,\n code: 'schema',\n })),\n });\n};\n\nconst REQUEST_PARTS: ReadonlySet<HttpApiError.HttpApiSchemaError['kind']> =\n new Set(['Params', 'Query', 'Payload', 'Headers']);\n\nconst respondLayer = (policy: FailurePolicy) =>\n Layer.succeed(Respond)(((httpEffect: Effect.Effect<never, unknown, never>) =>\n respond(\n httpEffect.pipe(\n Effect.catchIf(\n (error: unknown): error is HttpApiError.HttpApiSchemaError =>\n HttpApiError.HttpApiSchemaError.is(error) &&\n REQUEST_PARTS.has(error.kind),\n error => Effect.fail(invalidRequest(error)),\n ),\n ) as never,\n policy,\n ).pipe(Effect.map(uncachedByDefault))) as never);\n\n/**\n * Every answer `no-store` unless its endpoint chose a cache policy of its own.\n * An API answer carries a principal, a token or a tenant's records far more\n * often than anything a cache could share, and a token response must not be\n * stored at all (RFC 6749 §5.1) — so the safe default is the shell's, and an\n * endpoint that wants caching (an `ETag`ed metadata document) says so.\n */\nconst uncachedByDefault = (\n response: HttpServerResponse.HttpServerResponse,\n): HttpServerResponse.HttpServerResponse =>\n response.headers['cache-control'] === undefined\n ? HttpServerResponse.setHeader(response, 'cache-control', 'no-store')\n : response;\n\nconst toEndpoint = (descriptor: AnyEndpoint, policy: FailurePolicy) => {\n const params = toSchema(descriptor.params);\n const query = toSchema(descriptor.query);\n const payload = toPayload(descriptor.payload);\n const headers = toSchema(descriptor.headers);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n let endpoint: any = HttpApiEndpoint.make(descriptor.method)(\n descriptor.name,\n descriptor.path,\n {\n ...(params === undefined ? {} : { params }),\n ...(query === undefined ? {} : { query }),\n ...(payload === undefined ? {} : { payload }),\n ...(headers === undefined ? {} : { headers }),\n success: descriptor.success,\n error: errorSchemas(descriptor, policy),\n } as never,\n ).annotate(EndpointGuardAnnotation, descriptor.guard);\n // Order is outermost last: idempotency runs inside the guard, so it sees\n // the principal the guard verified; `Respond` wraps everything.\n if (descriptor.idempotent !== undefined)\n endpoint = endpoint\n .annotate(EndpointIdempotencyAnnotation, descriptor.idempotent)\n .middleware(IdempotencyGuard);\n const guard = GUARD_MIDDLEWARE[descriptor.guard.kind];\n if (guard !== undefined) endpoint = endpoint.middleware(guard);\n return endpoint.middleware(Respond);\n};\n\nexport interface ApiOptions {\n /** The status and log table; the framework's defaults when absent. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * The `HttpApi` a set of groups describes. Every endpoint's failures carry the\n * status the policy gives them, and two endpoints that share a method and\n * path throw here rather than shadowing each other at runtime.\n */\nexport const buildApi = (\n name: string,\n groups: ReadonlyArray<AnyEndpointGroup>,\n options: ApiOptions = {},\n): HttpApi.Top => {\n const policy = options.policy ?? defaultFailurePolicy;\n const seen = new Set<string>();\n for (const target of endpointsOf(groups)) {\n if (seen.has(target)) throw new Error(`'${name}' declares ${target} twice`);\n seen.add(target);\n }\n // A group serves its endpoints by name, so a second one under a name would\n // silently replace the first rather than fail.\n for (const group of groups) {\n const names = new Set<string>();\n for (const { descriptor } of group.endpoints) {\n if (names.has(descriptor.name))\n throw new Error(\n `'${name}' names two endpoints '${descriptor.name}' in '${group.name}'`,\n );\n names.add(descriptor.name);\n }\n }\n return groups.reduce<HttpApi.Top>(\n (api, group) =>\n api.add(\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (built: any, { descriptor }) =>\n built.add(toEndpoint(descriptor, policy)),\n HttpApiGroup.make(group.name),\n ),\n ) as HttpApi.Top,\n HttpApi.make(name) as unknown as HttpApi.Top,\n );\n};\n\n/**\n * Serve `groups` under one API: the routes, every guard, the respond\n * middleware. The layer requires what the handlers, guards and idempotency\n * modes read, plus the HTTP platform the server provides.\n */\nexport const serveApi = <const Groups extends ReadonlyArray<AnyEndpointGroup>>(\n api: HttpApi.Top,\n groups: Groups,\n options: ApiOptions = {},\n): Layer.Layer<never, never, ServedRequirements<Groups> | ServedPlatform> => {\n const handlers = groups.map(group =>\n HttpApiBuilder.group(\n api as never,\n group.name as never,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- assembled at runtime\n (handle: any) =>\n group.endpoints.reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (built: any, { descriptor, handler }) =>\n built.handle(descriptor.name, handler),\n handle,\n ),\n ),\n );\n return HttpApiBuilder.layer(api as never).pipe(\n Layer.provide(\n Layer.mergeAll(...(handlers as unknown as [Layer.Layer<never>])),\n ),\n Layer.provide(guardLayers),\n Layer.provide(respondLayer(options.policy ?? defaultFailurePolicy)),\n ) as never;\n};\n\n/** Build and serve in one call, for a host that needs nothing between. */\nexport const serveEndpoints = <\n const Groups extends ReadonlyArray<AnyEndpointGroup>,\n>(\n name: string,\n groups: Groups,\n options: ApiOptions = {},\n) => {\n const api = buildApi(name, groups, options);\n return { api, layer: serveApi(api, groups, options) } as const;\n};\n"],"names":["bodyEncodingOf","Contention","Forbidden","IdempotencyKeyInFlight","IdempotencyKeyMissing","IdempotencyKeyReused","Internal","Invalid","Overloaded","ProtocolFailure","Timeout","Unauthenticated","Unavailable","UpstreamUnavailable","Effect","Layer","Schema","SchemaIssue","HttpServerResponse","HttpApi","HttpApiBuilder","HttpApiEndpoint","HttpApiError","HttpApiGroup","HttpApiMiddleware","HttpApiSchema","NoActiveOrganization","defaultFailurePolicy","respond","EndpointGuardAnnotation","EndpointIdempotencyAnnotation","GUARD_MIDDLEWARE","guardLayers","IdempotencyGuard","problemCodec","endpointGroup","name","endpoints","endpointsOf","groups","flatMap","group","map","descriptor","method","path","TECHNICAL","GUARD_FAILURES","public","session","permission","organization","crossing","fleet","IDEMPOTENCY_FAILURES","statusForClass","failureClass","policy","tagStatus","identifier","categoryStatus","prototype","category","errorSchemas","Set","errors","guard","kind","idempotent","undefined","toSchema","schema","isSchema","Struct","toPayload","payload","encoding","pipe","asText","contentType","asFormUrlEncoded","Respond","Service","formatIssues","makeFormatterStandardSchemaV1","invalidRequest","error","where","toLowerCase","issues","cause","issue","pointer","String","join","detail","message","code","REQUEST_PARTS","respondLayer","succeed","httpEffect","catchIf","HttpApiSchemaError","is","has","fail","uncachedByDefault","response","headers","setHeader","toEndpoint","params","query","endpoint","make","success","annotate","middleware","buildApi","options","seen","target","Error","add","names","reduce","api","built","serveApi","handlers","handle","handler","layer","provide","mergeAll","serveEndpoints"],"mappings":";AAMA,SAEEA,cAAc,EACdC,UAAU,EAKVC,SAAS,EACTC,sBAAsB,EACtBC,qBAAqB,EACrBC,oBAAoB,EAEpBC,QAAQ,EACRC,OAAO,EACPC,UAAU,EACVC,eAAe,EACfC,OAAO,EACPC,eAAe,EACfC,WAAW,EACXC,mBAAmB,QACd,gBAAgB;AACvB,SACEC,MAAM,EAENC,KAAK,EAELC,MAAM,EACNC,WAAW,QACN,SAAS;AAEhB,SAASC,kBAAkB,QAAQ,cAAc;AACjD,SACEC,OAAO,EACPC,cAAc,EACdC,eAAe,EACfC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,SAAS,CAACyF,MAAM,CACpB,sFAAsF;QACtF,CAACE,OAAY,EAAErF,UAAU,EAAE,GACzBqF,MAAMJ,GAAG,CAACb,WAAWpE,YAAYc,UACnClC,aAAa4F,IAAI,CAAC1E,MAAML,IAAI,KAGlCjB,QAAQgG,IAAI,CAAC/E;AAEjB,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAM6F,WAAW,CACtBF,KACAxF,QACAiF,UAAsB,CAAC,CAAC;QAqBKA;IAnB7B,MAAMU,WAAW3F,OAAOG,GAAG,CAACD,CAAAA,QAC1BrB,eAAeqB,KAAK,CAClBsF,KACAtF,MAAML,IAAI,EACV,sFAAsF;QACtF,CAAC+F,SACC1F,MAAMJ,SAAS,CAACyF,MAAM,CACpB,8DAA8D;YAC9D,CAACE,OAAY,EAAErF,UAAU,EAAEyF,OAAO,EAAE,GAClCJ,MAAMG,MAAM,CAACxF,WAAWP,IAAI,EAAEgG,UAChCD;IAIR,OAAO/G,eAAeiH,KAAK,CAACN,KAAclD,IAAI,CAC5C9D,MAAMuH,OAAO,CACXvH,MAAMwH,QAAQ,IAAKL,YAErBnH,MAAMuH,OAAO,CAACtG,cACdjB,MAAMuH,OAAO,CAACnC,cAAaqB,kBAAAA,QAAQ/D,MAAM,YAAd+D,kBAAkB7F;AAEjD,EAAE;AAEF,wEAAwE,GACxE,OAAO,MAAM6G,iBAAiB,CAG5BpG,MACAG,QACAiF,UAAsB,CAAC,CAAC;IAExB,MAAMO,MAAMR,SAASnF,MAAMG,QAAQiF;IACnC,OAAO;QAAEO;QAAKM,OAAOJ,SAASF,KAAKxF,QAAQiF;IAAS;AACtD,EAAE"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { PolicyDecisionTag } from '@entifix/authz';
|
|
2
|
+
import { type EntityApiDeclaration, type EntityApiOptions, EntityFacetCounterFactoryTag, EntityRepositoryFactoryTag } from '@entifix/business';
|
|
3
|
+
import { type AnyEndpoint, type EndpointGuard, type Entity } from '@entifix/core';
|
|
4
|
+
import { Effect } from 'effect';
|
|
5
|
+
import { type MetadataCompositions } from '../metadata-composition.js';
|
|
6
|
+
import type { EndpointGroup } from './build-api.js';
|
|
7
|
+
type KindOf<G> = G extends {
|
|
8
|
+
readonly kind: infer Kind;
|
|
9
|
+
} ? Kind : G extends {
|
|
10
|
+
readonly read: infer Read;
|
|
11
|
+
readonly write: infer Write;
|
|
12
|
+
} ? KindOf<Read> | KindOf<Write> : never;
|
|
13
|
+
type OverrideValues<O> = O extends {
|
|
14
|
+
readonly override: infer Overrides;
|
|
15
|
+
} ? Overrides extends object ? NonNullable<Overrides[keyof Overrides]> : never : never;
|
|
16
|
+
type OverrideGuardKinds<V> = V extends {
|
|
17
|
+
readonly guard: infer G;
|
|
18
|
+
} ? KindOf<G> : never;
|
|
19
|
+
type OverrideIdempotency<V> = V extends {
|
|
20
|
+
readonly idempotent: infer I;
|
|
21
|
+
} ? I : never;
|
|
22
|
+
type UseCaseValues<O> = O extends {
|
|
23
|
+
readonly useCases: infer U;
|
|
24
|
+
} ? U extends ReadonlyArray<infer V> ? V : never : never;
|
|
25
|
+
/** Every guard kind an entity group mounts: `$metadata` is a session. */
|
|
26
|
+
export type EntityGuardKinds<O> = Extract<'session' | KindOf<O extends {
|
|
27
|
+
readonly guard: infer G;
|
|
28
|
+
} ? G : never> | OverrideGuardKinds<OverrideValues<O> | UseCaseValues<O>>, EndpointGuard['kind']>;
|
|
29
|
+
/** Every idempotency mode an entity group's overrides and verbs declare. */
|
|
30
|
+
export type EntityIdempotencies<O> = OverrideIdempotency<OverrideValues<O> | UseCaseValues<O>>;
|
|
31
|
+
type ReturnRequirements<F> = F extends (...args: any[]) => Effect.Effect<any, any, infer R> ? R : never;
|
|
32
|
+
type OverrideRequirements<V> = V extends {
|
|
33
|
+
readonly handler: infer H;
|
|
34
|
+
} ? ReturnRequirements<H> : never;
|
|
35
|
+
/** What the host's `prepare` and overrides need. */
|
|
36
|
+
export type OptionsRequirements<O> = ReturnRequirements<O extends {
|
|
37
|
+
readonly prepare: infer P;
|
|
38
|
+
} ? P : never> | OverrideRequirements<OverrideValues<O> | UseCaseValues<O>>;
|
|
39
|
+
/** An entity endpoint as its guard kinds and idempotency type it. */
|
|
40
|
+
export type EntityEndpoint<Kind extends EndpointGuard['kind'], Idempotency> = AnyEndpoint & {
|
|
41
|
+
readonly guard: Extract<EndpointGuard, {
|
|
42
|
+
readonly kind: Kind;
|
|
43
|
+
}>;
|
|
44
|
+
readonly idempotent?: Idempotency;
|
|
45
|
+
};
|
|
46
|
+
/** What the shell adds when it serves an entity's declared endpoints. */
|
|
47
|
+
export interface EntityApiServing {
|
|
48
|
+
/** The compositions `$metadata` reports for the entity's verbs. */
|
|
49
|
+
readonly compositions?: MetadataCompositions;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The generic endpoints of an entity — list, get, create, update, delete,
|
|
53
|
+
* `$metadata` and, when asked, `$facets` — as one group named for its key
|
|
54
|
+
* ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
|
|
55
|
+
*
|
|
56
|
+
* `$metadata` and `$facets` come before `/:id`, so neither is read as an id.
|
|
57
|
+
* The list query is the entity's RSQL request, parsed against its own
|
|
58
|
+
* `filterable`/`sortable` metadata: a member that is not queryable answers
|
|
59
|
+
* `invalidQuery`. A narrowing is conjoined onto every read and count, never
|
|
60
|
+
* substituted, and a reader it leaves with nothing gets an empty page and a
|
|
61
|
+
* `404`, never a `403`.
|
|
62
|
+
*
|
|
63
|
+
* It serves a declaration the domain made with `defineEntityApi`; what the
|
|
64
|
+
* shell alone knows — the recipes and variants `$metadata` resolves verbs
|
|
65
|
+
* against — is added here.
|
|
66
|
+
*/
|
|
67
|
+
export declare const entityApi: <T extends Entity, const K extends string, const O extends EntityApiOptions<T, any>>(declaration: EntityApiDeclaration<T, K, O>, serving?: EntityApiServing) => EndpointGroup<EntityEndpoint<EntityGuardKinds<O>, EntityIdempotencies<O>>, OptionsRequirements<O> | EntityRepositoryFactoryTag | PolicyDecisionTag | (O["facets"] extends true ? EntityFacetCounterFactoryTag : never)>;
|
|
68
|
+
export {};
|
|
69
|
+
//# sourceMappingURL=entity-api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entity-api.d.ts","sourceRoot":"","sources":["../../src/http-api/entity-api.ts"],"names":[],"mappings":"AAEA,OAAO,EAML,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAGL,KAAK,oBAAoB,EAGzB,KAAK,gBAAgB,EAGrB,4BAA4B,EAI5B,0BAA0B,EAa3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,WAAW,EAGhB,KAAK,aAAa,EAClB,KAAK,MAAM,EAqBZ,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAkB,MAAM,QAAQ,CAAC;AAIhD,OAAO,EAGL,KAAK,oBAAoB,EAC1B,MAAM,4BAA4B,CAAC;AAMpC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAyFpD,KAAK,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,IAAI,CAAA;CAAE,GACpD,IAAI,GACJ,CAAC,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,IAAI,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,KAAK,CAAA;CAAE,GAClE,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,GAC5B,KAAK,CAAC;AAEZ,KAAK,cAAc,CAAC,CAAC,IAAI,CAAC,SAAS;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,SAAS,CAAA;CAAE,GACrE,SAAS,SAAS,MAAM,GACtB,WAAW,CAAC,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC,GACvC,KAAK,GACP,KAAK,CAAC;AAGV,KAAK,kBAAkB,CAA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