@entifix/next-shell 0.13.0 → 0.14.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.
- package/dist/lib/config/service-proxy-route.js +1 -1
- package/dist/lib/config/service-proxy-route.js.map +1 -1
- package/dist/lib/crud/entity-crud-form.d.ts +5 -3
- package/dist/lib/crud/entity-crud-form.d.ts.map +1 -1
- package/dist/lib/crud/entity-crud-form.js +2 -1
- package/dist/lib/crud/entity-crud-form.js.map +1 -1
- package/dist/lib/crud/make-entity-crud.d.ts.map +1 -1
- package/dist/lib/crud/make-entity-crud.js +124 -53
- package/dist/lib/crud/make-entity-crud.js.map +1 -1
- package/dist/lib/crud/make-entity-crud.types.d.ts +13 -1
- package/dist/lib/crud/make-entity-crud.types.d.ts.map +1 -1
- package/dist/lib/crud/make-entity-crud.types.js.map +1 -1
- package/dist/lib/session/bearer.d.ts +1 -1
- package/dist/lib/session/bearer.js +1 -1
- package/dist/lib/session/bearer.js.map +1 -1
- package/dist/lib/workspace/index.d.ts +1 -0
- package/dist/lib/workspace/index.d.ts.map +1 -1
- package/dist/lib/workspace/index.js +1 -0
- package/dist/lib/workspace/index.js.map +1 -1
- package/dist/lib/workspace/pending-flows.d.ts +48 -0
- package/dist/lib/workspace/pending-flows.d.ts.map +1 -0
- package/dist/lib/workspace/pending-flows.js +60 -0
- package/dist/lib/workspace/pending-flows.js.map +1 -0
- package/package.json +11 -11
|
@@ -16,7 +16,7 @@ import { problemResponse } from './problem-response.js';
|
|
|
16
16
|
*
|
|
17
17
|
* The cookie is forwarded upstream as a bearer token. **This proxy grants
|
|
18
18
|
* nothing** — the service still verifies the token and applies its own
|
|
19
|
-
* `
|
|
19
|
+
* the endpoint's `guard`. It only carries.
|
|
20
20
|
*
|
|
21
21
|
* It also carries the **caching contract** in both directions, which it did not
|
|
22
22
|
* always: rebuilding every response as a fresh body dropped `ETag`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/config/service-proxy-route.ts"],"sourcesContent":["import { DEADLINE_HEADER, UpstreamUnavailable } from '@entifix/core';\nimport { NextResponse } from 'next/server';\n\nimport { bearerHeader, sessionToken } from '../session/bearer.js';\nimport { problemResponse } from './problem-response.js';\n\ntype Params = { params: Promise<{ path: string[] }> };\n\nexport interface ServiceProxyRouteOptions {\n /** Where the service listens, without the `/api` suffix. */\n readonly baseUrl: string;\n /**\n * A segment to put back in front of the forwarded path.\n *\n * ⚠️ **Needed when the proxy's namespace *is* the upstream's route name.**\n * `/api/stock/stock-item` forwards to `/api/stock-item` because `stock` names\n * the service and `stock-item` names the entity — two different words. But\n * `/api/transaction/events` forwards to `/api/events`, which exists nowhere:\n * there the namespace and the route are the same word, and stripping it\n * strips half the address.\n *\n * Caught on the live lab rather than by any check, and the symptom is exactly\n * the one this proxy exists to prevent — the SSE stream 404s, a pending write\n * never settles, and every probe stays green.\n */\n readonly pathPrefix?: string;\n}\n\n/**\n * Builds a same-origin proxy for one backend service, mounted as a catch-all\n * route handler — e.g. `app/api/admin/[...path]/route.ts`.\n *\n * The browser can never call `:310N` directly: `entifix_at` is httpOnly and\n * same-origin, so a cross-origin request carries no cookie and a guarded route\n * answers `401`. Host-scoping the cookie does not help — that governs which host\n * *stores* it, not which cross-origin requests send it. Routing through the app's\n * own origin makes the cookie automatic and needs no CORS, which is the same\n * reason the credential routes are shaped this way.\n *\n * The cookie is forwarded upstream as a bearer token. **This proxy grants\n * nothing** — the service still verifies the token and applies its own\n * `requirePermission`. It only carries.\n *\n * It also carries the **caching contract** in both directions, which it did not\n * always: rebuilding every response as a fresh body dropped `ETag`,\n * `Cache-Control` and `Vary`, and forwarded no `If-None-Match`. The effect was\n * invisible and entirely wasteful — `GET /api/<entity>/$metadata` computes and\n * hashes a permission-filtered document per request, and a validator that never\n * reaches the service means it can never answer `304`. Worse, `Vary` is a\n * *correctness* header here: the document differs per caller, and one stripped\n * of `Vary: Cookie, Authorization` may be cached and served to a different\n * principal.\n *\n * A factory, because a host mounts one of these per backend it talks to, and\n * back-office-app now talks to two: marketplace-admin-service for the catalog a\n * vendor authors, marketplace-service for the platform vocabulary it is\n * classified in.\n */\n/**\n * Response headers that must survive the rebuild.\n *\n * Deliberately a short allow-list rather than copying every header: the\n * upstream's `content-length` and `content-encoding` describe *its* body, and\n * carrying them onto a response this function reconstructs is how a proxy\n * serves a truncated payload. Beside the cache validators: `retry-after`,\n * which says when an overloaded service wants to be asked again; `location`,\n * which a `202` points its tracker at; and `traceparent`, so the browser's\n * failure toast can name the trace a service logged its side under.\n */\nconst PASSED_RESPONSE_HEADERS = [\n 'etag',\n 'cache-control',\n 'vary',\n 'retry-after',\n 'location',\n 'traceparent',\n] as const;\n\n/**\n * Request headers forwarded to the service, beside the bearer it gets from\n * the session: the validator, so `$metadata` can answer `304`; the\n * idempotency key, so a retried write is recognised; the trace, so one\n * request is one trace across the hop; and the caller's remaining budget\n * ([ADR 0014](../../../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst FORWARDED_REQUEST_HEADERS = [\n 'if-none-match',\n 'idempotency-key',\n 'traceparent',\n DEADLINE_HEADER,\n] as const;\n\n/**\n * Whether the upstream answer must be piped rather than rebuilt.\n *\n * Reading a `text/event-stream` body to completion holds the request open\n * forever and delivers nothing — no error, no timeout, and the browser's\n * `EventSource` sits in `CONNECTING` while the service is happily emitting.\n * It is the most likely way to build the reactive stream, see silence, and go\n * looking in the wrong service.\n */\nconst isStreamed = (upstream: Response): boolean =>\n upstream.headers.get('content-type')?.startsWith('text/event-stream') ===\n true;\n\nconst passThrough = (upstream: Response): Record<string, string> => {\n const headers: Record<string, string> = {};\n for (const name of PASSED_RESPONSE_HEADERS) {\n const value = upstream.headers.get(name);\n if (value !== null) headers[name] = value;\n }\n return headers;\n};\n\nexport const createServiceProxyRoute = ({\n baseUrl,\n pathPrefix,\n}: ServiceProxyRouteOptions) => {\n const forward = async (\n request: Request,\n { params }: Params,\n ): Promise<Response> => {\n const { path } = await params;\n const search = new URL(request.url).search;\n\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...bearerHeader(await sessionToken()),\n };\n\n for (const name of FORWARDED_REQUEST_HEADERS) {\n const value = request.headers.get(name);\n if (value !== null) headers[name] = value;\n }\n\n const hasBody = request.method !== 'GET' && request.method !== 'DELETE';\n const body = hasBody ? await request.text() : undefined;\n // Only the connection is caught. A service that answers — with anything,\n // a `500` included — is passed through below exactly as it answered.\n const upstream = await fetch(\n `${baseUrl}/api/${[pathPrefix, ...path].filter(Boolean).join('/')}${search}`,\n { method: request.method, headers, body, cache: 'no-store' },\n ).catch(() => undefined);\n\n // `502`, never the `500` an unhandled rejection becomes: the host did\n // nothing wrong, and a `500` sends whoever reads it looking for a bug in\n // the app rather than for a process that is not running.\n if (upstream === undefined) {\n return problemResponse(\n new UpstreamUnavailable(\n pathPrefix === undefined ? {} : { upstream: pathPrefix },\n ),\n {\n status: 502,\n },\n );\n }\n\n const passed = passThrough(upstream);\n\n // A `304` carries no body by definition, and neither does a `204`. Running\n // either through a body read is not merely wasteful — a `304` reconstructed\n // with a body is no longer a `304`.\n if (upstream.status === 304) {\n return new NextResponse(null, { status: 304, headers: passed });\n }\n\n // Piped, never buffered, and never re-typed as JSON: the body is an open\n // stream of frames, and `no-store` is correctness rather than politeness —\n // this response is scoped to one principal.\n if (isStreamed(upstream)) {\n return new NextResponse(upstream.body, {\n status: upstream.status,\n headers: {\n ...passed,\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-store',\n },\n });\n }\n\n // 204s and empty bodies must not be given a body. The upstream's content\n // type is kept, never re-typed: a problem body re-typed as plain JSON is\n // one the browser can no longer recognise as a failure it can decode.\n const text = await upstream.text();\n return text === ''\n ? new NextResponse(null, { status: upstream.status, headers: passed })\n : new NextResponse(text, {\n status: upstream.status,\n headers: {\n ...passed,\n 'content-type':\n upstream.headers.get('content-type') ?? 'application/json',\n },\n });\n };\n\n return forward;\n};\n"],"names":["DEADLINE_HEADER","UpstreamUnavailable","NextResponse","bearerHeader","sessionToken","problemResponse","PASSED_RESPONSE_HEADERS","FORWARDED_REQUEST_HEADERS","isStreamed","upstream","headers","get","startsWith","passThrough","name","value","createServiceProxyRoute","baseUrl","pathPrefix","forward","request","params","path","search","URL","url","hasBody","method","body","text","undefined","fetch","filter","Boolean","join","cache","catch","status","passed"],"mappings":";AAAA,SAASA,eAAe,EAAEC,mBAAmB,QAAQ,gBAAgB;AACrE,SAASC,YAAY,QAAQ,cAAc;AAE3C,SAASC,YAAY,EAAEC,YAAY,QAAQ,uBAAuB;AAClE,SAASC,eAAe,QAAQ,wBAAwB;AAwBxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD;;;;;;;;;;CAUC,GACD,MAAMC,0BAA0B;IAC9B;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;;;CAMC,GACD,MAAMC,4BAA4B;IAChC;IACA;IACA;IACAP;CACD;AAED;;;;;;;;CAQC,GACD,MAAMQ,aAAa,CAACC;QAClBA;WAAAA,EAAAA,wBAAAA,SAASC,OAAO,CAACC,GAAG,CAAC,oCAArBF,sBAAsCG,UAAU,CAAC,0BACjD;;AAEF,MAAMC,cAAc,CAACJ;IACnB,MAAMC,UAAkC,CAAC;IACzC,KAAK,MAAMI,QAAQR,wBAAyB;QAC1C,MAAMS,QAAQN,SAASC,OAAO,CAACC,GAAG,CAACG;QACnC,IAAIC,UAAU,MAAML,OAAO,CAACI,KAAK,GAAGC;IACtC;IACA,OAAOL;AACT;AAEA,OAAO,MAAMM,0BAA0B,CAAC,EACtCC,OAAO,EACPC,UAAU,EACe;IACzB,MAAMC,UAAU,OACdC,SACA,EAAEC,MAAM,EAAU;YAwERZ;QAtEV,MAAM,EAAEa,IAAI,EAAE,GAAG,MAAMD;QACvB,MAAME,SAAS,IAAIC,IAAIJ,QAAQK,GAAG,EAAEF,MAAM;QAE1C,MAAMb,UAAkC;YACtC,gBAAgB;WACbP,aAAa,MAAMC;QAGxB,KAAK,MAAM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aAAa,MAAM;YAAEmC,QAAQ5B,SAAS4B,MAAM;YAAE3B,SAAS4B;QAAO,KAClE,IAAIpC,aAAa2B,MAAM;YACrBQ,QAAQ5B,SAAS4B,MAAM;YACvB3B,SAAS,aACJ4B;gBACH,cAAc,GACZ7B,wBAAAA,SAASC,OAAO,CAACC,GAAG,CAAC,2BAArBF,wBAAwC;;QAE9C;IACN;IAEA,OAAOU;AACT,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/config/service-proxy-route.ts"],"sourcesContent":["import { DEADLINE_HEADER, UpstreamUnavailable } from '@entifix/core';\nimport { NextResponse } from 'next/server';\n\nimport { bearerHeader, sessionToken } from '../session/bearer.js';\nimport { problemResponse } from './problem-response.js';\n\ntype Params = { params: Promise<{ path: string[] }> };\n\nexport interface ServiceProxyRouteOptions {\n /** Where the service listens, without the `/api` suffix. */\n readonly baseUrl: string;\n /**\n * A segment to put back in front of the forwarded path.\n *\n * ⚠️ **Needed when the proxy's namespace *is* the upstream's route name.**\n * `/api/stock/stock-item` forwards to `/api/stock-item` because `stock` names\n * the service and `stock-item` names the entity — two different words. But\n * `/api/transaction/events` forwards to `/api/events`, which exists nowhere:\n * there the namespace and the route are the same word, and stripping it\n * strips half the address.\n *\n * Caught on the live lab rather than by any check, and the symptom is exactly\n * the one this proxy exists to prevent — the SSE stream 404s, a pending write\n * never settles, and every probe stays green.\n */\n readonly pathPrefix?: string;\n}\n\n/**\n * Builds a same-origin proxy for one backend service, mounted as a catch-all\n * route handler — e.g. `app/api/admin/[...path]/route.ts`.\n *\n * The browser can never call `:310N` directly: `entifix_at` is httpOnly and\n * same-origin, so a cross-origin request carries no cookie and a guarded route\n * answers `401`. Host-scoping the cookie does not help — that governs which host\n * *stores* it, not which cross-origin requests send it. Routing through the app's\n * own origin makes the cookie automatic and needs no CORS, which is the same\n * reason the credential routes are shaped this way.\n *\n * The cookie is forwarded upstream as a bearer token. **This proxy grants\n * nothing** — the service still verifies the token and applies its own\n * the endpoint's `guard`. It only carries.\n *\n * It also carries the **caching contract** in both directions, which it did not\n * always: rebuilding every response as a fresh body dropped `ETag`,\n * `Cache-Control` and `Vary`, and forwarded no `If-None-Match`. The effect was\n * invisible and entirely wasteful — `GET /api/<entity>/$metadata` computes and\n * hashes a permission-filtered document per request, and a validator that never\n * reaches the service means it can never answer `304`. Worse, `Vary` is a\n * *correctness* header here: the document differs per caller, and one stripped\n * of `Vary: Cookie, Authorization` may be cached and served to a different\n * principal.\n *\n * A factory, because a host mounts one of these per backend it talks to, and\n * back-office-app now talks to two: marketplace-admin-service for the catalog a\n * vendor authors, marketplace-service for the platform vocabulary it is\n * classified in.\n */\n/**\n * Response headers that must survive the rebuild.\n *\n * Deliberately a short allow-list rather than copying every header: the\n * upstream's `content-length` and `content-encoding` describe *its* body, and\n * carrying them onto a response this function reconstructs is how a proxy\n * serves a truncated payload. Beside the cache validators: `retry-after`,\n * which says when an overloaded service wants to be asked again; `location`,\n * which a `202` points its tracker at; and `traceparent`, so the browser's\n * failure toast can name the trace a service logged its side under.\n */\nconst PASSED_RESPONSE_HEADERS = [\n 'etag',\n 'cache-control',\n 'vary',\n 'retry-after',\n 'location',\n 'traceparent',\n] as const;\n\n/**\n * Request headers forwarded to the service, beside the bearer it gets from\n * the session: the validator, so `$metadata` can answer `304`; the\n * idempotency key, so a retried write is recognised; the trace, so one\n * request is one trace across the hop; and the caller's remaining budget\n * ([ADR 0014](../../../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst FORWARDED_REQUEST_HEADERS = [\n 'if-none-match',\n 'idempotency-key',\n 'traceparent',\n DEADLINE_HEADER,\n] as const;\n\n/**\n * Whether the upstream answer must be piped rather than rebuilt.\n *\n * Reading a `text/event-stream` body to completion holds the request open\n * forever and delivers nothing — no error, no timeout, and the browser's\n * `EventSource` sits in `CONNECTING` while the service is happily emitting.\n * It is the most likely way to build the reactive stream, see silence, and go\n * looking in the wrong service.\n */\nconst isStreamed = (upstream: Response): boolean =>\n upstream.headers.get('content-type')?.startsWith('text/event-stream') ===\n true;\n\nconst passThrough = (upstream: Response): Record<string, string> => {\n const headers: Record<string, string> = {};\n for (const name of PASSED_RESPONSE_HEADERS) {\n const value = upstream.headers.get(name);\n if (value !== null) headers[name] = value;\n }\n return headers;\n};\n\nexport const createServiceProxyRoute = ({\n baseUrl,\n pathPrefix,\n}: ServiceProxyRouteOptions) => {\n const forward = async (\n request: Request,\n { params }: Params,\n ): Promise<Response> => {\n const { path } = await params;\n const search = new URL(request.url).search;\n\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...bearerHeader(await sessionToken()),\n };\n\n for (const name of FORWARDED_REQUEST_HEADERS) {\n const value = request.headers.get(name);\n if (value !== null) headers[name] = value;\n }\n\n const hasBody = request.method !== 'GET' && request.method !== 'DELETE';\n const body = hasBody ? await request.text() : undefined;\n // Only the connection is caught. A service that answers — with anything,\n // a `500` included — is passed through below exactly as it answered.\n const upstream = await fetch(\n `${baseUrl}/api/${[pathPrefix, ...path].filter(Boolean).join('/')}${search}`,\n { method: request.method, headers, body, cache: 'no-store' },\n ).catch(() => undefined);\n\n // `502`, never the `500` an unhandled rejection becomes: the host did\n // nothing wrong, and a `500` sends whoever reads it looking for a bug in\n // the app rather than for a process that is not running.\n if (upstream === undefined) {\n return problemResponse(\n new UpstreamUnavailable(\n pathPrefix === undefined ? {} : { upstream: pathPrefix },\n ),\n {\n status: 502,\n },\n );\n }\n\n const passed = passThrough(upstream);\n\n // A `304` carries no body by definition, and neither does a `204`. Running\n // either through a body read is not merely wasteful — a `304` reconstructed\n // with a body is no longer a `304`.\n if (upstream.status === 304) {\n return new NextResponse(null, { status: 304, headers: passed });\n }\n\n // Piped, never buffered, and never re-typed as JSON: the body is an open\n // stream of frames, and `no-store` is correctness rather than politeness —\n // this response is scoped to one principal.\n if (isStreamed(upstream)) {\n return new NextResponse(upstream.body, {\n status: upstream.status,\n headers: {\n ...passed,\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-store',\n },\n });\n }\n\n // 204s and empty bodies must not be given a body. The upstream's content\n // type is kept, never re-typed: a problem body re-typed as plain JSON is\n // one the browser can no longer recognise as a failure it can decode.\n const text = await upstream.text();\n return text === ''\n ? new NextResponse(null, { status: upstream.status, headers: passed })\n : new NextResponse(text, {\n status: upstream.status,\n headers: {\n ...passed,\n 'content-type':\n upstream.headers.get('content-type') ?? 'application/json',\n },\n });\n };\n\n return forward;\n};\n"],"names":["DEADLINE_HEADER","UpstreamUnavailable","NextResponse","bearerHeader","sessionToken","problemResponse","PASSED_RESPONSE_HEADERS","FORWARDED_REQUEST_HEADERS","isStreamed","upstream","headers","get","startsWith","passThrough","name","value","createServiceProxyRoute","baseUrl","pathPrefix","forward","request","params","path","search","URL","url","hasBody","method","body","text","undefined","fetch","filter","Boolean","join","cache","catch","status","passed"],"mappings":";AAAA,SAASA,eAAe,EAAEC,mBAAmB,QAAQ,gBAAgB;AACrE,SAASC,YAAY,QAAQ,cAAc;AAE3C,SAASC,YAAY,EAAEC,YAAY,QAAQ,uBAAuB;AAClE,SAASC,eAAe,QAAQ,wBAAwB;AAwBxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD;;;;;;;;;;CAUC,GACD,MAAMC,0BAA0B;IAC9B;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;;;CAMC,GACD,MAAMC,4BAA4B;IAChC;IACA;IACA;IACAP;CACD;AAED;;;;;;;;CAQC,GACD,MAAMQ,aAAa,CAACC;QAClBA;WAAAA,EAAAA,wBAAAA,SAASC,OAAO,CAACC,GAAG,CAAC,oCAArBF,sBAAsCG,UAAU,CAAC,0BACjD;;AAEF,MAAMC,cAAc,CAACJ;IACnB,MAAMC,UAAkC,CAAC;IACzC,KAAK,MAAMI,QAAQR,wBAAyB;QAC1C,MAAMS,QAAQN,SAASC,OAAO,CAACC,GAAG,CAACG;QACnC,IAAIC,UAAU,MAAML,OAAO,CAACI,KAAK,GAAGC;IACtC;IACA,OAAOL;AACT;AAE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AA4C;QAC5C,IAAI9B,WAAWC,WAAW;YACxB,OAAO,IAAIP,aAAaO,SAASmB,IAAI,EAAE;gBACrCS,QAAQ5B,SAAS4B,MAAM;gBACvB3B,SAAS,aACJ4B;oBACH,gBAAgB;oBAChB,iBAAiB;;YAErB;QACF;QAEA,yEAAyE;QACzE,yEAAyE;QACzE,sEAAsE;QACtE,MAAMT,OAAO,MAAMpB,SAASoB,IAAI;QAChC,OAAOA,SAAS,KACZ,IAAI3B,aAAa,MAAM;YAAEmC,QAAQ5B,SAAS4B,MAAM;YAAE3B,SAAS4B;QAAO,KAClE,IAAIpC,aAAa2B,MAAM;YACrBQ,QAAQ5B,SAAS4B,MAAM;YACvB3B,SAAS,aACJ4B;gBACH,cAAc,GACZ7B,wBAAAA,SAASC,OAAO,CAACC,GAAG,CAAC,2BAArBF,wBAAwC;;QAE9C;IACN;IAEA,OAAOU;AACT,EAAE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type EntifixFailure, type Entity, type EntityConstructor, type EntityMetadataSource } from '@entifix/core';
|
|
2
2
|
import { type RenderLink } from '@entifix/react-controls';
|
|
3
3
|
import { type EntityDraftStore } from '@entifix/react-integration';
|
|
4
4
|
import type { EntityCatalogKey, EntityCrudLinkSource } from './make-entity-crud.types.js';
|
|
@@ -11,8 +11,10 @@ export interface EntityCrudFormProps<TEntity extends Entity> {
|
|
|
11
11
|
readonly entity?: TEntity;
|
|
12
12
|
readonly isLoading?: boolean;
|
|
13
13
|
readonly isSaving?: boolean;
|
|
14
|
+
/** A write handed to a flow that has not settled: the form waits, keeping its input. */
|
|
15
|
+
readonly isPending?: boolean;
|
|
14
16
|
readonly isDeleting?: boolean;
|
|
15
|
-
readonly error?:
|
|
17
|
+
readonly error?: EntifixFailure;
|
|
16
18
|
readonly onSave: (entity: TEntity) => void;
|
|
17
19
|
/** Omitted for a create — there is nothing to delete yet. */
|
|
18
20
|
readonly onDelete?: () => void;
|
|
@@ -48,5 +50,5 @@ export interface EntityCrudFormProps<TEntity extends Entity> {
|
|
|
48
50
|
* `useEntityForm` owns the draft and seeds it once, so the page keys this
|
|
49
51
|
* component by the record id to reseed when the record arrives.
|
|
50
52
|
*/
|
|
51
|
-
export declare function EntityCrudForm<TEntity extends Entity>({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading, isSaving, isDeleting, error, onSave, onDelete, backHref, renderLink, draft, metadataSource, onUseCase, }: EntityCrudFormProps<TEntity>): import("react").JSX.Element;
|
|
53
|
+
export declare function EntityCrudForm<TEntity extends Entity>({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading, isSaving, isPending, isDeleting, error, onSave, onDelete, backHref, renderLink, draft, metadataSource, onUseCase, }: EntityCrudFormProps<TEntity>): import("react").JSX.Element;
|
|
52
54
|
//# sourceMappingURL=entity-crud-form.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity-crud-form.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/entity-crud-form.tsx"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,
|
|
1
|
+
{"version":3,"file":"entity-crud-form.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/entity-crud-form.tsx"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EAE1B,MAAM,eAAe,CAAC;AACvB,OAAO,EAGL,KAAK,UAAU,EAGhB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,KAAK,gBAAgB,EAEtB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,KAAK,EACV,gBAAgB,EAChB,oBAAoB,EACrB,MAAM,6BAA6B,CAAC;AAKrC,MAAM,WAAW,mBAAmB,CAAC,OAAO,SAAS,MAAM;IACzD,QAAQ,CAAC,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,CA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ACV,KAAK,EACL,cAAc,EACd,SAAS,GACV,EAAE,mBAAmB,CAAC,OAAO,CAAC,+BAkH9B"}
|
|
@@ -22,7 +22,7 @@ import { validationMessagesFor } from './validation-messages.js';
|
|
|
22
22
|
*
|
|
23
23
|
* `useEntityForm` owns the draft and seeds it once, so the page keys this
|
|
24
24
|
* component by the record id to reseed when the record arrives.
|
|
25
|
-
*/ export function EntityCrudForm({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading = false, isSaving = false, isDeleting = false, error, onSave, onDelete, backHref, renderLink, draft, metadataSource, onUseCase }) {
|
|
25
|
+
*/ export function EntityCrudForm({ entityConstructor, catalogKey, hiddenFields, links, entity, isLoading = false, isSaving = false, isPending = false, isDeleting = false, error, onSave, onDelete, backHref, renderLink, draft, metadataSource, onUseCase }) {
|
|
26
26
|
const et = useT('entity');
|
|
27
27
|
const ct = useT('controls');
|
|
28
28
|
// `controls` copy, resolved here and handed down; see validationMessagesFor.
|
|
@@ -110,6 +110,7 @@ import { validationMessagesFor } from './validation-messages.js';
|
|
|
110
110
|
onUseCase: onUseCase,
|
|
111
111
|
isLoading: isLoading,
|
|
112
112
|
isSaving: isSaving,
|
|
113
|
+
isPending: isPending,
|
|
113
114
|
isDeleting: isDeleting,
|
|
114
115
|
error: error,
|
|
115
116
|
backHref: backHref,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/crud/entity-crud-form.tsx"],"sourcesContent":["'use client';\n\nimport {\n type Entity,\n type EntityConstructor,\n type EntityMetadataSource,\n reconstructEntity,\n type TransitionalFailure,\n} from '@entifix/core';\nimport {\n EntityField,\n EntityForm,\n type RenderLink,\n useT,\n useTranslateKey,\n} from '@entifix/react-controls';\nimport {\n type EntityDraftStore,\n useEntityForm,\n} from '@entifix/react-integration';\nimport { useEffect, useMemo } from 'react';\n\nimport type {\n EntityCatalogKey,\n EntityCrudLinkSource,\n} from './make-entity-crud.types.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityLinkSources } from './use-entity-link-sources.js';\nimport { validationMessagesFor } from './validation-messages.js';\n\nexport interface EntityCrudFormProps<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n readonly catalogKey: EntityCatalogKey;\n readonly hiddenFields: readonly string[];\n readonly links: readonly EntityCrudLinkSource[];\n /** The record being edited; `undefined` means this is a create. */\n readonly entity?: TEntity;\n readonly isLoading?: boolean;\n readonly isSaving?: boolean;\n readonly isDeleting?: boolean;\n readonly error?: TransitionalFailure;\n readonly onSave: (entity: TEntity) => void;\n /** Omitted for a create — there is nothing to delete yet. */\n readonly onDelete?: () => void;\n readonly backHref: string;\n /** Renders the Back link; see `useCrudRenderLink`. */\n readonly renderLink?: RenderLink;\n /**\n * Where to autosave this form's draft. Omitted by a route host, which is what\n * keeps a plain route ephemeral; the workspace tab host supplies one.\n */\n readonly draft?: EntityDraftStore;\n /**\n * Where this caller's affordances come from. Absent keeps the pre-ADR-0026\n * behaviour: Save and Delete render unconditionally and no declared verb\n * appears — which is what every generated catalog did before it existed.\n */\n readonly metadataSource?: EntityMetadataSource;\n /** Runs a declared `entity`-bound verb on this record, by its key. */\n readonly onUseCase?: (key: string) => void;\n}\n\n/**\n * The generated create/update form. A thin wrapper over the agnostic\n * {@link EntityForm}: every field, label and validation rule comes from the\n * entity's own accessor metadata, and `reconstructEntity` derives the submit\n * rebuild from that same metadata — so nothing here is per-entity but the\n * constructor, the catalog key and the hidden-field list.\n *\n * A hidden member still round-trips. `code` is assigned by the create\n * transaction and never shown, but it is a plain writable member, so the rebuild\n * picks it out of the seeded draft; dropping it from the rendered fields is not\n * dropping it from the draft.\n *\n * `useEntityForm` owns the draft and seeds it once, so the page keys this\n * component by the record id to reseed when the record arrives.\n */\nexport function EntityCrudForm<TEntity extends Entity>({\n entityConstructor,\n catalogKey,\n hiddenFields,\n links,\n entity,\n isLoading = false,\n isSaving = false,\n isDeleting = false,\n error,\n onSave,\n onDelete,\n backHref,\n renderLink,\n draft,\n metadataSource,\n onUseCase,\n}: EntityCrudFormProps<TEntity>) {\n const et = useT('entity');\n const ct = useT('controls');\n\n // `controls` copy, resolved here and handed down; see validationMessagesFor.\n const validationMessages = useMemo(() => validationMessagesFor(ct), [ct]);\n\n // A runtime-key translator, so a message names the field by its catalog word\n // (`labelKey`) and a schema's keyed message resolves at all. Without it both\n // fell back to untranslated text inside an otherwise Spanish sentence.\n const translateKey = useTranslateKey();\n\n const form = useEntityForm<TEntity>({\n entityConstructor,\n entity,\n validationMessages,\n translateKey,\n draft,\n onSubmit: values =>\n onSave(\n reconstructEntity(entityConstructor, values, { existing: entity }),\n ),\n });\n\n const linkSources = useEntityLinkSources(links, {\n values: form.values,\n selection: form.links,\n });\n\n // Refill the relation sidecar from the ids the draft did keep.\n //\n // A draft is JSON, so it holds ids and nothing else; the instances behind them\n // die with the page. Each picker already resolves its id — that is how a\n // restored draft shows a brand's name instead of its key — so the instance is\n // in hand and only has to be handed back. Without this, a member declared\n // `linkSerialization: 'embedded'` reaches `applyEntityLinks` with an id and no\n // target, which it refuses rather than writing the wrong wire shape.\n //\n // `hydrateLink`, not `setLink`: this is a lookup landing, not a pick, so it\n // must leave the draft — and the form's dirty flag — alone.\n const { links: selection, hydrateLink } = form;\n useEffect(() => {\n for (const [field, source] of Object.entries(linkSources)) {\n const resolved = source.selected.entity;\n if (resolved !== undefined && selection[field] === undefined) {\n hydrateLink(field, resolved);\n }\n }\n }, [linkSources, selection, hydrateLink]);\n\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n\n /**\n * May this caller write the record in front of them?\n *\n * The **same authority that withholds Save**, applied one step earlier.\n * Absent metadata keeps the pre-ADR-0026 behaviour, so an un-migrated call\n * site is untouched; present metadata is authoritative, because it is what\n * the service already decided.\n *\n * ⚠️ Without this the form rendered inputs nobody could submit. Measured on\n * the stock surface: `stock-item` answers `[\"read\"]` — no role holds\n * `stock-item:write` and there is no save route — so Save was correctly\n * absent while `onHand` and `reserved` still rendered as **enabled number\n * inputs**. A vendor could type a new quantity into a field that is only ever\n * moved by a ledger, and nothing would happen and nothing would say why.\n *\n * A create is exempt: there is no record yet, so there is nothing to read and\n * a `read` mode would render an empty form with no way to fill it.\n */\n const mayWrite =\n entity === undefined ||\n affordances.metadata === undefined ||\n affordances.metadata.actions.includes('write');\n\n return (\n <EntityForm<TEntity>\n entityConstructor={entityConstructor}\n entity={entity}\n // Driven by the served descriptor rather than fixed: `edit` for a caller\n // who may write, `read` for one who may not. Passing it at all is what\n // suppresses the built-in Ver/Editar toggle, which would otherwise offer\n // a way back into inputs the service will refuse.\n mode={mayWrite ? 'edit' : 'read'}\n values={form.values}\n onFieldChange={form.setField}\n linkSources={linkSources}\n onLinkChange={form.setLink}\n errors={form.errors}\n formError={form.formError}\n onSubmit={form.submit}\n onDelete={onDelete}\n {...affordances}\n onUseCase={onUseCase}\n isLoading={isLoading}\n isSaving={isSaving}\n isDeleting={isDeleting}\n error={error}\n backHref={backHref}\n renderLink={renderLink}\n // `entity` is undefined until the record lands, so testing it alone\n // titled a loading edit form \"New\" and then relabelled it.\n title={et(\n entity || isLoading\n ? `${catalogKey}.form.editTitle`\n : `${catalogKey}.form.newTitle`,\n )}\n >\n {hiddenFields.map(field => (\n <EntityField<TEntity> key={field} field={field} hidden />\n ))}\n </EntityForm>\n );\n}\n"],"names":["reconstructEntity","EntityField","EntityForm","useT","useTranslateKey","useEntityForm","useEffect","useMemo","useEntityAffordances","useEntityLinkSources","validationMessagesFor","EntityCrudForm","entityConstructor","catalogKey","hiddenFields","links","entity","isLoading","isSaving","isDeleting","error","onSave","onDelete","backHref","renderLink","draft","metadataSource","onUseCase","et","ct","validationMessages","translateKey","form","onSubmit","values","existing","linkSources","selection","hydrateLink","field","source","Object","entries","resolved","selected","undefined","affordances","mayWrite","metadata","actions","includes","mode","onFieldChange","setField","onLinkChange","setLink","errors","formError","submit","title","map","hidden"],"mappings":"AAAA;;;AAEA,SAIEA,iBAAiB,QAEZ,gBAAgB;AACvB,SACEC,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KAAK,MAAM,CAACiC,OAAOC,OAAO,IAAIC,OAAOC,OAAO,CAACN,aAAc;YACzD,MAAMO,WAAWH,OAAOI,QAAQ,CAAC5B,MAAM;YACvC,IAAI2B,aAAaE,aAAaR,SAAS,CAACE,MAAM,KAAKM,WAAW;gBAC5DP,YAAYC,OAAOI;YACrB;QACF;IACF,GAAG;QAACP;QAAaC;QAAWC;KAAY;IAExC,MAAMQ,cAActC,qBAAqBI,mBAAmBc;IAE5D;;;;;;;;;;;;;;;;;GAiBC,GACD,MAAMqB,WACJ/B,WAAW6B,aACXC,YAAYE,QAAQ,KAAKH,aACzBC,YAAYE,QAAQ,CAACC,OAAO,CAACC,QAAQ,CAAC;IAExC,qBACE,KAAChD;QACCU,mBAAmBA;QACnBI,QAAQA;QACR,yEAAyE;QACzE,uEAAuE;QACvE,yEAAyE;QACzE,kDAAkD;QAClDmC,MAAMJ,WAAW,SAAS;QAC1Bb,QAAQF,KAAKE,MAAM;QACnBkB,eAAepB,KAAKqB,QAAQ;QAC5BjB,aAAaA;QACbkB,cAActB,KAAKuB,OAAO;QAC1BC,QAAQxB,KAAKwB,MAAM;QACnBC,WAAWzB,KAAKyB,SAAS;QACzBxB,UAAUD,KAAK0B,MAAM;QACrBpC,UAAUA;OACNwB;QACJnB,WAAWA;QACXV,WAAWA;QACXC,UAAUA;QACVC,YAAYA;QACZC,OAAOA;QACPG,UAAUA;QACVC,YAAYA;QACZ,oEAAoE;QACpE,2DAA2D;QAC3DmC,OAAO/B,GACLZ,UAAUC,YACN,GAAGJ,WAAW,eAAe,CAAC,GAC9B,GAAGA,WAAW,cAAc,CAAC;kBAGlCC,aAAa8C,GAAG,CAACrB,CAAAA,sBAChB,KAACtC;gBAAiCsC,OAAOA;gBAAOsB,MAAM;eAA3BtB;;AAInC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/crud/entity-crud-form.tsx"],"sourcesContent":["'use client';\n\nimport {\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityMetadataSource,\n reconstructEntity,\n} from '@entifix/core';\nimport {\n EntityField,\n EntityForm,\n type RenderLink,\n useT,\n useTranslateKey,\n} from '@entifix/react-controls';\nimport {\n type EntityDraftStore,\n useEntityForm,\n} from '@entifix/react-integration';\nimport { useEffect, useMemo } from 'react';\n\nimport type {\n EntityCatalogKey,\n EntityCrudLinkSource,\n} from './make-entity-crud.types.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityLinkSources } from './use-entity-link-sources.js';\nimport { validationMessagesFor } from './validation-messages.js';\n\nexport interface EntityCrudFormProps<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n readonly catalogKey: EntityCatalogKey;\n readonly hiddenFields: readonly string[];\n readonly links: readonly EntityCrudLinkSource[];\n /** The record being edited; `undefined` means this is a create. */\n readonly entity?: TEntity;\n readonly isLoading?: boolean;\n readonly isSaving?: boolean;\n /** A write handed to a flow that has not settled: the form waits, keeping its input. */\n readonly isPending?: boolean;\n readonly isDeleting?: boolean;\n readonly error?: EntifixFailure;\n readonly onSave: (entity: TEntity) => void;\n /** Omitted for a create — there is nothing to delete yet. */\n readonly onDelete?: () => void;\n readonly backHref: string;\n /** Renders the Back link; see `useCrudRenderLink`. */\n readonly renderLink?: RenderLink;\n /**\n * Where to autosave this form's draft. Omitted by a route host, which is what\n * keeps a plain route ephemeral; the workspace tab host supplies one.\n */\n readonly draft?: EntityDraftStore;\n /**\n * Where this caller's affordances come from. Absent keeps the pre-ADR-0026\n * behaviour: Save and Delete render unconditionally and no declared verb\n * appears — which is what every generated catalog did before it existed.\n */\n readonly metadataSource?: EntityMetadataSource;\n /** Runs a declared `entity`-bound verb on this record, by its key. */\n readonly onUseCase?: (key: string) => void;\n}\n\n/**\n * The generated create/update form. A thin wrapper over the agnostic\n * {@link EntityForm}: every field, label and validation rule comes from the\n * entity's own accessor metadata, and `reconstructEntity` derives the submit\n * rebuild from that same metadata — so nothing here is per-entity but the\n * constructor, the catalog key and the hidden-field list.\n *\n * A hidden member still round-trips. `code` is assigned by the create\n * transaction and never shown, but it is a plain writable member, so the rebuild\n * picks it out of the seeded draft; dropping it from the rendered fields is not\n * dropping it from the draft.\n *\n * `useEntityForm` owns the draft and seeds it once, so the page keys this\n * component by the record id to reseed when the record arrives.\n */\nexport function EntityCrudForm<TEntity extends Entity>({\n entityConstructor,\n catalogKey,\n hiddenFields,\n links,\n entity,\n isLoading = false,\n isSaving = false,\n isPending = false,\n isDeleting = false,\n error,\n onSave,\n onDelete,\n backHref,\n renderLink,\n draft,\n metadataSource,\n onUseCase,\n}: EntityCrudFormProps<TEntity>) {\n const et = useT('entity');\n const ct = useT('controls');\n\n // `controls` copy, resolved here and handed down; see validationMessagesFor.\n const validationMessages = useMemo(() => validationMessagesFor(ct), [ct]);\n\n // A runtime-key translator, so a message names the field by its catalog word\n // (`labelKey`) and a schema's keyed message resolves at all. Without it both\n // fell back to untranslated text inside an otherwise Spanish sentence.\n const translateKey = useTranslateKey();\n\n const form = useEntityForm<TEntity>({\n entityConstructor,\n entity,\n validationMessages,\n translateKey,\n draft,\n onSubmit: values =>\n onSave(\n reconstructEntity(entityConstructor, values, { existing: entity }),\n ),\n });\n\n const linkSources = useEntityLinkSources(links, {\n values: form.values,\n selection: form.links,\n });\n\n // Refill the relation sidecar from the ids the draft did keep.\n //\n // A draft is JSON, so it holds ids and nothing else; the instances behind them\n // die with the page. Each picker already resolves its id — that is how a\n // restored draft shows a brand's name instead of its key — so the instance is\n // in hand and only has to be handed back. Without this, a member declared\n // `linkSerialization: 'embedded'` reaches `applyEntityLinks` with an id and no\n // target, which it refuses rather than writing the wrong wire shape.\n //\n // `hydrateLink`, not `setLink`: this is a lookup landing, not a pick, so it\n // must leave the draft — and the form's dirty flag — alone.\n const { links: selection, hydrateLink } = form;\n useEffect(() => {\n for (const [field, source] of Object.entries(linkSources)) {\n const resolved = source.selected.entity;\n if (resolved !== undefined && selection[field] === undefined) {\n hydrateLink(field, resolved);\n }\n }\n }, [linkSources, selection, hydrateLink]);\n\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n\n /**\n * May this caller write the record in front of them?\n *\n * The **same authority that withholds Save**, applied one step earlier.\n * Absent metadata keeps the pre-ADR-0026 behaviour, so an un-migrated call\n * site is untouched; present metadata is authoritative, because it is what\n * the service already decided.\n *\n * ⚠️ Without this the form rendered inputs nobody could submit. Measured on\n * the stock surface: `stock-item` answers `[\"read\"]` — no role holds\n * `stock-item:write` and there is no save route — so Save was correctly\n * absent while `onHand` and `reserved` still rendered as **enabled number\n * inputs**. A vendor could type a new quantity into a field that is only ever\n * moved by a ledger, and nothing would happen and nothing would say why.\n *\n * A create is exempt: there is no record yet, so there is nothing to read and\n * a `read` mode would render an empty form with no way to fill it.\n */\n const mayWrite =\n entity === undefined ||\n affordances.metadata === undefined ||\n affordances.metadata.actions.includes('write');\n\n return (\n <EntityForm<TEntity>\n entityConstructor={entityConstructor}\n entity={entity}\n // Driven by the served descriptor rather than fixed: `edit` for a caller\n // who may write, `read` for one who may not. Passing it at all is what\n // suppresses the built-in Ver/Editar toggle, which would otherwise offer\n // a way back into inputs the service will refuse.\n mode={mayWrite ? 'edit' : 'read'}\n values={form.values}\n onFieldChange={form.setField}\n linkSources={linkSources}\n onLinkChange={form.setLink}\n errors={form.errors}\n formError={form.formError}\n onSubmit={form.submit}\n onDelete={onDelete}\n {...affordances}\n onUseCase={onUseCase}\n isLoading={isLoading}\n isSaving={isSaving}\n isPending={isPending}\n isDeleting={isDeleting}\n error={error}\n backHref={backHref}\n renderLink={renderLink}\n // `entity` is undefined until the record lands, so testing it alone\n // titled a loading edit form \"New\" and then relabelled it.\n title={et(\n entity || isLoading\n ? `${catalogKey}.form.editTitle`\n : `${catalogKey}.form.newTitle`,\n )}\n >\n {hiddenFields.map(field => (\n <EntityField<TEntity> key={field} field={field} hidden />\n ))}\n </EntityForm>\n );\n}\n"],"names":["reconstructEntity","EntityField","EntityForm","useT","useTranslateKey","useEntityForm","useEffect","useMemo","useEntityAffordances","useEntityLinkSources","validationMessagesFor","EntityCrudForm","entityConstructor","catalogKey","hiddenFields","links","entity","isLoading","isSaving","isPending","isDeleting","error","onSave","onDelete","backHref","renderLink","draft","metadataSource","onUseCase","et","ct","validationMessages","translateKey","form","onSubmit","values","existing","linkSources","selection","hydrateLink","field","source","Object","entries","resolved","selected","undefined","affordances","mayWrite","metadata","actions","includes","mode","onFieldChange","setField","onLinkChange","setLink","errors","formError","submit","title","map","hidden"],"mappings":"AAAA;;;AAEA,SAKEA,iBAAiB,QACZ,gBAAgB;AACvB,SACEC,WAAW,EACXC,UAAU,EAEVC,IAAI,EACJC,eAAe,QACV,0BAA0B;AACjC,SAEEC,aAAa,QACR,6BAA6B;AACpC,SAASC,SAAS,EAAEC,OAAO,QAAQ,QAAQ;AAM3C,SAASC,oBAAoB,QAAQ,8BAA8B;AACnE,SAASC,oBAAoB,QAAQ,+BAA+B;AACpE,SAASC,qBAAqB,QAAQ,2BAA2B;AAoCjE;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,eAAuC,EACrDC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,KAAK,EACLC,MAAM,EACNC,YAAY,KAAK,EACjBC,WAAW,KAAK,EAChBC,YAAY,KAAK,EACjBC,aAAa,KAAK,EAClBC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,QAAQ,EACRC,UAAU,EACVC,KAAK,EACLC,cAAc,EACdC,SAAS,EACoB;IAC7B,MAAMC,KAAK1B,KAAK;IAChB,MAAM2B,KAAK3B,KAAK;IAEhB,6EAA6E;IAC7E,MAAM4B,qBAAqBxB,QAAQ,IAAMG,sBAAsBoB,KAAK;QAACA;KAAG;IAExE,6EAA6E;IAC7E,6EAA6E;IAC7E,uEAAuE;IACvE,MAAME,eAAe5B;IAErB,MAAM6B,OAAO5B,cAAuB;QAClCO;QACAI;QACAe;QACAC;QACAN;QACAQ,UAAUC,CAAAA,SACRb,OACEtB,kBAAkBY,mBAAmBuB,QAAQ;gBAAE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OA;QACPG,UAAUA;QACVC,YAAYA;QACZ,oEAAoE;QACpE,2DAA2D;QAC3DmC,OAAO/B,GACLb,UAAUC,YACN,GAAGJ,WAAW,eAAe,CAAC,GAC9B,GAAGA,WAAW,cAAc,CAAC;kBAGlCC,aAAa+C,GAAG,CAACrB,CAAAA,sBAChB,KAACvC;gBAAiCuC,OAAOA;gBAAOsB,MAAM;eAA3BtB;;AAInC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make-entity-crud.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/make-entity-crud.tsx"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"make-entity-crud.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/make-entity-crud.tsx"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,mBAAmB,EAKzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,KAAK,MAAM,EACX,KAAK,iBAAiB,EAavB,MAAM,eAAe,CAAC;AASvB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAS,OAAO,EAAgB,MAAM,QAAQ,CAAC;AAatD,OAAO,KAAK,EAEV,UAAU,EAEV,iBAAiB,EAElB,MAAM,6BAA6B,CAAC;AAUrC;;;;;;;GAOG;AACH,MAAM,MAAM,WAAW,GAAG,mBAAmB,GAAG,kBAAkB,CAAC;AAEnE;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EACxC,QAAQ,EAAE,SAAS,EACnB,UAAU,EAAE,MAAM,SAAS,EAC3B,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAM9B;AAsID,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,SAAS,EAC9D,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAC7C,OAAO,EAAE,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,GAC7C,UAAU,CAAC,OAAO,CAAC,CA2arB"}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
3
3
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
4
|
-
import { deleteUCFactory, getUCFactory, loadUCFactory, saveUCFactory } from '@entifix/business';
|
|
5
|
-
import { describeEntityColumns, envelopeEntityName, extractMetaEntity, Internal } from '@entifix/core';
|
|
4
|
+
import { deleteUCFactory, EntityIdTag, EntityTag, getUCFactory, loadUCFactory, saveUCFactory } from '@entifix/business';
|
|
5
|
+
import { describeEntityColumns, envelopeEntityName, extractMetaEntity, Internal, isFailure, settled } from '@entifix/core';
|
|
6
6
|
import { EntityTable, useCasesForSurface } from '@entifix/react-controls';
|
|
7
|
-
import { entityQueryScope, useDataLoading,
|
|
7
|
+
import { entityQueryScope, useDataLoading, useEntityRecord, useOptimisticMutation } from '@entifix/react-integration';
|
|
8
8
|
import { TransactionSinkTag } from '@entifix/transactions';
|
|
9
9
|
import { useQueryClient } from '@tanstack/react-query';
|
|
10
10
|
import { Cause, Context, Effect, Exit } from 'effect';
|
|
11
11
|
import { useParams, useRouter } from 'next/navigation';
|
|
12
|
-
import {
|
|
12
|
+
import { useEffect, useRef } from 'react';
|
|
13
13
|
import { useLocaleHref } from '../i18n/index.js';
|
|
14
14
|
import { useEntityNavHost } from '../workspace/entity-nav.js';
|
|
15
15
|
import { pendingFor, pendingRecordsFor, usePendingTransactions } from '../workspace/pending-transactions.js';
|
|
@@ -51,32 +51,71 @@ import { useEntityBulk } from './use-entity-bulk.js';
|
|
|
51
51
|
* with the code, so making this spec-driven would trade type safety for nothing;
|
|
52
52
|
* a vendor-authored `EntitySpecification` renders through a separate path.
|
|
53
53
|
*/ /**
|
|
54
|
-
* A rejected
|
|
54
|
+
* A rejected write, as something the form's error slot can render.
|
|
55
55
|
*
|
|
56
56
|
* A typed failure is kept as it is: `useErrorMessage` translates its own code,
|
|
57
|
-
* a business refusal and an outage alike
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
* thrown value with no message at all is `Internal`.
|
|
57
|
+
* a business refusal and an outage alike. Anything else is a bug that reached
|
|
58
|
+
* the screen, and is shown as `Internal` — never with its own text, which
|
|
59
|
+
* nobody wrote for a user.
|
|
61
60
|
*/ function asFailure(failure) {
|
|
62
|
-
|
|
63
|
-
// one check keeps both it and a legacy error carrying its own message.
|
|
64
|
-
return failure instanceof Error ? failure : new Internal();
|
|
61
|
+
return isFailure(failure) ? failure : new Internal();
|
|
65
62
|
}
|
|
66
63
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
64
|
+
* What a write failed with *synchronously* — before any flow took it — or
|
|
65
|
+
* `undefined`. A flow's own failure is toasted by the `PendingFlowsProvider`
|
|
66
|
+
* that settles it, so showing it in the error slot too would tell the operator
|
|
67
|
+
* twice.
|
|
68
|
+
*/ function syncFailure(mutation) {
|
|
69
|
+
return mutation.status === 'failed' && mutation.flowId === undefined ? asFailure(mutation.failure) : undefined;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* A runner's verbs, looked up by the key the served `$metadata` named. A
|
|
73
|
+
* single verb answers either settle mode, so it is run through the optimistic
|
|
74
|
+
* API; a bulk run reports per row and is awaited as a promise whose rejection
|
|
75
|
+
* carries the failure itself.
|
|
70
76
|
*/ function verbsOf(runner, served) {
|
|
71
77
|
if (runner === undefined) return undefined;
|
|
72
|
-
const settle = (effect)=>Effect.runPromiseExit(effect).then((exit)=>Exit.isSuccess(exit) ? exit.value : Promise.reject(Cause.squash(exit.cause)));
|
|
73
78
|
// The key always comes from the served document, so it names a verb in it.
|
|
74
79
|
const descriptor = (key)=>served == null ? void 0 : served.find((candidate)=>candidate.key === key);
|
|
75
80
|
return {
|
|
76
|
-
run: (key, id)=>
|
|
77
|
-
bulk: (key, selection)=>
|
|
81
|
+
run: (key, id)=>runner.run(descriptor(key), id),
|
|
82
|
+
bulk: (key, selection)=>Effect.runPromiseExit(runner.bulk(descriptor(key), selection)).then((exit)=>Exit.isSuccess(exit) ? exit.value : Promise.reject(Cause.squash(exit.cause)))
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* One verb on one record, through the optimistic API: `done` runs once the
|
|
87
|
+
* verb took effect — at once when it settled, or when the flow it was handed
|
|
88
|
+
* to completed.
|
|
89
|
+
*/ function useVerb(verbs, done) {
|
|
90
|
+
const verb = useOptimisticMutation({
|
|
91
|
+
// Only ever sent from a handler that exists because `verbs` does.
|
|
92
|
+
write: ({ key, id })=>verbs.run(key, id),
|
|
93
|
+
confirm: done
|
|
94
|
+
});
|
|
95
|
+
const run = (key, id)=>{
|
|
96
|
+
void verb.mutate({
|
|
97
|
+
key,
|
|
98
|
+
id
|
|
99
|
+
}).then((result)=>{
|
|
100
|
+
if (result._tag === 'settled') done();
|
|
101
|
+
}, // Shown through `syncFailure`, from the mutation's own state.
|
|
102
|
+
()=>undefined);
|
|
103
|
+
};
|
|
104
|
+
return {
|
|
105
|
+
verb,
|
|
106
|
+
run
|
|
78
107
|
};
|
|
79
108
|
}
|
|
109
|
+
/** Whether the component is still mounted: a flow can settle after it left. */ function useMounted() {
|
|
110
|
+
const mounted = useRef(true);
|
|
111
|
+
useEffect(()=>{
|
|
112
|
+
mounted.current = true;
|
|
113
|
+
return ()=>{
|
|
114
|
+
mounted.current = false;
|
|
115
|
+
};
|
|
116
|
+
}, []);
|
|
117
|
+
return mounted;
|
|
118
|
+
}
|
|
80
119
|
/**
|
|
81
120
|
* Runs each link's `useBaseFiltering` against the record being edited, in link
|
|
82
121
|
* order, with `undefined` for a link that declares none.
|
|
@@ -89,7 +128,7 @@ import { useEntityBulk } from './use-entity-bulk.js';
|
|
|
89
128
|
return links.map((link)=>link.useBaseFiltering == null ? void 0 : link.useBaseFiltering.call(link, record));
|
|
90
129
|
}
|
|
91
130
|
export function makeEntityCrud(entityConstructor, options) {
|
|
92
|
-
const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, pageSize, links = [], metadataSource: givenMetadataSource, metadata, useCases } = options;
|
|
131
|
+
const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, pageSize, links = [], metadataSource: givenMetadataSource, metadata, useCases, write } = options;
|
|
93
132
|
if (givenMetadataSource !== undefined && metadata !== undefined) {
|
|
94
133
|
throw new Error(`${entityConstructor.name} was given both metadataSource and metadata; pass one`);
|
|
95
134
|
}
|
|
@@ -133,6 +172,7 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
133
172
|
});
|
|
134
173
|
});
|
|
135
174
|
function ListPage() {
|
|
175
|
+
var _syncFailure;
|
|
136
176
|
var _affordances_metadata, _affordances_metadata1, _affordances_metadata2;
|
|
137
177
|
const adapters = useAdapters();
|
|
138
178
|
// Outside a `PendingTransactionsProvider` this watches nothing, so a host
|
|
@@ -194,10 +234,14 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
194
234
|
//
|
|
195
235
|
// ⚠️ **A row verb and the form's are the same runner with different
|
|
196
236
|
// arguments.** `EntityTable` hands back the whole record, because that is
|
|
197
|
-
// what it has; the runner takes an id, because that is what a route needs
|
|
237
|
+
// what it has; the runner takes an id, because that is what a route needs.
|
|
198
238
|
// The list has no error slot of its own, so a failure lands in the
|
|
199
239
|
// table's own error region — the same one a failed page read uses.
|
|
200
|
-
const
|
|
240
|
+
const rowVerb = useVerb(verbs, ()=>{
|
|
241
|
+
void queryClient.invalidateQueries({
|
|
242
|
+
queryKey: scope
|
|
243
|
+
});
|
|
244
|
+
});
|
|
201
245
|
// Called unconditionally and the *result* gated, the way the surfaces are
|
|
202
246
|
// read in `EntityForm`: the name begins with `use`, so short-circuiting it
|
|
203
247
|
// reads to `react-hooks/rules-of-hooks` as a conditional hook.
|
|
@@ -205,10 +249,7 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
205
249
|
const canRunRowUseCase = verbs !== undefined && rowUseCases.length > 0;
|
|
206
250
|
const handleRowUseCase = canRunRowUseCase ? (key, item)=>{
|
|
207
251
|
if (item.id == null) return;
|
|
208
|
-
|
|
209
|
-
void (verbs == null ? void 0 : verbs.run(key, item.id).then(()=>queryClient.invalidateQueries({
|
|
210
|
-
queryKey: scope
|
|
211
|
-
}), (failure)=>setUseCaseError(asFailure(failure))));
|
|
252
|
+
rowVerb.run(key, item.id);
|
|
212
253
|
} : undefined;
|
|
213
254
|
return /*#__PURE__*/ _jsxs("div", {
|
|
214
255
|
className: "flex flex-col gap-s",
|
|
@@ -230,7 +271,7 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
230
271
|
renderLink: renderLink
|
|
231
272
|
}, affordances, bulk.tableProps, {
|
|
232
273
|
onUseCase: handleRowUseCase,
|
|
233
|
-
error:
|
|
274
|
+
error: (_syncFailure = syncFailure(rowVerb.verb)) != null ? _syncFailure : pager.error,
|
|
234
275
|
children: [
|
|
235
276
|
columns,
|
|
236
277
|
toolbar
|
|
@@ -244,7 +285,7 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
244
285
|
* on save; in a workspace tab it takes the slug and the post-save action as
|
|
245
286
|
* props.
|
|
246
287
|
*/ function SingleViewPage({ slug, onSaved, onDeleted, draft } = {}) {
|
|
247
|
-
var _ref, _ref1;
|
|
288
|
+
var _ref, _ref1, _ref2;
|
|
248
289
|
var _affordances_metadata;
|
|
249
290
|
const adapters = useAdapters();
|
|
250
291
|
const metadataSource = metadataSourceOf(adapters);
|
|
@@ -255,9 +296,7 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
255
296
|
const router = useRouter();
|
|
256
297
|
const withLocale = useLocaleHref();
|
|
257
298
|
const params = useParams();
|
|
258
|
-
|
|
259
|
-
// so it needs a slot of its own to reach the form's error area.
|
|
260
|
-
const [useCaseError, setUseCaseError] = useState(undefined);
|
|
299
|
+
const mounted = useMounted();
|
|
261
300
|
const id = slugToEntityId(slug != null ? slug : params.slug);
|
|
262
301
|
const ctx = mergeCrudContext(adapters, repository, pending);
|
|
263
302
|
const { entity, isLoading, error: loadError, reload } = useEntityRecord({
|
|
@@ -265,11 +304,6 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
265
304
|
ctx,
|
|
266
305
|
id
|
|
267
306
|
});
|
|
268
|
-
const { save, remove, isSaving, isDeleting, error: writeError } = useEntityMutation({
|
|
269
|
-
saveUc: saveUCFactory(),
|
|
270
|
-
deleteUc: deleteUCFactory(),
|
|
271
|
-
ctx
|
|
272
|
-
});
|
|
273
307
|
// Against the record as loaded, not the draft: the rule is about which
|
|
274
308
|
// record this is, not what the operator has typed into it.
|
|
275
309
|
const linkFilters = useLinkFilters(linkPlans, entity);
|
|
@@ -308,13 +342,46 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
308
342
|
const toList = ()=>host === undefined ? router.push(withLocale(basePath)) : host.toList(catalogKey);
|
|
309
343
|
const afterSave = onSaved != null ? onSaved : toList;
|
|
310
344
|
const afterDelete = onDeleted != null ? onDeleted : toList;
|
|
345
|
+
// Through the host's writer when it named one, which answers both settle
|
|
346
|
+
// modes; otherwise through the repository, where every write settles.
|
|
347
|
+
const writer = write === undefined ? undefined : adapters[write];
|
|
311
348
|
// The draft is spent once the write *commits*, and only here is that known:
|
|
312
349
|
// `useEntityForm` neither fetches nor saves, so it cannot clear its own.
|
|
313
|
-
// A failed
|
|
314
|
-
// user's only copy of what they typed.
|
|
350
|
+
// A failed write — or a failed flow — deliberately keeps the draft and the
|
|
351
|
+
// form: the edit is still the user's only copy of what they typed.
|
|
352
|
+
//
|
|
353
|
+
// ⚠️ A flow can complete after the operator left this page, so leaving it
|
|
354
|
+
// is guarded on still being here: a navigation from a form nobody is
|
|
355
|
+
// looking at would pull them away from wherever they went.
|
|
356
|
+
const saveMutation = useOptimisticMutation({
|
|
357
|
+
write: (next)=>writer === undefined ? Effect.map(Effect.provide(saveUCFactory(), ctx.pipe(Context.add(EntityTag, next))), settled) : writer.save(next),
|
|
358
|
+
intent: ()=>({
|
|
359
|
+
entity: entityName,
|
|
360
|
+
write: 'save'
|
|
361
|
+
}),
|
|
362
|
+
confirm: ()=>{
|
|
363
|
+
draft == null ? void 0 : draft.clear();
|
|
364
|
+
void refreshList();
|
|
365
|
+
if (mounted.current) afterSave();
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
const deleteMutation = useOptimisticMutation({
|
|
369
|
+
write: (target)=>writer === undefined ? Effect.as(Effect.provide(deleteUCFactory(), ctx.pipe(Context.add(EntityIdTag, target))), settled(undefined)) : writer.delete(target),
|
|
370
|
+
intent: ()=>({
|
|
371
|
+
entity: entityName,
|
|
372
|
+
write: 'delete'
|
|
373
|
+
}),
|
|
374
|
+
confirm: ()=>{
|
|
375
|
+
draft == null ? void 0 : draft.clear();
|
|
376
|
+
void refreshList();
|
|
377
|
+
if (mounted.current) afterDelete();
|
|
378
|
+
}
|
|
379
|
+
});
|
|
315
380
|
const handleSave = async (next)=>{
|
|
316
|
-
const
|
|
317
|
-
|
|
381
|
+
const result = await saveMutation.mutate(next).catch(()=>undefined);
|
|
382
|
+
// Failed, or pending: the form stays, and the mutation says which.
|
|
383
|
+
if ((result == null ? void 0 : result._tag) !== 'settled') return;
|
|
384
|
+
const saved = result.value;
|
|
318
385
|
// ⚠️ Deliberately *not* a `setQueriesData` patch. The list refetches on
|
|
319
386
|
// mount — precisely when the operator arrives, having just been navigated
|
|
320
387
|
// here — and the server legitimately does not hold the record yet, so the
|
|
@@ -330,16 +397,17 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
330
397
|
afterSave();
|
|
331
398
|
};
|
|
332
399
|
const handleDelete = async ()=>{
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
400
|
+
const result = await deleteMutation.mutate(id).catch(()=>undefined);
|
|
401
|
+
if ((result == null ? void 0 : result._tag) !== 'settled') return;
|
|
402
|
+
draft == null ? void 0 : draft.clear();
|
|
403
|
+
void refreshList();
|
|
404
|
+
afterDelete();
|
|
338
405
|
};
|
|
339
406
|
/**
|
|
340
407
|
* An `entity`-bound verb, on the record being shown.
|
|
341
408
|
*
|
|
342
|
-
* It **reloads**
|
|
409
|
+
* It **reloads** — once the verb took effect, which for one the server
|
|
410
|
+
* handed to a flow is when the flow completed — rather than patching what it has: the service decides the
|
|
343
411
|
* resulting state — a `publish` may land on `published` from four different
|
|
344
412
|
* places — and a client that assumed the new value would show the wrong one
|
|
345
413
|
* the first time the rule changed. `id == null` means the create form,
|
|
@@ -352,10 +420,8 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
352
420
|
* the record correctly did not move, and the operator saw a button that
|
|
353
421
|
* appeared to do nothing at all.
|
|
354
422
|
*/ const verbs = verbsOf(useCases === undefined ? undefined : adapters[useCases], (_affordances_metadata = affordances.metadata) == null ? void 0 : _affordances_metadata.useCases);
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
void verbs.run(key, id).then(()=>reload(), (failure)=>setUseCaseError(asFailure(failure)));
|
|
358
|
-
};
|
|
423
|
+
const recordVerb = useVerb(verbs, ()=>void reload());
|
|
424
|
+
const handleUseCase = verbs === undefined || id == null ? undefined : (key)=>recordVerb.run(key, id);
|
|
359
425
|
return /*#__PURE__*/ _jsx(EntityCrudForm, {
|
|
360
426
|
entityConstructor: entityConstructor,
|
|
361
427
|
catalogKey: catalogKey,
|
|
@@ -364,16 +430,21 @@ export function makeEntityCrud(entityConstructor, options) {
|
|
|
364
430
|
links: linkSources,
|
|
365
431
|
entity: entity,
|
|
366
432
|
isLoading: isLoading,
|
|
367
|
-
isSaving:
|
|
368
|
-
|
|
369
|
-
|
|
433
|
+
isSaving: saveMutation.status === 'running',
|
|
434
|
+
isPending: [
|
|
435
|
+
saveMutation,
|
|
436
|
+
deleteMutation,
|
|
437
|
+
recordVerb.verb
|
|
438
|
+
].some((mutation)=>mutation.status === 'pending'),
|
|
439
|
+
isDeleting: deleteMutation.status === 'running',
|
|
440
|
+
error: (_ref = (_ref1 = loadError != null ? loadError : syncFailure(saveMutation)) != null ? _ref1 : syncFailure(deleteMutation)) != null ? _ref : syncFailure(recordVerb.verb),
|
|
370
441
|
onSave: handleSave,
|
|
371
442
|
onDelete: id == null ? undefined : handleDelete,
|
|
372
443
|
onUseCase: handleUseCase,
|
|
373
444
|
backHref: withLocale(basePath),
|
|
374
445
|
renderLink: renderLink,
|
|
375
446
|
draft: draft
|
|
376
|
-
}, String((
|
|
447
|
+
}, String((_ref2 = entity == null ? void 0 : entity.id) != null ? _ref2 : CATALOG_NEW_SLUG));
|
|
377
448
|
}
|
|
378
449
|
return {
|
|
379
450
|
entityConstructor,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/crud/make-entity-crud.tsx"],"sourcesContent":["'use client';\n\nimport {\n deleteUCFactory,\n type EntityRepositoryTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n describeEntityColumns,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityMetadataSource,\n type EntitySelection,\n type EntityUseCaseRunner,\n envelopeEntityName,\n extractMetaEntity,\n type FilterGroup,\n Internal,\n type TransitionalFailure,\n type UseCaseDescriptor,\n} from '@entifix/core';\nimport { EntityTable, useCasesForSurface } from '@entifix/react-controls';\nimport {\n entityQueryScope,\n useDataLoading,\n useEntityMutation,\n useEntityRecord,\n} from '@entifix/react-integration';\nimport type { TransactionSink } from '@entifix/transactions';\nimport { TransactionSinkTag } from '@entifix/transactions';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { Cause, Context, Effect, Exit } from 'effect';\nimport { useParams, useRouter } from 'next/navigation';\nimport { useState } from 'react';\n\nimport { useLocaleHref } from '../i18n/index.js';\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport {\n pendingFor,\n pendingRecordsFor,\n usePendingTransactions,\n} from '../workspace/pending-transactions.js';\nimport { EntityCrudForm } from './entity-crud-form.js';\nimport { handOffWrite } from './hand-off-write.js';\nimport type {\n AnyFilterGroup,\n EntityCrud,\n EntityCrudLinkSource,\n EntityCrudOptions,\n EntityCrudSingleViewProps,\n} from './make-entity-crud.types.js';\nimport { PendingNotice } from './pending-notice.js';\nimport { CATALOG_NEW_SLUG, slugToEntityId } from './slug.js';\nimport { useCrudRenderLink } from './use-crud-render-link.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityBulk } from './use-entity-bulk.js';\n\n/** What a picker defaults to reading off its target. */\nconst TARGET_NAME_PROPERTY = 'name';\n\n/**\n * What the generated pages' use-cases run against.\n *\n * Exported because a hand-built screen needs the same three: a wizard reads\n * records, resolves pickers and writes through exactly these ports, and\n * rebuilding the union at each such call site is how one of them ends up\n * missing `TransactionSinkTag` and quietly losing its optimistic treatment.\n */\nexport type CrudContext = EntityRepositoryTag | TransactionSinkTag;\n\n/**\n * Adds the pending-write sink to one repository adapter, giving the context the\n * use-cases run against.\n *\n * The cast is the price of naming adapters by key: `AdapterKey` narrows which\n * names may be *offered*, but TypeScript will not carry that narrowing through\n * an index access on a generic record.\n */\nexport function mergeCrudContext<TAdapters>(\n adapters: TAdapters,\n repository: keyof TAdapters,\n sink: TransactionSink,\n): Context.Context<CrudContext> {\n return Context.add(\n adapters[repository] as Context.Context<EntityRepositoryTag>,\n TransactionSinkTag,\n sink,\n );\n}\n\n/**\n * Builds the list page and the single-record page for one entity.\n *\n * Every catalog entity used to cost ~10 files and ~300 lines whose only variable\n * was a class name: two organisms with a `.types.ts` each, two client pages, two\n * route files. The route files stay (Next needs a module per path); everything\n * between them is derived from the entity's own metadata, so a new reference\n * entity is this call plus a nav entry.\n *\n * Two things are checked here rather than at the call site, because both fail\n * silently otherwise. The catalog key must be the entity's own `@entity({ key })`\n * — they are the same string by convention, and a drifted one titles the form\n * after a different entity in a way only a reader of both catalogs would catch.\n * And a `links` entry must name a real member — a picker aimed at nothing renders\n * identically to a read-only field.\n *\n * **Serves compile-time `@entity()` classes only.** Operator reference data ships\n * with the code, so making this spec-driven would trade type safety for nothing;\n * a vendor-authored `EntitySpecification` renders through a separate path.\n */\n/**\n * A rejected verb, as something the form's error slot can render.\n *\n * A typed failure is kept as it is: `useErrorMessage` translates its own code,\n * a business refusal and an outage alike, and the failure toast that tells\n * them apart arrives with the optimistic API. Anything else that carries a\n * message keeps it rather than being relabelled with a code it never had; a\n * thrown value with no message at all is `Internal`.\n */\nfunction asFailure(failure: unknown): TransitionalFailure {\n // A typed failure is an `Error` too — Effect's tagged errors extend it — so\n // one check keeps both it and a legacy error carrying its own message.\n return failure instanceof Error\n ? (failure as TransitionalFailure)\n : new Internal();\n}\n\n/**\n * A runner's verbs as the promises the screens await, looked up by the key the\n * served `$metadata` named. A rejection carries the failure itself, so the\n * screen shows its coded message.\n */\nfunction verbsOf(\n runner: EntityUseCaseRunner | undefined,\n served: readonly UseCaseDescriptor[] | undefined,\n) {\n if (runner === undefined) return undefined;\n const settle = <A,>(effect: Effect.Effect<A, unknown>): Promise<A> =>\n Effect.runPromiseExit(effect).then(exit =>\n Exit.isSuccess(exit)\n ? exit.value\n : Promise.reject(Cause.squash(exit.cause)),\n );\n // The key always comes from the served document, so it names a verb in it.\n const descriptor = (key: string) =>\n served?.find(candidate => candidate.key === key) as UseCaseDescriptor;\n return {\n run: (key: string, id: EntityId) => settle(runner.run(descriptor(key), id)),\n bulk: (key: string, selection: EntitySelection<Entity>) =>\n settle(runner.bulk(descriptor(key), selection)),\n };\n}\n\n/**\n * Runs each link's `useBaseFiltering` against the record being edited, in link\n * order, with `undefined` for a link that declares none.\n *\n * Legal for the reason `useEntityLinkSources` gives: the links are a\n * factory-time array, and whether a link carries a rule is fixed with it, so\n * the same hooks run in the same order on every render. The lint rule cannot\n * see a hook called through a member, so there is nothing for it to flag.\n */\nfunction useLinkFilters<TEntity extends Entity>(\n links: readonly {\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n }[],\n record: TEntity | undefined,\n): (AnyFilterGroup | undefined)[] {\n return links.map(link => link.useBaseFiltering?.(record));\n}\n\nexport function makeEntityCrud<TEntity extends Entity, TAdapters>(\n entityConstructor: EntityConstructor<TEntity>,\n options: EntityCrudOptions<TAdapters, TEntity>,\n): EntityCrud<TEntity> {\n const {\n useAdapters,\n basePath,\n catalogKey,\n repository,\n hiddenFields = [],\n columns,\n toolbar,\n pageSize,\n links = [],\n metadataSource: givenMetadataSource,\n metadata,\n useCases,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new Error(\n `${entityConstructor.name} was given both metadataSource and metadata; pass one`,\n );\n }\n // An adapter value, so it is resolved per render from the same `useAdapters()`\n // the records come from — the host's composition, never the caller's module.\n const metadataSourceOf = (adapters: TAdapters) =>\n metadata === undefined\n ? givenMetadataSource\n : (adapters[metadata] as EntityMetadataSource);\n\n const meta = extractMetaEntity(entityConstructor);\n if (meta.key !== catalogKey) {\n throw new Error(\n `${entityConstructor.name} declares key \"${String(meta.key)}\" but was given catalog key \"${catalogKey}\"`,\n );\n }\n // Read off `@entity()` rather than rebuilt from `catalogKey`. Both spellings\n // produce the same string today, and that is exactly the problem: a second\n // place that knows how an entity's catalog subtree is laid out is a second\n // place to fix when one moves. `MetaEntityOptions` makes them optional, so an\n // entity that never declared them fails here — where a screen is generated —\n // rather than on the render that first tries to title a tab with `undefined`.\n const { labelKey: entityLabelKey, pluralKey: entityPluralKey } = meta;\n if (entityLabelKey === undefined || entityPluralKey === undefined) {\n throw new Error(\n `${entityConstructor.name} must declare labelKey and pluralKey on @entity() to be generated`,\n );\n }\n\n // Computed once: a descriptor is a property of the class, so nothing about it\n // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`\n // are overridden here because a scalar foreign key's `@accessor()` cannot name\n // the target's members — it may not import the target at all.\n // The wire name, which is also what a pending entry records and what\n // `entityQueryScopeFor` keys on — one derivation, so a notice and an\n // invalidation can never disagree about which entity they mean.\n const entityName = envelopeEntityName(entityConstructor);\n const descriptors = describeEntityColumns(entityConstructor);\n const linkPlans = links.map(link => {\n const descriptor = descriptors.find(entry => entry.name === link.field);\n if (descriptor === undefined) {\n throw new Error(\n `${entityConstructor.name} has no member \"${link.field}\" for a link source`,\n );\n }\n return {\n ...link,\n descriptor: {\n ...descriptor,\n linkLabelProperty: link.labelProperty ?? TARGET_NAME_PROPERTY,\n linkSearchProperty: link.searchProperty ?? TARGET_NAME_PROPERTY,\n },\n };\n });\n\n function ListPage() {\n const adapters = useAdapters();\n // Outside a `PendingTransactionsProvider` this watches nothing, so a host\n // that has not mounted one behaves exactly as it did before.\n const pending = usePendingTransactions();\n // Every internal href carries the locale. An unprefixed one still resolves —\n // the middleware redirects it — but the visitor pays a round trip per click.\n const withLocale = useLocaleHref();\n\n const queryClient = useQueryClient();\n const scope = entityQueryScope(entityConstructor);\n const metadataSource = metadataSourceOf(adapters);\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const renderLink = useCrudRenderLink(catalogKey);\n\n // Records this browser has created but the service has not finished\n // writing. Prepended below rather than patched into the cache, which a\n // refetch would undo.\n const optimistic = pendingRecordsFor<TEntity>(pending, entityName);\n\n const pager = useDataLoading<TEntity, CrudContext>({\n uc: loadUCFactory<TEntity>(),\n ctx: mergeCrudContext(adapters, repository, pending),\n // Scoped rather than left to the per-instance fallback, which is correct\n // but unshared: with the entity's own scope one invalidation refreshes\n // every page and filter of it, which is what a bulk run needs — and it is\n // the same prefix `useReactiveInvalidation`already targets, so a generated\n // list now also refreshes on a reactive change event.\n queryKey: scope,\n ...(pageSize === undefined ? {} : { initialPageSize: pageSize }),\n });\n\n // Only when this caller may actually run something over a selection.\n //\n // Measured live: an `admin` holds `catalog-reference:*:read` and no\n // `retire`, so the service filters the verb out of `$metadata` — but the\n // selection column still rendered, offering a set that no action could be\n // taken on. A checkbox that can lead nowhere is worse than no checkbox: it\n // reads as a permission the user does not have.\n //\n // Decided from the served document rather than from the runner, because\n // the runner is a property of the *shell* (it knows the route) and the\n // grant is a property of the *caller*. The column therefore appears when\n // the document lands, which is the asynchrony serving affordances accepts\n // for every action surface.\n const canRunBulk =\n useCasesForSurface('bulk-bar', affordances.metadata?.useCases).length > 0;\n\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n\n const bulk = useEntityBulk<TEntity>({\n run:\n canRunBulk && verbs !== undefined\n ? (key, selection) =>\n verbs.bulk(key, selection as EntitySelection<Entity>)\n : undefined,\n // A bulk write changed the rows underneath the listing, so the page is\n // re-read; the selection deliberately survives it (\"the selection\n // is still there afterwards\"), because the operator's next act is usually\n // to retry the failures or run a second verb on the same rows.\n onCompleted: () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n },\n });\n\n // What a row's overflow menu runs, and the one place the list reports a\n // verb that failed.\n //\n // ⚠️ **A row verb and the form's are the same runner with different\n // arguments.** `EntityTable` hands back the whole record, because that is\n // what it has; the runner takes an id, because that is what a route needs\n // The list has no error slot of its own, so a failure lands in the\n // table's own error region — the same one a failed page read uses.\n const [useCaseError, setUseCaseError] = useState<\n TransitionalFailure | undefined\n >(undefined);\n // Called unconditionally and the *result* gated, the way the surfaces are\n // read in `EntityForm`: the name begins with `use`, so short-circuiting it\n // reads to `react-hooks/rules-of-hooks` as a conditional hook.\n const rowUseCases = useCasesForSurface(\n 'row-menu',\n affordances.metadata?.useCases,\n );\n const canRunRowUseCase = verbs !== undefined && rowUseCases.length > 0;\n\n const handleRowUseCase = canRunRowUseCase\n ? (key: string, item: TEntity) => {\n if (item.id == null) return;\n setUseCaseError(undefined);\n void verbs?.run(key, item.id).then(\n () => queryClient.invalidateQueries({ queryKey: scope }),\n (failure: unknown) => setUseCaseError(asFailure(failure)),\n );\n }\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-s\">\n {/* Above the table, because this is where `afterSave()` leaves the\n operator after a create — and a create is the only transactional\n write there is, so this is the surface the pending state has. */}\n <PendingNotice\n entries={pendingFor(pending, entityName)}\n onDismiss={pending.dismiss}\n />\n <EntityTable\n entityConstructor={entityConstructor}\n {...pager}\n items={[...optimistic, ...pager.items]}\n totalItems={pager.totalItems + optimistic.length}\n hrefFor={id => withLocale(`${basePath}/${String(id)}`)}\n newHref={withLocale(`${basePath}/${CATALOG_NEW_SLUG}`)}\n renderLink={renderLink}\n {...affordances}\n {...bulk.tableProps}\n onUseCase={handleRowUseCase}\n error={useCaseError ?? pager.error}\n >\n {columns}\n {toolbar}\n </EntityTable>\n </div>\n );\n }\n\n /**\n * Dual-host: as a route it reads its slug from the URL and returns to the list\n * on save; in a workspace tab it takes the slug and the post-save action as\n * props.\n */\n function SingleViewPage({\n slug,\n onSaved,\n onDeleted,\n draft,\n }: EntityCrudSingleViewProps = {}) {\n const adapters = useAdapters();\n const metadataSource = metadataSourceOf(adapters);\n // The same served document the form reads its buttons from, so a key the\n // form hands back always names a verb in it.\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const pending = usePendingTransactions();\n const router = useRouter();\n const withLocale = useLocaleHref();\n const params = useParams<{ slug: string }>();\n // A verb's failure is this page's, not the record fetch's or the mutation's,\n // so it needs a slot of its own to reach the form's error area.\n const [useCaseError, setUseCaseError] = useState<\n TransitionalFailure | undefined\n >(undefined);\n const id = slugToEntityId(slug ?? params.slug);\n\n const ctx = mergeCrudContext(adapters, repository, pending);\n\n const {\n entity,\n isLoading,\n error: loadError,\n reload,\n } = useEntityRecord<TEntity, CrudContext>({\n uc: getUCFactory<TEntity>(),\n ctx,\n id,\n });\n\n const {\n save,\n remove,\n isSaving,\n isDeleting,\n error: writeError,\n } = useEntityMutation<TEntity, CrudContext>({\n saveUc: saveUCFactory<TEntity>(),\n deleteUc: deleteUCFactory<TEntity>(),\n ctx,\n });\n\n // Against the record as loaded, not the draft: the rule is about which\n // record this is, not what the operator has typed into it.\n const linkFilters = useLinkFilters(linkPlans, entity);\n\n // Rebuilt inline on every render on purpose: `useEntityLinkSource` holds\n // these in a ref and keeps them out of its query keys, precisely so a caller\n // does not have to memoise them.\n const linkSources: EntityCrudLinkSource[] = linkPlans.map(\n (plan, index) => ({\n field: plan.field,\n descriptor: plan.descriptor,\n config: {\n entityConstructor: plan.entityConstructor,\n loadUc: loadUCFactory(),\n getUc: getUCFactory(),\n ctx: mergeCrudContext(adapters, plan.repository, pending),\n // The config's target is erased to `Entity`, and the host's filter to\n // `any`; the two meet here, where neither type is the real target's.\n baseFiltering: linkFilters[index] as FilterGroup<Entity> | undefined,\n },\n }),\n );\n\n // Inside a workspace tab, \"back to the list\" is the list's tab, not a URL\n // that would leave the workspace. A host's own callbacks still win.\n const host = useEntityNavHost();\n const renderLink = useCrudRenderLink(catalogKey);\n const queryClient = useQueryClient();\n // The list this page returns to has its page cached, and it is no longer\n // true. Invalidated rather than patched, for the reason `handOffWrite`\n // gives: a transactional create is not in the service yet, and the pending\n // set, not the cache, is what keeps it visible until it is.\n //\n // ⚠️ Invisible while every Open was a document load, which threw the cache\n // away anyway (#20): the first client-side navigation back to the list\n // showed the record as it was before the save.\n const refreshList = () =>\n queryClient.invalidateQueries({\n queryKey: entityQueryScope(entityConstructor),\n });\n const toList = () =>\n host === undefined\n ? router.push(withLocale(basePath))\n : host.toList(catalogKey);\n const afterSave = onSaved ?? toList;\n const afterDelete = onDeleted ?? toList;\n\n // The draft is spent once the write *commits*, and only here is that known:\n // `useEntityForm` neither fetches nor saves, so it cannot clear its own.\n // A failed mutation deliberately keeps the draft — the edit is still the\n // user's only copy of what they typed.\n const handleSave = async (next: TEntity) => {\n const saved = await save(next);\n if (saved === undefined) return;\n\n // ⚠️ Deliberately *not* a `setQueriesData` patch. The list refetches on\n // mount — precisely when the operator arrives, having just been navigated\n // here — and the server legitimately does not hold the record yet, so the\n // refetch would replace the patched page and the row would vanish a\n // moment after appearing. The pending set outlives refetches.\n handOffWrite({ id: String(saved.id), record: saved, pending, draft });\n void refreshList();\n afterSave();\n };\n\n const handleDelete = async () => {\n if (await remove(id)) {\n draft?.clear();\n void refreshList();\n afterDelete();\n }\n };\n\n /**\n * An `entity`-bound verb, on the record being shown.\n *\n * It **reloads** rather than patching what it has: the service decides the\n * resulting state — a `publish` may land on `published` from four different\n * places — and a client that assumed the new value would show the wrong one\n * the first time the rule changed. `id == null` means the create form,\n * where there is no record to act on and the form renders no verbs anyway.\n *\n * ⚠️ The rejection is **caught and shown**, never left to the promise.\n * `EntityForm`'s `onUseCase` returns `void`, so an uncaught rejection here\n * reaches the console and nothing else — measured on an offering refusing\n * `unpublish` from `draft`: the service answered `409` with a coded body,\n * the record correctly did not move, and the operator saw a button that\n * appeared to do nothing at all.\n */\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n const handleUseCase =\n verbs === undefined || id == null\n ? undefined\n : (key: string) => {\n setUseCaseError(undefined);\n void verbs.run(key, id).then(\n () => reload(),\n (failure: unknown) => setUseCaseError(asFailure(failure)),\n );\n };\n\n return (\n <EntityCrudForm<TEntity>\n // Remounts (and reseeds the fields) once the record arrives.\n key={String(entity?.id ?? CATALOG_NEW_SLUG)}\n entityConstructor={entityConstructor}\n catalogKey={catalogKey}\n metadataSource={metadataSource}\n hiddenFields={hiddenFields}\n links={linkSources}\n entity={entity}\n isLoading={isLoading}\n isSaving={isSaving}\n isDeleting={isDeleting}\n error={loadError ?? writeError ?? useCaseError}\n onSave={handleSave}\n onDelete={id == null ? undefined : handleDelete}\n onUseCase={handleUseCase}\n backHref={withLocale(basePath)}\n renderLink={renderLink}\n draft={draft}\n />\n );\n }\n\n return {\n entityConstructor,\n entityKey: catalogKey,\n entityLabelKey,\n entityPluralKey,\n basePath,\n ListPage,\n SingleViewPage,\n };\n}\n"],"names":["deleteUCFactory","getUCFactory","loadUCFactory","saveUCFactory","describeEntityColumns","envelopeEntityName","extractMetaEntity","Internal","EntityTable","useCasesForSurface","entityQueryScope","useDataLoading","useEntityMutation","useEntityRecord","TransactionSinkTag","useQueryClient","Cause","Context","Effect","Exit","useParams","useRouter","useState","useLocaleHref","useEntityNavHost","pendingFor","pendingRecordsFor","usePendingTransactions","EntityCrudForm","handOffWrite","PendingNotice","CATALOG_NEW_SLUG","slugToEntityId","useCrudRenderLink","useEntityAffordances","useEntityBulk","TARGET_NAME_PROPERTY","mergeCrudContext","adapters","repository","sink","add","asFailure","failure","Error","verbsOf","runner","served","undefined","settle","effect","runPromiseExit","then","exit","isSuccess","value","Promise","reject","squash","cause","descriptor","key","find","candidate","run","id","bulk","selection","useLinkFilters","links","record","map","link","useBaseFiltering","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","pageSize","metadataSource","givenMetadataSource","metadata","useCases","name","metadataSourceOf","meta","String","labelKey","entityLabelKey","pluralKey","entityPluralKey","entityName","descriptors","linkPlans","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListPage","affordances","pending","withLocale","queryClient","scope","renderLink","optimistic","pager","uc","ctx","queryKey","initialPageSize","canRunBulk","length","verbs","onCompleted","invalidateQueries","useCaseError","setUseCaseError","rowUseCases","canRunRowUseCase","handleRowUseCase","item","div","className","entries","onDismiss","dismiss","items","totalItems","hrefFor","newHref","tableProps","onUseCase","error","SingleViewPage","slug","onSaved","onDeleted","draft","loadError","router","params","entity","isLoading","reload","save","remove","isSaving","isDeleting","writeError","saveUc","deleteUc","linkFilters","linkSources","plan","index","config","loadUc","getUc","baseFiltering","host","refreshList","toList","push","afterSave","afterDelete","handleSave","next","saved","handleDelete","clear","handleUseCase","onSave","onDelete","backHref","entityKey"],"mappings":"AAAA;;;AAEA,SACEA,eAAe,EAEfC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SACEC,qBAAqB,EAOrBC,kBAAkB,EAClBC,iBAAiB,EAEjBC,QAAQ,QAGH,gBAAgB;AACvB,SAASC,WAAW,EAAEC,kBAAkB,QAAQ,0BAA0B;AAC1E,SACEC,gBAAgB,EAChBC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C,mBAAmBA;YACnBI,YAAYA;YACZK,gBAAgBA;YAChBJ,cAAcA;YACdX,OAAO2F;YACPX,QAAQA;YACRC,WAAWA;YACXI,UAAUA;YACVC,YAAYA;YACZf,KAAK,GAAEM,OAAAA,oBAAAA,YAAaU,sBAAbV,OAA2BvB;YAClCwD,QAAQN;YACRO,UAAUnH,MAAM,OAAOjB,YAAYgI;YACnCrC,WAAWuC;YACXG,UAAUzE,WAAW9B;YACrBiC,YAAYA;YACZkC,OAAOA;WAhBFtD,gBAAO0D,0BAAAA,OAAQpF,EAAE,oBAAIlC;IAmBhC;IAEA,OAAO;QACL4C;QACA2G,WAAWvG;QACXc;QACAE;QACAjB;QACA2B;QACAoC;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/crud/make-entity-crud.tsx"],"sourcesContent":["'use client';\n\nimport {\n deleteUCFactory,\n EntityIdTag,\n type EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n describeEntityColumns,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityMetadataSource,\n type EntitySelection,\n type EntityUseCaseRunner,\n type EntityWriter,\n envelopeEntityName,\n extractMetaEntity,\n type FilterGroup,\n Internal,\n isFailure,\n settled,\n type UseCaseDescriptor,\n} from '@entifix/core';\nimport { EntityTable, useCasesForSurface } from '@entifix/react-controls';\nimport {\n entityQueryScope,\n type OptimisticMutation,\n useDataLoading,\n useEntityRecord,\n useOptimisticMutation,\n} from '@entifix/react-integration';\nimport type { TransactionSink } from '@entifix/transactions';\nimport { TransactionSinkTag } from '@entifix/transactions';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { Cause, Context, Effect, Exit } from 'effect';\nimport { useParams, useRouter } from 'next/navigation';\nimport { useEffect, useRef } from 'react';\n\nimport { useLocaleHref } from '../i18n/index.js';\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport {\n pendingFor,\n pendingRecordsFor,\n usePendingTransactions,\n} from '../workspace/pending-transactions.js';\nimport { EntityCrudForm } from './entity-crud-form.js';\nimport { handOffWrite } from './hand-off-write.js';\nimport type {\n AnyFilterGroup,\n EntityCrud,\n EntityCrudLinkSource,\n EntityCrudOptions,\n EntityCrudSingleViewProps,\n} from './make-entity-crud.types.js';\nimport { PendingNotice } from './pending-notice.js';\nimport { CATALOG_NEW_SLUG, slugToEntityId } from './slug.js';\nimport { useCrudRenderLink } from './use-crud-render-link.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityBulk } from './use-entity-bulk.js';\n\n/** What a picker defaults to reading off its target. */\nconst TARGET_NAME_PROPERTY = 'name';\n\n/**\n * What the generated pages' use-cases run against.\n *\n * Exported because a hand-built screen needs the same three: a wizard reads\n * records, resolves pickers and writes through exactly these ports, and\n * rebuilding the union at each such call site is how one of them ends up\n * missing `TransactionSinkTag` and quietly losing its optimistic treatment.\n */\nexport type CrudContext = EntityRepositoryTag | TransactionSinkTag;\n\n/**\n * Adds the pending-write sink to one repository adapter, giving the context the\n * use-cases run against.\n *\n * The cast is the price of naming adapters by key: `AdapterKey` narrows which\n * names may be *offered*, but TypeScript will not carry that narrowing through\n * an index access on a generic record.\n */\nexport function mergeCrudContext<TAdapters>(\n adapters: TAdapters,\n repository: keyof TAdapters,\n sink: TransactionSink,\n): Context.Context<CrudContext> {\n return Context.add(\n adapters[repository] as Context.Context<EntityRepositoryTag>,\n TransactionSinkTag,\n sink,\n );\n}\n\n/**\n * Builds the list page and the single-record page for one entity.\n *\n * Every catalog entity used to cost ~10 files and ~300 lines whose only variable\n * was a class name: two organisms with a `.types.ts` each, two client pages, two\n * route files. The route files stay (Next needs a module per path); everything\n * between them is derived from the entity's own metadata, so a new reference\n * entity is this call plus a nav entry.\n *\n * Two things are checked here rather than at the call site, because both fail\n * silently otherwise. The catalog key must be the entity's own `@entity({ key })`\n * — they are the same string by convention, and a drifted one titles the form\n * after a different entity in a way only a reader of both catalogs would catch.\n * And a `links` entry must name a real member — a picker aimed at nothing renders\n * identically to a read-only field.\n *\n * **Serves compile-time `@entity()` classes only.** Operator reference data ships\n * with the code, so making this spec-driven would trade type safety for nothing;\n * a vendor-authored `EntitySpecification` renders through a separate path.\n */\n/**\n * A rejected write, as something the form's error slot can render.\n *\n * A typed failure is kept as it is: `useErrorMessage` translates its own code,\n * a business refusal and an outage alike. Anything else is a bug that reached\n * the screen, and is shown as `Internal` — never with its own text, which\n * nobody wrote for a user.\n */\nfunction asFailure(failure: unknown): EntifixFailure {\n return isFailure(failure) ? failure : new Internal();\n}\n\n/**\n * What a write failed with *synchronously* — before any flow took it — or\n * `undefined`. A flow's own failure is toasted by the `PendingFlowsProvider`\n * that settles it, so showing it in the error slot too would tell the operator\n * twice.\n */\nfunction syncFailure(\n mutation: OptimisticMutation<never, unknown>,\n): EntifixFailure | undefined {\n return mutation.status === 'failed' && mutation.flowId === undefined\n ? asFailure(mutation.failure)\n : undefined;\n}\n\n/**\n * A runner's verbs, looked up by the key the served `$metadata` named. A\n * single verb answers either settle mode, so it is run through the optimistic\n * API; a bulk run reports per row and is awaited as a promise whose rejection\n * carries the failure itself.\n */\nfunction verbsOf(\n runner: EntityUseCaseRunner | undefined,\n served: readonly UseCaseDescriptor[] | undefined,\n) {\n if (runner === undefined) return undefined;\n // The key always comes from the served document, so it names a verb in it.\n const descriptor = (key: string) =>\n served?.find(candidate => candidate.key === key) as UseCaseDescriptor;\n return {\n run: (key: string, id: EntityId) => runner.run(descriptor(key), id),\n bulk: (key: string, selection: EntitySelection<Entity>) =>\n Effect.runPromiseExit(runner.bulk(descriptor(key), selection)).then(\n exit =>\n Exit.isSuccess(exit)\n ? exit.value\n : Promise.reject(Cause.squash(exit.cause)),\n ),\n };\n}\n\ntype Verbs = NonNullable<ReturnType<typeof verbsOf>>;\n\n/**\n * One verb on one record, through the optimistic API: `done` runs once the\n * verb took effect — at once when it settled, or when the flow it was handed\n * to completed.\n */\nfunction useVerb(verbs: Verbs | undefined, done: () => void) {\n const verb = useOptimisticMutation<\n { readonly key: string; readonly id: EntityId },\n unknown\n >({\n // Only ever sent from a handler that exists because `verbs` does.\n write: ({ key, id }) => (verbs as Verbs).run(key, id),\n confirm: done,\n });\n const run = (key: string, id: EntityId) => {\n void verb.mutate({ key, id }).then(\n result => {\n if (result._tag === 'settled') done();\n },\n // Shown through `syncFailure`, from the mutation's own state.\n () => undefined,\n );\n };\n return { verb, run };\n}\n\n/** Whether the component is still mounted: a flow can settle after it left. */\nfunction useMounted() {\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n return mounted;\n}\n\n/**\n * Runs each link's `useBaseFiltering` against the record being edited, in link\n * order, with `undefined` for a link that declares none.\n *\n * Legal for the reason `useEntityLinkSources` gives: the links are a\n * factory-time array, and whether a link carries a rule is fixed with it, so\n * the same hooks run in the same order on every render. The lint rule cannot\n * see a hook called through a member, so there is nothing for it to flag.\n */\nfunction useLinkFilters<TEntity extends Entity>(\n links: readonly {\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n }[],\n record: TEntity | undefined,\n): (AnyFilterGroup | undefined)[] {\n return links.map(link => link.useBaseFiltering?.(record));\n}\n\nexport function makeEntityCrud<TEntity extends Entity, TAdapters>(\n entityConstructor: EntityConstructor<TEntity>,\n options: EntityCrudOptions<TAdapters, TEntity>,\n): EntityCrud<TEntity> {\n const {\n useAdapters,\n basePath,\n catalogKey,\n repository,\n hiddenFields = [],\n columns,\n toolbar,\n pageSize,\n links = [],\n metadataSource: givenMetadataSource,\n metadata,\n useCases,\n write,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new Error(\n `${entityConstructor.name} was given both metadataSource and metadata; pass one`,\n );\n }\n // An adapter value, so it is resolved per render from the same `useAdapters()`\n // the records come from — the host's composition, never the caller's module.\n const metadataSourceOf = (adapters: TAdapters) =>\n metadata === undefined\n ? givenMetadataSource\n : (adapters[metadata] as EntityMetadataSource);\n\n const meta = extractMetaEntity(entityConstructor);\n if (meta.key !== catalogKey) {\n throw new Error(\n `${entityConstructor.name} declares key \"${String(meta.key)}\" but was given catalog key \"${catalogKey}\"`,\n );\n }\n // Read off `@entity()` rather than rebuilt from `catalogKey`. Both spellings\n // produce the same string today, and that is exactly the problem: a second\n // place that knows how an entity's catalog subtree is laid out is a second\n // place to fix when one moves. `MetaEntityOptions` makes them optional, so an\n // entity that never declared them fails here — where a screen is generated —\n // rather than on the render that first tries to title a tab with `undefined`.\n const { labelKey: entityLabelKey, pluralKey: entityPluralKey } = meta;\n if (entityLabelKey === undefined || entityPluralKey === undefined) {\n throw new Error(\n `${entityConstructor.name} must declare labelKey and pluralKey on @entity() to be generated`,\n );\n }\n\n // Computed once: a descriptor is a property of the class, so nothing about it\n // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`\n // are overridden here because a scalar foreign key's `@accessor()` cannot name\n // the target's members — it may not import the target at all.\n // The wire name, which is also what a pending entry records and what\n // `entityQueryScopeFor` keys on — one derivation, so a notice and an\n // invalidation can never disagree about which entity they mean.\n const entityName = envelopeEntityName(entityConstructor);\n const descriptors = describeEntityColumns(entityConstructor);\n const linkPlans = links.map(link => {\n const descriptor = descriptors.find(entry => entry.name === link.field);\n if (descriptor === undefined) {\n throw new Error(\n `${entityConstructor.name} has no member \"${link.field}\" for a link source`,\n );\n }\n return {\n ...link,\n descriptor: {\n ...descriptor,\n linkLabelProperty: link.labelProperty ?? TARGET_NAME_PROPERTY,\n linkSearchProperty: link.searchProperty ?? TARGET_NAME_PROPERTY,\n },\n };\n });\n\n function ListPage() {\n const adapters = useAdapters();\n // Outside a `PendingTransactionsProvider` this watches nothing, so a host\n // that has not mounted one behaves exactly as it did before.\n const pending = usePendingTransactions();\n // Every internal href carries the locale. An unprefixed one still resolves —\n // the middleware redirects it — but the visitor pays a round trip per click.\n const withLocale = useLocaleHref();\n\n const queryClient = useQueryClient();\n const scope = entityQueryScope(entityConstructor);\n const metadataSource = metadataSourceOf(adapters);\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const renderLink = useCrudRenderLink(catalogKey);\n\n // Records this browser has created but the service has not finished\n // writing. Prepended below rather than patched into the cache, which a\n // refetch would undo.\n const optimistic = pendingRecordsFor<TEntity>(pending, entityName);\n\n const pager = useDataLoading<TEntity, CrudContext>({\n uc: loadUCFactory<TEntity>(),\n ctx: mergeCrudContext(adapters, repository, pending),\n // Scoped rather than left to the per-instance fallback, which is correct\n // but unshared: with the entity's own scope one invalidation refreshes\n // every page and filter of it, which is what a bulk run needs — and it is\n // the same prefix `useReactiveInvalidation`already targets, so a generated\n // list now also refreshes on a reactive change event.\n queryKey: scope,\n ...(pageSize === undefined ? {} : { initialPageSize: pageSize }),\n });\n\n // Only when this caller may actually run something over a selection.\n //\n // Measured live: an `admin` holds `catalog-reference:*:read` and no\n // `retire`, so the service filters the verb out of `$metadata` — but the\n // selection column still rendered, offering a set that no action could be\n // taken on. A checkbox that can lead nowhere is worse than no checkbox: it\n // reads as a permission the user does not have.\n //\n // Decided from the served document rather than from the runner, because\n // the runner is a property of the *shell* (it knows the route) and the\n // grant is a property of the *caller*. The column therefore appears when\n // the document lands, which is the asynchrony serving affordances accepts\n // for every action surface.\n const canRunBulk =\n useCasesForSurface('bulk-bar', affordances.metadata?.useCases).length > 0;\n\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n\n const bulk = useEntityBulk<TEntity>({\n run:\n canRunBulk && verbs !== undefined\n ? (key, selection) =>\n verbs.bulk(key, selection as EntitySelection<Entity>)\n : undefined,\n // A bulk write changed the rows underneath the listing, so the page is\n // re-read; the selection deliberately survives it (\"the selection\n // is still there afterwards\"), because the operator's next act is usually\n // to retry the failures or run a second verb on the same rows.\n onCompleted: () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n },\n });\n\n // What a row's overflow menu runs, and the one place the list reports a\n // verb that failed.\n //\n // ⚠️ **A row verb and the form's are the same runner with different\n // arguments.** `EntityTable` hands back the whole record, because that is\n // what it has; the runner takes an id, because that is what a route needs.\n // The list has no error slot of its own, so a failure lands in the\n // table's own error region — the same one a failed page read uses.\n const rowVerb = useVerb(verbs, () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n });\n // Called unconditionally and the *result* gated, the way the surfaces are\n // read in `EntityForm`: the name begins with `use`, so short-circuiting it\n // reads to `react-hooks/rules-of-hooks` as a conditional hook.\n const rowUseCases = useCasesForSurface(\n 'row-menu',\n affordances.metadata?.useCases,\n );\n const canRunRowUseCase = verbs !== undefined && rowUseCases.length > 0;\n\n const handleRowUseCase = canRunRowUseCase\n ? (key: string, item: TEntity) => {\n if (item.id == null) return;\n rowVerb.run(key, item.id);\n }\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-s\">\n {/* Above the table, because this is where `afterSave()` leaves the\n operator after a create — and a create is the only transactional\n write there is, so this is the surface the pending state has. */}\n <PendingNotice\n entries={pendingFor(pending, entityName)}\n onDismiss={pending.dismiss}\n />\n <EntityTable\n entityConstructor={entityConstructor}\n {...pager}\n items={[...optimistic, ...pager.items]}\n totalItems={pager.totalItems + optimistic.length}\n hrefFor={id => withLocale(`${basePath}/${String(id)}`)}\n newHref={withLocale(`${basePath}/${CATALOG_NEW_SLUG}`)}\n renderLink={renderLink}\n {...affordances}\n {...bulk.tableProps}\n onUseCase={handleRowUseCase}\n error={syncFailure(rowVerb.verb) ?? pager.error}\n >\n {columns}\n {toolbar}\n </EntityTable>\n </div>\n );\n }\n\n /**\n * Dual-host: as a route it reads its slug from the URL and returns to the list\n * on save; in a workspace tab it takes the slug and the post-save action as\n * props.\n */\n function SingleViewPage({\n slug,\n onSaved,\n onDeleted,\n draft,\n }: EntityCrudSingleViewProps = {}) {\n const adapters = useAdapters();\n const metadataSource = metadataSourceOf(adapters);\n // The same served document the form reads its buttons from, so a key the\n // form hands back always names a verb in it.\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const pending = usePendingTransactions();\n const router = useRouter();\n const withLocale = useLocaleHref();\n const params = useParams<{ slug: string }>();\n const mounted = useMounted();\n const id = slugToEntityId(slug ?? params.slug);\n\n const ctx = mergeCrudContext(adapters, repository, pending);\n\n const {\n entity,\n isLoading,\n error: loadError,\n reload,\n } = useEntityRecord<TEntity, CrudContext>({\n uc: getUCFactory<TEntity>(),\n ctx,\n id,\n });\n\n // Against the record as loaded, not the draft: the rule is about which\n // record this is, not what the operator has typed into it.\n const linkFilters = useLinkFilters(linkPlans, entity);\n\n // Rebuilt inline on every render on purpose: `useEntityLinkSource` holds\n // these in a ref and keeps them out of its query keys, precisely so a caller\n // does not have to memoise them.\n const linkSources: EntityCrudLinkSource[] = linkPlans.map(\n (plan, index) => ({\n field: plan.field,\n descriptor: plan.descriptor,\n config: {\n entityConstructor: plan.entityConstructor,\n loadUc: loadUCFactory(),\n getUc: getUCFactory(),\n ctx: mergeCrudContext(adapters, plan.repository, pending),\n // The config's target is erased to `Entity`, and the host's filter to\n // `any`; the two meet here, where neither type is the real target's.\n baseFiltering: linkFilters[index] as FilterGroup<Entity> | undefined,\n },\n }),\n );\n\n // Inside a workspace tab, \"back to the list\" is the list's tab, not a URL\n // that would leave the workspace. A host's own callbacks still win.\n const host = useEntityNavHost();\n const renderLink = useCrudRenderLink(catalogKey);\n const queryClient = useQueryClient();\n // The list this page returns to has its page cached, and it is no longer\n // true. Invalidated rather than patched, for the reason `handOffWrite`\n // gives: a transactional create is not in the service yet, and the pending\n // set, not the cache, is what keeps it visible until it is.\n //\n // ⚠️ Invisible while every Open was a document load, which threw the cache\n // away anyway (#20): the first client-side navigation back to the list\n // showed the record as it was before the save.\n const refreshList = () =>\n queryClient.invalidateQueries({\n queryKey: entityQueryScope(entityConstructor),\n });\n const toList = () =>\n host === undefined\n ? router.push(withLocale(basePath))\n : host.toList(catalogKey);\n const afterSave = onSaved ?? toList;\n const afterDelete = onDeleted ?? toList;\n\n // Through the host's writer when it named one, which answers both settle\n // modes; otherwise through the repository, where every write settles.\n const writer =\n write === undefined ? undefined : (adapters[write] as EntityWriter);\n\n // The draft is spent once the write *commits*, and only here is that known:\n // `useEntityForm` neither fetches nor saves, so it cannot clear its own.\n // A failed write — or a failed flow — deliberately keeps the draft and the\n // form: the edit is still the user's only copy of what they typed.\n //\n // ⚠️ A flow can complete after the operator left this page, so leaving it\n // is guarded on still being here: a navigation from a form nobody is\n // looking at would pull them away from wherever they went.\n const saveMutation = useOptimisticMutation<TEntity, TEntity>({\n write: next =>\n writer === undefined\n ? Effect.map(\n Effect.provide(\n saveUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityTag, next)),\n ),\n settled,\n )\n : writer.save(next),\n intent: () => ({ entity: entityName, write: 'save' }),\n confirm: () => {\n draft?.clear();\n void refreshList();\n if (mounted.current) afterSave();\n },\n });\n const deleteMutation = useOptimisticMutation<EntityId, void>({\n write: target =>\n writer === undefined\n ? Effect.as(\n Effect.provide(\n deleteUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityIdTag, target)),\n ),\n settled(undefined),\n )\n : writer.delete(target),\n intent: () => ({ entity: entityName, write: 'delete' }),\n confirm: () => {\n draft?.clear();\n void refreshList();\n if (mounted.current) afterDelete();\n },\n });\n\n const handleSave = async (next: TEntity) => {\n const result = await saveMutation.mutate(next).catch(() => undefined);\n // Failed, or pending: the form stays, and the mutation says which.\n if (result?._tag !== 'settled') return;\n const saved = result.value;\n\n // ⚠️ Deliberately *not* a `setQueriesData` patch. The list refetches on\n // mount — precisely when the operator arrives, having just been navigated\n // here — and the server legitimately does not hold the record yet, so the\n // refetch would replace the patched page and the row would vanish a\n // moment after appearing. The pending set outlives refetches.\n handOffWrite({ id: String(saved.id), record: saved, pending, draft });\n void refreshList();\n afterSave();\n };\n\n const handleDelete = async () => {\n const result = await deleteMutation.mutate(id).catch(() => undefined);\n if (result?._tag !== 'settled') return;\n draft?.clear();\n void refreshList();\n afterDelete();\n };\n\n /**\n * An `entity`-bound verb, on the record being shown.\n *\n * It **reloads** — once the verb took effect, which for one the server\n * handed to a flow is when the flow completed — rather than patching what it has: the service decides the\n * resulting state — a `publish` may land on `published` from four different\n * places — and a client that assumed the new value would show the wrong one\n * the first time the rule changed. `id == null` means the create form,\n * where there is no record to act on and the form renders no verbs anyway.\n *\n * ⚠️ The rejection is **caught and shown**, never left to the promise.\n * `EntityForm`'s `onUseCase` returns `void`, so an uncaught rejection here\n * reaches the console and nothing else — measured on an offering refusing\n * `unpublish` from `draft`: the service answered `409` with a coded body,\n * the record correctly did not move, and the operator saw a button that\n * appeared to do nothing at all.\n */\n const verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n const recordVerb = useVerb(verbs, () => void reload());\n const handleUseCase =\n verbs === undefined || id == null\n ? undefined\n : (key: string) => recordVerb.run(key, id);\n\n return (\n <EntityCrudForm<TEntity>\n // Remounts (and reseeds the fields) once the record arrives.\n key={String(entity?.id ?? CATALOG_NEW_SLUG)}\n entityConstructor={entityConstructor}\n catalogKey={catalogKey}\n metadataSource={metadataSource}\n hiddenFields={hiddenFields}\n links={linkSources}\n entity={entity}\n isLoading={isLoading}\n isSaving={saveMutation.status === 'running'}\n isPending={[saveMutation, deleteMutation, recordVerb.verb].some(\n mutation => mutation.status === 'pending',\n )}\n isDeleting={deleteMutation.status === 'running'}\n error={\n loadError ??\n syncFailure(saveMutation) ??\n syncFailure(deleteMutation) ??\n syncFailure(recordVerb.verb)\n }\n onSave={handleSave}\n onDelete={id == null ? undefined : handleDelete}\n onUseCase={handleUseCase}\n backHref={withLocale(basePath)}\n renderLink={renderLink}\n draft={draft}\n />\n );\n }\n\n return {\n entityConstructor,\n entityKey: catalogKey,\n entityLabelKey,\n entityPluralKey,\n basePath,\n ListPage,\n SingleViewPage,\n };\n}\n"],"names":["deleteUCFactory","EntityIdTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","describeEntityColumns","envelopeEntityName","extractMetaEntity","Internal","isFailure","settled","EntityTable","useCasesForSurface","entityQueryScope","useDataLoading","useEntityRecord","useOptimisticMutation","TransactionSinkTag","useQueryClient","Cause","Context","Effect","Exit","useParams","useRouter","useEffect","useRef","useLocaleHref","useEntityNavHost","pendingFor","pendingRecordsFor","usePendingTransactions","EntityCrudForm","handOffWrite","PendingNotice","CATALOG_NEW_SLUG","slugToEntityId","useCrudRenderLink","useEntityAffordances","useEntityBulk","TARGET_NAME_PROPERTY","mergeCrudContext","adapters","repository","sink","add","asFailure","failure","syncFailure","mutation","status","flowId","undefined","verbsOf","runner","served","descriptor","key","find","candidate","run","id","bulk","selection","runPromiseExit","then","exit","isSuccess","value","Promise","reject","squash","cause","useVerb","verbs","done","verb","write","confirm","mutate","result","_tag","useMounted","mounted","current","useLinkFilters","links","record","map","link","useBaseFiltering","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","pageSize","metadataSource","givenMetadataSource","metadata","useCases","Error","name","metadataSourceOf","meta","String","labelKey","entityLabelKey","pluralKey","entityPluralKey","entityName","descriptors","linkPlans","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListPage","affordances","pending","withLocale","queryClient","scope","renderLink","optimistic","pager","uc","ctx","queryKey","initialPageSize","canRunBulk","length","onCompleted","invalidateQueries","rowVerb","rowUseCases","canRunRowUseCase","handleRowUseCase","item","div","className","entries","onDismiss","dismiss","items","totalItems","hrefFor","newHref","tableProps","onUseCase","error","SingleViewPage","slug","onSaved","onDeleted","draft","loadError","router","params","entity","isLoading","reload","linkFilters","linkSources","plan","index","config","loadUc","getUc","baseFiltering","host","refreshList","toList","push","afterSave","afterDelete","writer","saveMutation","next","provide","pipe","save","intent","clear","deleteMutation","target","as","delete","handleSave","catch","saved","handleDelete","recordVerb","handleUseCase","isSaving","isPending","some","isDeleting","onSave","onDelete","backHref","entityKey"],"mappings":"AAAA;;;AAEA,SACEA,eAAe,EACfC,WAAW,EAEXC,SAAS,EACT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B;QACAkC;IACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EntityRepositoryTag } from '@entifix/business';
|
|
2
|
-
import type { Entity, EntityConstructor, EntityFieldDescriptor, EntityMetadataSource, EntityUseCaseRunner, FilterGroup } from '@entifix/core';
|
|
2
|
+
import type { Entity, EntityConstructor, EntityFieldDescriptor, EntityMetadataSource, EntityUseCaseRunner, EntityWriter, FilterGroup } from '@entifix/core';
|
|
3
3
|
import type { EntityDraftStore, EntityLinkSourceConfig } from '@entifix/react-integration';
|
|
4
4
|
import type { Context } from 'effect/Context';
|
|
5
5
|
import type { CustomTypeOptions } from 'i18next';
|
|
@@ -199,6 +199,18 @@ export interface EntityCrudOptions<TAdapters, TEntity extends Entity> {
|
|
|
199
199
|
* a promise nobody catches.
|
|
200
200
|
*/
|
|
201
201
|
readonly useCases?: AdapterKey<TAdapters, EntityUseCaseRunner>;
|
|
202
|
+
/**
|
|
203
|
+
* Which adapter makes this entity's saves and deletes, answering both
|
|
204
|
+
* settle modes — `buildEntityRestAdapterWrite` over REST. Resolved from the
|
|
205
|
+
* host's composition, as {@link repository} is.
|
|
206
|
+
*
|
|
207
|
+
* Omitted, the form writes through {@link repository}, and every write
|
|
208
|
+
* settles. Supplied, a write the server hands to a flow keeps the form open
|
|
209
|
+
* and waiting, with what was typed, until the flow settles: a completed one
|
|
210
|
+
* returns to the list, and a failed one is toasted once by the
|
|
211
|
+
* `PendingFlowsProvider` above while the form keeps its input.
|
|
212
|
+
*/
|
|
213
|
+
readonly write?: AdapterKey<TAdapters, EntityWriter>;
|
|
202
214
|
}
|
|
203
215
|
/**
|
|
204
216
|
* Props both hosts pass. A route host passes none — the slug comes from the URL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make-entity-crud.types.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/make-entity-crud.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CA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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/crud/make-entity-crud.types.ts"],"sourcesContent":["import type { EntityRepositoryTag } from '@entifix/business';\nimport type {\n Entity,\n EntityConstructor,\n EntityFieldDescriptor,\n EntityMetadataSource,\n EntityUseCaseRunner,\n FilterGroup,\n} from '@entifix/core';\nimport type {\n EntityDraftStore,\n EntityLinkSourceConfig,\n} from '@entifix/react-integration';\nimport type { Context } from 'effect/Context';\nimport type { CustomTypeOptions } from 'i18next';\nimport type { ReactElement, ReactNode } from 'react';\n\n/**\n * The `entity` catalog keys that carry **both** form titles, a `label` and a\n * `plural`.\n *\n * Derived from the Spanish catalog rather than written out, so the union is the\n * catalog: an entity whose subtree has no `form.editTitle`/`form.newTitle`\n * cannot be handed to {@link makeEntityCrud} at all, and adding a reference\n * entity therefore starts by adding its copy to both locales. That is the whole\n * i18n gate for this factory — a host's catalog check typically scans its\n * domain packages for `@useCase()` decorators and never `.tsx`, so a runtime\n * key here would be checked by nothing.\n *\n * `label`/`plural` joined the condition when {@link EntityCrud} began carrying\n * them, so that a workspace tab and a nav entry derived from this descriptor\n * name the entity in the catalog's own words. They are part of the **type**\n * rather than a runtime assertion in the factory, because the catalog is\n * statically known here: a missing `plural` should fail at the call site that\n * generates the screens, not on the render that first tries to title a tab.\n *\n * Keeping the key typed is what lets the generated form call `useT('entity')`\n * with a template literal and still fail the build on a typo, instead of\n * reaching for the `useTranslateKey` escape hatch that authored copy must not\n * use. `AccountLabelKey` in `../session/account-links.ts` is the same trick\n * written out by hand; this one cannot drift because it is computed.\n */\nexport type EntityCatalogKey<\n TEntityCatalog = EntityCatalogOf<TypeOptionsResources>,\n> = [TEntityCatalog] extends [never]\n ? // No host augmentation in this compilation — this package's own specs, or\n // an adopter who has not declared one. The factory still works; the key is\n // simply unchecked, which is the same trade `useTranslateKey` makes.\n string\n : {\n [K in keyof TEntityCatalog]: TEntityCatalog[K] extends {\n form: { editTitle: string; newTitle: string };\n label: string;\n plural: string;\n }\n ? K\n : never;\n }[keyof TEntityCatalog] &\n string;\n\n/**\n * The host's `entity` namespace, read back out of its own `i18next`\n * augmentation.\n *\n * ⚠️ **The `entity` catalog is the host's, not entifix's.** It names *their*\n * entities — a parameter, an offering, a sales channel — so a framework that\n * shipped one would be shipping an application's product copy. Reading it back\n * through `CustomTypeOptions` keeps the key union computed rather than written\n * out, which is what stops it drifting, while leaving the catalog where it\n * belongs. A host that declares no augmentation gets `string`, and the factory\n * still works with the gate relaxed.\n */\ntype TypeOptionsResources = CustomTypeOptions extends { resources: infer R }\n ? R\n : never;\n\ntype EntityCatalogOf<TResources> = TResources extends { entity: infer E }\n ? E\n : never;\n\n/**\n * A relation the generated form edits with a picker.\n *\n * The target is named here rather than derived, because the common case is a\n * **plain foreign key**: when the target lives in another slice's store a typed\n * `EntityLink` is both an illegal import and a cross-store join, so the member\n * is a bare `string` (`ProductSpecification.brandId` into `catalog-reference`)\n * and its `@accessor()` has no vocabulary for \"the target's name\". Hence\n * `labelProperty`/`searchProperty` are stated at the call site instead of being\n * left to `describeEntityColumns`' `'name'` default, which happens to be right\n * today and states nothing.\n *\n * `searchProperty` must be `filterable` on the **target** or the service answers\n * `400`; `useEntityLinkSource` throws at render rather than letting that surface\n * as an empty suggestion list.\n */\nexport interface EntityCrudLink<TAdapters, TEntity extends Entity = Entity> {\n /** The owning entity's accessor name, e.g. `'brandId'`. */\n readonly field: string;\n readonly entityConstructor: EntityConstructor<Entity>;\n /**\n * Which adapter holds the **target's** repository. Often a different service\n * than the record's own: `catalog-reference` is another slice's store, so\n * resolving an id goes through that domain's own read path.\n */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /** Defaults to `'name'`. */\n readonly labelProperty?: string;\n /** Defaults to `'name'`. Must be `filterable` on the target. */\n readonly searchProperty?: string;\n /**\n * A restriction on what may be picked **for this record**, ANDed into every\n * quick and browse request — `useEntityLinkSource`'s `baseFiltering`, built\n * from the record being edited rather than fixed at factory time.\n *\n * A record-dependent rule is the case it exists for: a parent picker that\n * must not offer the record itself or anything beneath it. That rule needs\n * more than the record — its descendants are other records — which is why\n * this is a **hook** and not a function of the record: it may load what it\n * needs through the host's own adapters, and answer `undefined` until it has.\n *\n * Called on every render of the single view, under the rules of hooks: once\n * per link, unconditionally, with `undefined` while the record loads and\n * throughout a create. `undefined` back means no restriction. Its members\n * must be `filterable` on the target, or the service answers `400`. It\n * narrows the suggestions and nothing else — the service still has to refuse\n * a value the picker would not have offered.\n */\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n}\n\n/**\n * A restriction over a picker's target, with the target's type erased — the\n * link names its target only as `EntityConstructor<Entity>`, so a filter typed\n * on the real target would not be assignable. Erased for the reason\n * {@link AnyEntityLinkSourceConfig} is.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFilterGroup = FilterGroup<any>;\n\n/** The keys of `TAdapters` whose value is assignable to `TValue`. */\nexport type AdapterKey<TAdapters, TValue> = {\n [K in keyof TAdapters]: TAdapters[K] extends TValue ? K : never;\n}[keyof TAdapters];\n\nexport interface EntityCrudOptions<TAdapters, TEntity extends Entity> {\n /** The domain shell's adapters hook, e.g. `useMarketplaceAdminAdapters`. */\n readonly useAdapters: () => TAdapters;\n /** Route prefix for both pages, e.g. `'/catalog/product-brand'`. */\n readonly basePath: string;\n /**\n * The entity's `entity` catalog key. Asserted against `@entity({ key })` at\n * factory time — the two are the same string by convention\n * (`entity:product-brand.label` mirrors `key: 'product-brand'`), and letting\n * them drift would title a form after a different entity.\n */\n readonly catalogKey: EntityCatalogKey;\n /** Which adapter holds this entity's own repository. */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /**\n * Members the form keeps but does not show — `id` always, plus anything a\n * transaction assigns. A hidden member still round-trips: it is dropped from\n * the rendered fields, not from the draft, so `reconstructEntity` carries it\n * back out of the seeded values.\n */\n readonly hiddenFields?: readonly string[];\n /** `<EntityColumn>` overrides for the list, for presentation metadata cannot express. */\n readonly columns?: ReactNode;\n /**\n * Extra controls beside the table's own — an `<EntityTableToolbar>`.\n *\n * Its own option rather than more `columns`, though both end up as\n * `EntityTable` children and the slots are sorted by component identity: a\n * toolbar filed under a columns prop is a name that lies, and the first thing\n * to go here is a link into a wizard, which is not a column by any reading.\n */\n readonly toolbar?: ReactNode;\n /**\n * How many rows the list asks for on its first load. Defaults to\n * `useDataLoading`'s own default.\n *\n * Raised for a vocabulary that should be seen whole: `EntityTable` nests a\n * hierarchy only within the page it was given, so a tree larger than one page\n * shows the children whose parent fell on another page as roots.\n */\n readonly pageSize?: number;\n /** Frozen at factory time — see `use-entity-link-sources.ts`. */\n readonly links?: readonly EntityCrudLink<TAdapters, TEntity>[];\n /**\n * Where the entity's served affordances come from — `GET /api/<entity>/$metadata`.\n *\n * Supplying it is what turns on every served affordance:\n * Save and Delete filtered against the caller's real grants, the declared\n * verbs on the form, the row overflow menu, and the bulk bar. Omitting it\n * keeps the pre-0026 behaviour exactly, which is what every generated catalog\n * rendered before this option existed.\n *\n * A `EntityMetadataSource` rather than a URL because the two hosts reach\n * their service differently — one through the config-driven REST adapters,\n * one through a shell's own same-origin routes.\n */\n readonly metadataSource?: EntityMetadataSource;\n /**\n * Which adapter holds this entity's {@link EntityMetadataSource} — the same\n * source as {@link metadataSource}, resolved from the host's composition\n * instead of built by the caller.\n *\n * Prefer it: a source is a transport, and naming it by key keeps the module\n * that generates the screens free of the adapter that fetches, exactly as\n * {@link repository} already does for records. Supplying both is a build\n * error — two answers to where the document comes from.\n */\n readonly metadata?: AdapterKey<TAdapters, EntityMetadataSource>;\n /**\n * Which adapter runs this entity's `@useCase()` verbs — over REST against\n * the service that serves them, or in-process for records that live in the\n * browser. Resolved from the host's composition, as {@link repository} is.\n *\n * Supplying it lets the generated screens run what the served `$metadata`\n * lists for the caller: a row's menu and a form's buttons run a verb on a\n * record, and the bulk bar runs a `collection` verb over a selection,\n * reporting per row. A verb that resolves reloads what it changed; one that\n * refuses shows its coded message in the screen's error slot rather than as\n * a promise nobody catches.\n */\n readonly useCases?: AdapterKey<TAdapters, EntityUseCaseRunner>;\n}\n\n/**\n * Props both hosts pass. A route host passes none — the slug comes from the URL\n * and a save returns to the list; the workspace tab host passes all of them.\n */\nexport interface EntityCrudSingleViewProps {\n /** Defaults to the `[slug]` route param. */\n readonly slug?: string;\n /** Defaults to navigating back to the list. */\n readonly onSaved?: () => void;\n readonly onDeleted?: () => void;\n /**\n * Where to autosave the edit. Supplying it is the whole opt-in: the form\n * seeds from the persisted draft, writes to it on every edit, and the page\n * clears it once a save or delete commits.\n *\n * A route host omits it and stays ephemeral, which is the rule stated as a\n * missing prop rather than as a flag — there is no value of \"absent\" that\n * accidentally starts persisting.\n */\n readonly draft?: EntityDraftStore;\n}\n\n/**\n * What the factory returns: a **named descriptor**, not four loose components.\n *\n * The identity fields are here so the workspace registry and the nav are derived\n * from a list of these rather than from the hand-written const maps they replace.\n */\nexport interface EntityCrud<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n /** `@entity({ key })`, which is also `catalogKey` and the tab address payload. */\n readonly entityKey: EntityCatalogKey;\n /**\n * `@entity({ labelKey })` — how one record is named. A record tab's title.\n *\n * Read off the decorator rather than passed, so the tab strip, the nav and the\n * search results all name the entity from the one place it names itself.\n */\n readonly entityLabelKey: string;\n /** `@entity({ pluralKey })` — how the collection is named. A list tab's title. */\n readonly entityPluralKey: string;\n readonly basePath: string;\n readonly ListPage: () => ReactElement;\n readonly SingleViewPage: (props?: EntityCrudSingleViewProps) => ReactElement;\n}\n\n/**\n * A picker's transport with its context tags erased.\n *\n * The factory cannot preserve one type parameter per link — the pages that\n * build these know their adapters, the generated form only forwards them — and\n * `EntityForm.linkSources` is already `Record<string, EntityLinkSource<any>>`\n * for the same reason.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyEntityLinkSourceConfig = EntityLinkSourceConfig<Entity, any>;\n\n/**\n * One picker, resolved: the descriptor computed once at factory time, and the\n * use-cases plus adapter context the page builds per render.\n */\nexport interface EntityCrudLinkSource {\n readonly field: string;\n readonly descriptor: EntityFieldDescriptor;\n readonly config: AnyEntityLinkSourceConfig;\n}\n"],"names":[],"mappings":"AA+RA;;;CAGC,GACD,WAIC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/crud/make-entity-crud.types.ts"],"sourcesContent":["import type { EntityRepositoryTag } from '@entifix/business';\nimport type {\n Entity,\n EntityConstructor,\n EntityFieldDescriptor,\n EntityMetadataSource,\n EntityUseCaseRunner,\n EntityWriter,\n FilterGroup,\n} from '@entifix/core';\nimport type {\n EntityDraftStore,\n EntityLinkSourceConfig,\n} from '@entifix/react-integration';\nimport type { Context } from 'effect/Context';\nimport type { CustomTypeOptions } from 'i18next';\nimport type { ReactElement, ReactNode } from 'react';\n\n/**\n * The `entity` catalog keys that carry **both** form titles, a `label` and a\n * `plural`.\n *\n * Derived from the Spanish catalog rather than written out, so the union is the\n * catalog: an entity whose subtree has no `form.editTitle`/`form.newTitle`\n * cannot be handed to {@link makeEntityCrud} at all, and adding a reference\n * entity therefore starts by adding its copy to both locales. That is the whole\n * i18n gate for this factory — a host's catalog check typically scans its\n * domain packages for `@useCase()` decorators and never `.tsx`, so a runtime\n * key here would be checked by nothing.\n *\n * `label`/`plural` joined the condition when {@link EntityCrud} began carrying\n * them, so that a workspace tab and a nav entry derived from this descriptor\n * name the entity in the catalog's own words. They are part of the **type**\n * rather than a runtime assertion in the factory, because the catalog is\n * statically known here: a missing `plural` should fail at the call site that\n * generates the screens, not on the render that first tries to title a tab.\n *\n * Keeping the key typed is what lets the generated form call `useT('entity')`\n * with a template literal and still fail the build on a typo, instead of\n * reaching for the `useTranslateKey` escape hatch that authored copy must not\n * use. `AccountLabelKey` in `../session/account-links.ts` is the same trick\n * written out by hand; this one cannot drift because it is computed.\n */\nexport type EntityCatalogKey<\n TEntityCatalog = EntityCatalogOf<TypeOptionsResources>,\n> = [TEntityCatalog] extends [never]\n ? // No host augmentation in this compilation — this package's own specs, or\n // an adopter who has not declared one. The factory still works; the key is\n // simply unchecked, which is the same trade `useTranslateKey` makes.\n string\n : {\n [K in keyof TEntityCatalog]: TEntityCatalog[K] extends {\n form: { editTitle: string; newTitle: string };\n label: string;\n plural: string;\n }\n ? K\n : never;\n }[keyof TEntityCatalog] &\n string;\n\n/**\n * The host's `entity` namespace, read back out of its own `i18next`\n * augmentation.\n *\n * ⚠️ **The `entity` catalog is the host's, not entifix's.** It names *their*\n * entities — a parameter, an offering, a sales channel — so a framework that\n * shipped one would be shipping an application's product copy. Reading it back\n * through `CustomTypeOptions` keeps the key union computed rather than written\n * out, which is what stops it drifting, while leaving the catalog where it\n * belongs. A host that declares no augmentation gets `string`, and the factory\n * still works with the gate relaxed.\n */\ntype TypeOptionsResources = CustomTypeOptions extends { resources: infer R }\n ? R\n : never;\n\ntype EntityCatalogOf<TResources> = TResources extends { entity: infer E }\n ? E\n : never;\n\n/**\n * A relation the generated form edits with a picker.\n *\n * The target is named here rather than derived, because the common case is a\n * **plain foreign key**: when the target lives in another slice's store a typed\n * `EntityLink` is both an illegal import and a cross-store join, so the member\n * is a bare `string` (`ProductSpecification.brandId` into `catalog-reference`)\n * and its `@accessor()` has no vocabulary for \"the target's name\". Hence\n * `labelProperty`/`searchProperty` are stated at the call site instead of being\n * left to `describeEntityColumns`' `'name'` default, which happens to be right\n * today and states nothing.\n *\n * `searchProperty` must be `filterable` on the **target** or the service answers\n * `400`; `useEntityLinkSource` throws at render rather than letting that surface\n * as an empty suggestion list.\n */\nexport interface EntityCrudLink<TAdapters, TEntity extends Entity = Entity> {\n /** The owning entity's accessor name, e.g. `'brandId'`. */\n readonly field: string;\n readonly entityConstructor: EntityConstructor<Entity>;\n /**\n * Which adapter holds the **target's** repository. Often a different service\n * than the record's own: `catalog-reference` is another slice's store, so\n * resolving an id goes through that domain's own read path.\n */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /** Defaults to `'name'`. */\n readonly labelProperty?: string;\n /** Defaults to `'name'`. Must be `filterable` on the target. */\n readonly searchProperty?: string;\n /**\n * A restriction on what may be picked **for this record**, ANDed into every\n * quick and browse request — `useEntityLinkSource`'s `baseFiltering`, built\n * from the record being edited rather than fixed at factory time.\n *\n * A record-dependent rule is the case it exists for: a parent picker that\n * must not offer the record itself or anything beneath it. That rule needs\n * more than the record — its descendants are other records — which is why\n * this is a **hook** and not a function of the record: it may load what it\n * needs through the host's own adapters, and answer `undefined` until it has.\n *\n * Called on every render of the single view, under the rules of hooks: once\n * per link, unconditionally, with `undefined` while the record loads and\n * throughout a create. `undefined` back means no restriction. Its members\n * must be `filterable` on the target, or the service answers `400`. It\n * narrows the suggestions and nothing else — the service still has to refuse\n * a value the picker would not have offered.\n */\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n}\n\n/**\n * A restriction over a picker's target, with the target's type erased — the\n * link names its target only as `EntityConstructor<Entity>`, so a filter typed\n * on the real target would not be assignable. Erased for the reason\n * {@link AnyEntityLinkSourceConfig} is.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFilterGroup = FilterGroup<any>;\n\n/** The keys of `TAdapters` whose value is assignable to `TValue`. */\nexport type AdapterKey<TAdapters, TValue> = {\n [K in keyof TAdapters]: TAdapters[K] extends TValue ? K : never;\n}[keyof TAdapters];\n\nexport interface EntityCrudOptions<TAdapters, TEntity extends Entity> {\n /** The domain shell's adapters hook, e.g. `useMarketplaceAdminAdapters`. */\n readonly useAdapters: () => TAdapters;\n /** Route prefix for both pages, e.g. `'/catalog/product-brand'`. */\n readonly basePath: string;\n /**\n * The entity's `entity` catalog key. Asserted against `@entity({ key })` at\n * factory time — the two are the same string by convention\n * (`entity:product-brand.label` mirrors `key: 'product-brand'`), and letting\n * them drift would title a form after a different entity.\n */\n readonly catalogKey: EntityCatalogKey;\n /** Which adapter holds this entity's own repository. */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /**\n * Members the form keeps but does not show — `id` always, plus anything a\n * transaction assigns. A hidden member still round-trips: it is dropped from\n * the rendered fields, not from the draft, so `reconstructEntity` carries it\n * back out of the seeded values.\n */\n readonly hiddenFields?: readonly string[];\n /** `<EntityColumn>` overrides for the list, for presentation metadata cannot express. */\n readonly columns?: ReactNode;\n /**\n * Extra controls beside the table's own — an `<EntityTableToolbar>`.\n *\n * Its own option rather than more `columns`, though both end up as\n * `EntityTable` children and the slots are sorted by component identity: a\n * toolbar filed under a columns prop is a name that lies, and the first thing\n * to go here is a link into a wizard, which is not a column by any reading.\n */\n readonly toolbar?: ReactNode;\n /**\n * How many rows the list asks for on its first load. Defaults to\n * `useDataLoading`'s own default.\n *\n * Raised for a vocabulary that should be seen whole: `EntityTable` nests a\n * hierarchy only within the page it was given, so a tree larger than one page\n * shows the children whose parent fell on another page as roots.\n */\n readonly pageSize?: number;\n /** Frozen at factory time — see `use-entity-link-sources.ts`. */\n readonly links?: readonly EntityCrudLink<TAdapters, TEntity>[];\n /**\n * Where the entity's served affordances come from — `GET /api/<entity>/$metadata`.\n *\n * Supplying it is what turns on every served affordance:\n * Save and Delete filtered against the caller's real grants, the declared\n * verbs on the form, the row overflow menu, and the bulk bar. Omitting it\n * keeps the pre-0026 behaviour exactly, which is what every generated catalog\n * rendered before this option existed.\n *\n * A `EntityMetadataSource` rather than a URL because the two hosts reach\n * their service differently — one through the config-driven REST adapters,\n * one through a shell's own same-origin routes.\n */\n readonly metadataSource?: EntityMetadataSource;\n /**\n * Which adapter holds this entity's {@link EntityMetadataSource} — the same\n * source as {@link metadataSource}, resolved from the host's composition\n * instead of built by the caller.\n *\n * Prefer it: a source is a transport, and naming it by key keeps the module\n * that generates the screens free of the adapter that fetches, exactly as\n * {@link repository} already does for records. Supplying both is a build\n * error — two answers to where the document comes from.\n */\n readonly metadata?: AdapterKey<TAdapters, EntityMetadataSource>;\n /**\n * Which adapter runs this entity's `@useCase()` verbs — over REST against\n * the service that serves them, or in-process for records that live in the\n * browser. Resolved from the host's composition, as {@link repository} is.\n *\n * Supplying it lets the generated screens run what the served `$metadata`\n * lists for the caller: a row's menu and a form's buttons run a verb on a\n * record, and the bulk bar runs a `collection` verb over a selection,\n * reporting per row. A verb that resolves reloads what it changed; one that\n * refuses shows its coded message in the screen's error slot rather than as\n * a promise nobody catches.\n */\n readonly useCases?: AdapterKey<TAdapters, EntityUseCaseRunner>;\n /**\n * Which adapter makes this entity's saves and deletes, answering both\n * settle modes — `buildEntityRestAdapterWrite` over REST. Resolved from the\n * host's composition, as {@link repository} is.\n *\n * Omitted, the form writes through {@link repository}, and every write\n * settles. Supplied, a write the server hands to a flow keeps the form open\n * and waiting, with what was typed, until the flow settles: a completed one\n * returns to the list, and a failed one is toasted once by the\n * `PendingFlowsProvider` above while the form keeps its input.\n */\n readonly write?: AdapterKey<TAdapters, EntityWriter>;\n}\n\n/**\n * Props both hosts pass. A route host passes none — the slug comes from the URL\n * and a save returns to the list; the workspace tab host passes all of them.\n */\nexport interface EntityCrudSingleViewProps {\n /** Defaults to the `[slug]` route param. */\n readonly slug?: string;\n /** Defaults to navigating back to the list. */\n readonly onSaved?: () => void;\n readonly onDeleted?: () => void;\n /**\n * Where to autosave the edit. Supplying it is the whole opt-in: the form\n * seeds from the persisted draft, writes to it on every edit, and the page\n * clears it once a save or delete commits.\n *\n * A route host omits it and stays ephemeral, which is the rule stated as a\n * missing prop rather than as a flag — there is no value of \"absent\" that\n * accidentally starts persisting.\n */\n readonly draft?: EntityDraftStore;\n}\n\n/**\n * What the factory returns: a **named descriptor**, not four loose components.\n *\n * The identity fields are here so the workspace registry and the nav are derived\n * from a list of these rather than from the hand-written const maps they replace.\n */\nexport interface EntityCrud<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n /** `@entity({ key })`, which is also `catalogKey` and the tab address payload. */\n readonly entityKey: EntityCatalogKey;\n /**\n * `@entity({ labelKey })` — how one record is named. A record tab's title.\n *\n * Read off the decorator rather than passed, so the tab strip, the nav and the\n * search results all name the entity from the one place it names itself.\n */\n readonly entityLabelKey: string;\n /** `@entity({ pluralKey })` — how the collection is named. A list tab's title. */\n readonly entityPluralKey: string;\n readonly basePath: string;\n readonly ListPage: () => ReactElement;\n readonly SingleViewPage: (props?: EntityCrudSingleViewProps) => ReactElement;\n}\n\n/**\n * A picker's transport with its context tags erased.\n *\n * The factory cannot preserve one type parameter per link — the pages that\n * build these know their adapters, the generated form only forwards them — and\n * `EntityForm.linkSources` is already `Record<string, EntityLinkSource<any>>`\n * for the same reason.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyEntityLinkSourceConfig = EntityLinkSourceConfig<Entity, any>;\n\n/**\n * One picker, resolved: the descriptor computed once at factory time, and the\n * use-cases plus adapter context the page builds per render.\n */\nexport interface EntityCrudLinkSource {\n readonly field: string;\n readonly descriptor: EntityFieldDescriptor;\n readonly config: AnyEntityLinkSourceConfig;\n}\n"],"names":[],"mappings":"AA4SA;;;CAGC,GACD,WAIC"}
|
|
@@ -19,7 +19,7 @@ export declare const sessionToken: () => Promise<string | undefined>;
|
|
|
19
19
|
* same way — the per-backend proxy, the auth shell's hand-written handlers, and
|
|
20
20
|
* the record search fan-out — and none of them grants anything by doing so. They
|
|
21
21
|
* only carry; the service still verifies the token and applies its own
|
|
22
|
-
* `
|
|
22
|
+
* the endpoint's `guard`.
|
|
23
23
|
*/
|
|
24
24
|
export declare const bearerHeader: (token: string | undefined) => Record<string, string>;
|
|
25
25
|
//# sourceMappingURL=bearer.d.ts.map
|
|
@@ -23,7 +23,7 @@ import { cookies } from 'next/headers';
|
|
|
23
23
|
* same way — the per-backend proxy, the auth shell's hand-written handlers, and
|
|
24
24
|
* the record search fan-out — and none of them grants anything by doing so. They
|
|
25
25
|
* only carry; the service still verifies the token and applies its own
|
|
26
|
-
* `
|
|
26
|
+
* the endpoint's `guard`.
|
|
27
27
|
*/ export const bearerHeader = (token)=>token === undefined ? {} : {
|
|
28
28
|
Authorization: `Bearer ${token}`
|
|
29
29
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/session/bearer.ts"],"sourcesContent":["import { ACCESS_COOKIE } from '@entifix/core';\nimport { cookies } from 'next/headers';\n\n/**\n * The caller's access token, or `undefined` when they hold no session.\n *\n * `entifix_at` is httpOnly, so only the server can read it — which is the whole\n * reason a browser talks to a backend through this app's own origin rather than\n * calling `:310N` directly.\n */\nexport const sessionToken = async (): Promise<string | undefined> =>\n (await cookies()).get(ACCESS_COOKIE)?.value;\n\n/**\n * The token as a forwardable header, and `{}` when there is none.\n *\n * The empty case is the point: a header of `Bearer undefined` is not \"no\n * credential\", it is a malformed one, and a service that answers `401` to both\n * hides the difference right up until one of them starts answering something\n * else. Omitting the header lets the upstream apply its own rule for an\n * anonymous caller — which for `catalog-reference` reads is to allow it.\n *\n * This lives on its own because three server surfaces carry the same cookie the\n * same way — the per-backend proxy, the auth shell's hand-written handlers, and\n * the record search fan-out — and none of them grants anything by doing so. They\n * only carry; the service still verifies the token and applies its own\n * `
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/session/bearer.ts"],"sourcesContent":["import { ACCESS_COOKIE } from '@entifix/core';\nimport { cookies } from 'next/headers';\n\n/**\n * The caller's access token, or `undefined` when they hold no session.\n *\n * `entifix_at` is httpOnly, so only the server can read it — which is the whole\n * reason a browser talks to a backend through this app's own origin rather than\n * calling `:310N` directly.\n */\nexport const sessionToken = async (): Promise<string | undefined> =>\n (await cookies()).get(ACCESS_COOKIE)?.value;\n\n/**\n * The token as a forwardable header, and `{}` when there is none.\n *\n * The empty case is the point: a header of `Bearer undefined` is not \"no\n * credential\", it is a malformed one, and a service that answers `401` to both\n * hides the difference right up until one of them starts answering something\n * else. Omitting the header lets the upstream apply its own rule for an\n * anonymous caller — which for `catalog-reference` reads is to allow it.\n *\n * This lives on its own because three server surfaces carry the same cookie the\n * same way — the per-backend proxy, the auth shell's hand-written handlers, and\n * the record search fan-out — and none of them grants anything by doing so. They\n * only carry; the service still verifies the token and applies its own\n * the endpoint's `guard`.\n */\nexport const bearerHeader = (\n token: string | undefined,\n): Record<string, string> =>\n token === undefined ? {} : { Authorization: `Bearer ${token}` };\n"],"names":["ACCESS_COOKIE","cookies","sessionToken","get","value","bearerHeader","token","undefined","Authorization"],"mappings":"AAAA,SAASA,aAAa,QAAQ,gBAAgB;AAC9C,SAASC,OAAO,QAAQ,eAAe;AAEvC;;;;;;CAMC,GACD,OAAO,MAAMC,eAAe;QAC1B;YAAA,OAAA,AAAC,CAAA,MAAMD,SAAQ,EAAGE,GAAG,CAACH,mCAAtB,KAAsCI,KAAK;EAAC;AAE9C;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,eAAe,CAC1BC,QAEAA,UAAUC,YAAY,CAAC,IAAI;QAAEC,eAAe,CAAC,OAAO,EAAEF,OAAO;IAAC,EAAE"}
|
|
@@ -2,6 +2,7 @@ export * from './drafts-state.js';
|
|
|
2
2
|
export * from './entity-nav.js';
|
|
3
3
|
export * from './entity-tab-kind.js';
|
|
4
4
|
export * from './idb-state-storage.js';
|
|
5
|
+
export * from './pending-flows.js';
|
|
5
6
|
export * from './pending-state.js';
|
|
6
7
|
export * from './pending-transactions.js';
|
|
7
8
|
export * from './tab-kind.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/workspace/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,wBAAwB,CAAC;AACvC,cAAc,oBAAoB,CAAC;AACnC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/workspace/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,sBAAsB,CAAC;AACrC,cAAc,wBAAwB,CAAC;AACvC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC"}
|
|
@@ -2,6 +2,7 @@ export * from './drafts-state.js';
|
|
|
2
2
|
export * from './entity-nav.js';
|
|
3
3
|
export * from './entity-tab-kind.js';
|
|
4
4
|
export * from './idb-state-storage.js';
|
|
5
|
+
export * from './pending-flows.js';
|
|
5
6
|
export * from './pending-state.js';
|
|
6
7
|
export * from './pending-transactions.js';
|
|
7
8
|
export * from './tab-kind.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/workspace/index.ts"],"sourcesContent":["export * from './drafts-state.js';\nexport * from './entity-nav.js';\nexport * from './entity-tab-kind.js';\nexport * from './idb-state-storage.js';\nexport * from './pending-state.js';\nexport * from './pending-transactions.js';\nexport * from './tab-kind.js';\nexport * from './tab-state.js';\nexport * from './tabs-state.js';\nexport * from './use-entity-draft.js';\nexport * from './workspace-scope.js';\nexport * from './workspace-shell.js';\n"],"names":[],"mappings":"AAAA,cAAc,oBAAoB;AAClC,cAAc,kBAAkB;AAChC,cAAc,uBAAuB;AACrC,cAAc,yBAAyB;AACvC,cAAc,qBAAqB;AACnC,cAAc,4BAA4B;AAC1C,cAAc,gBAAgB;AAC9B,cAAc,iBAAiB;AAC/B,cAAc,kBAAkB;AAChC,cAAc,wBAAwB;AACtC,cAAc,uBAAuB;AACrC,cAAc,uBAAuB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/workspace/index.ts"],"sourcesContent":["export * from './drafts-state.js';\nexport * from './entity-nav.js';\nexport * from './entity-tab-kind.js';\nexport * from './idb-state-storage.js';\nexport * from './pending-flows.js';\nexport * from './pending-state.js';\nexport * from './pending-transactions.js';\nexport * from './tab-kind.js';\nexport * from './tab-state.js';\nexport * from './tabs-state.js';\nexport * from './use-entity-draft.js';\nexport * from './workspace-scope.js';\nexport * from './workspace-shell.js';\n"],"names":[],"mappings":"AAAA,cAAc,oBAAoB;AAClC,cAAc,kBAAkB;AAChC,cAAc,uBAAuB;AACrC,cAAc,yBAAyB;AACvC,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,4BAA4B;AAC1C,cAAc,gBAAgB;AAC9B,cAAc,iBAAiB;AAC/B,cAAc,kBAAkB;AAChC,cAAc,wBAAwB;AACtC,cAAc,uBAAuB;AACrC,cAAc,uBAAuB"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type FlowStatusRead, type PendingFlowStorage, type PushChannel } from '@entifix/react-integration';
|
|
2
|
+
import { type ReactNode } from 'react';
|
|
3
|
+
/**
|
|
4
|
+
* How long a pending flow nobody can account for is kept before it is
|
|
5
|
+
* dropped: no push arrived, and its status read answers nothing. Long enough
|
|
6
|
+
* for a flow that waits on a person, short enough that a lost one does not
|
|
7
|
+
* hold a form open across a working day.
|
|
8
|
+
*/
|
|
9
|
+
export declare const PENDING_FLOW_MAX_AGE_MS: number;
|
|
10
|
+
export interface PendingFlowsProviderProps {
|
|
11
|
+
/**
|
|
12
|
+
* Whose pending flows these are — `workspaceScopeKey({ userId,
|
|
13
|
+
* organizationId })`, or `ANONYMOUS_WORKSPACE_SCOPE` for nobody in
|
|
14
|
+
* particular, which keeps flow ids and their age only.
|
|
15
|
+
*
|
|
16
|
+
* Required for the reason `PendingTransactionsProviderProps.scope` is:
|
|
17
|
+
* IndexedDB belongs to the browser profile, not to whoever signed in.
|
|
18
|
+
*/
|
|
19
|
+
readonly scope: string;
|
|
20
|
+
/** The tab's push channel, where each pending flow's outcome arrives. */
|
|
21
|
+
readonly channel: PushChannel;
|
|
22
|
+
/**
|
|
23
|
+
* Reads a flow's status link when its push may have been missed —
|
|
24
|
+
* `buildFlowStatusReader()` over REST. Omitted, a flow settles by push
|
|
25
|
+
* alone, and one whose push was missed is dropped at the age bound.
|
|
26
|
+
*/
|
|
27
|
+
readonly readStatus?: FlowStatusRead;
|
|
28
|
+
readonly maxAgeMs?: number;
|
|
29
|
+
/** Defaults to IndexedDB, so a pending write survives a reload. */
|
|
30
|
+
readonly storage?: PendingFlowStorage;
|
|
31
|
+
readonly children: ReactNode;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Waits on every write this browser handed to a flow, and tells the operator
|
|
35
|
+
* once when one fails
|
|
36
|
+
* ([ADR 0022](../../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
|
|
37
|
+
*
|
|
38
|
+
* It holds the pending-flow store the generated CRUD records into, persisted
|
|
39
|
+
* per principal, and settles each flow from its push or from a status read
|
|
40
|
+
* after a reconnect. A failed flow is shown through the host's
|
|
41
|
+
* `ToastRegion`, translated, exactly once — however many tabs or
|
|
42
|
+
* redeliveries report it.
|
|
43
|
+
*
|
|
44
|
+
* ⚠️ **Mount it inside a `ToastProvider`, and above the plain routes**, not
|
|
45
|
+
* only the workspace: a create is `/<basePath>/new` on the route host.
|
|
46
|
+
*/
|
|
47
|
+
export declare function PendingFlowsProvider({ scope, channel, readStatus, maxAgeMs, storage, children, }: PendingFlowsProviderProps): import("react").JSX.Element;
|
|
48
|
+
//# sourceMappingURL=pending-flows.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pending-flows.d.ts","sourceRoot":"","sources":["../../../src/lib/workspace/pending-flows.tsx"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,cAAc,EAEnB,KAAK,kBAAkB,EAEvB,KAAK,WAAW,EAEjB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,KAAK,SAAS,EAAW,MAAM,OAAO,CAAC;AAKhD;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,QAAiB,CAAC;AAQtD,MAAM,WAAW,yBAAyB;IACxC;;;;;;;OAOG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,yEAAyE;IACzE,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAC9B;;;;OAIG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC;IACrC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,mEAAmE;IACnE,QAAQ,CAAC,OAAO,CAAC,EAAE,kBAAkB,CAAC;IACtC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC;CAC9B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,KAAK,EACL,OAAO,EACP,UAAU,EACV,QAAkC,EAClC,OAA4B,EAC5B,QAAQ,GACT,EAAE,yBAAyB,+BAmC3B"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
3
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
4
|
+
import { useToasts } from '@entifix/react-controls';
|
|
5
|
+
import { makePendingFlowStore, PendingFlowStoreProvider, usePendingFlowSettlement } from '@entifix/react-integration';
|
|
6
|
+
import { useMemo } from 'react';
|
|
7
|
+
import { makeIndexedDbStateStorage } from './idb-state-storage.js';
|
|
8
|
+
import { ANONYMOUS_WORKSPACE_SCOPE } from './workspace-scope.js';
|
|
9
|
+
/**
|
|
10
|
+
* How long a pending flow nobody can account for is kept before it is
|
|
11
|
+
* dropped: no push arrived, and its status read answers nothing. Long enough
|
|
12
|
+
* for a flow that waits on a person, short enough that a lost one does not
|
|
13
|
+
* hold a form open across a working day.
|
|
14
|
+
*/ export const PENDING_FLOW_MAX_AGE_MS = 30 * 60 * 1000;
|
|
15
|
+
// Module scope: a storage per render would reopen the database each time.
|
|
16
|
+
const pendingFlowStorage = makeIndexedDbStateStorage('entifix-pending-flows', 'flows');
|
|
17
|
+
/**
|
|
18
|
+
* Waits on every write this browser handed to a flow, and tells the operator
|
|
19
|
+
* once when one fails
|
|
20
|
+
* ([ADR 0022](../../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
|
|
21
|
+
*
|
|
22
|
+
* It holds the pending-flow store the generated CRUD records into, persisted
|
|
23
|
+
* per principal, and settles each flow from its push or from a status read
|
|
24
|
+
* after a reconnect. A failed flow is shown through the host's
|
|
25
|
+
* `ToastRegion`, translated, exactly once — however many tabs or
|
|
26
|
+
* redeliveries report it.
|
|
27
|
+
*
|
|
28
|
+
* ⚠️ **Mount it inside a `ToastProvider`, and above the plain routes**, not
|
|
29
|
+
* only the workspace: a create is `/<basePath>/new` on the route host.
|
|
30
|
+
*/ export function PendingFlowsProvider({ scope, channel, readStatus, maxAgeMs = PENDING_FLOW_MAX_AGE_MS, storage = pendingFlowStorage, children }) {
|
|
31
|
+
const toasts = useToasts();
|
|
32
|
+
// A store per principal: a sign-in under another scope must never read the
|
|
33
|
+
// previous one's pending writes.
|
|
34
|
+
const store = useMemo(()=>makePendingFlowStore({
|
|
35
|
+
storage,
|
|
36
|
+
key: `pending-flows:${scope}`,
|
|
37
|
+
anonymous: scope === ANONYMOUS_WORKSPACE_SCOPE
|
|
38
|
+
}), [
|
|
39
|
+
scope,
|
|
40
|
+
storage
|
|
41
|
+
]);
|
|
42
|
+
usePendingFlowSettlement(_extends({
|
|
43
|
+
channel,
|
|
44
|
+
store,
|
|
45
|
+
maxAgeMs
|
|
46
|
+
}, readStatus === undefined ? {} : {
|
|
47
|
+
readStatus
|
|
48
|
+
}, {
|
|
49
|
+
onFailure: (failure)=>{
|
|
50
|
+
toasts == null ? void 0 : toasts.showFailure(failure);
|
|
51
|
+
}
|
|
52
|
+
}));
|
|
53
|
+
if (toasts === undefined) throw new Error('PendingFlowsProvider must sit inside a ToastProvider: a failed flow has nowhere else to be shown');
|
|
54
|
+
return /*#__PURE__*/ _jsx(PendingFlowStoreProvider, {
|
|
55
|
+
store: store,
|
|
56
|
+
children: children
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=pending-flows.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/workspace/pending-flows.tsx"],"sourcesContent":["'use client';\n\nimport { useToasts } from '@entifix/react-controls';\nimport {\n type FlowStatusRead,\n makePendingFlowStore,\n type PendingFlowStorage,\n PendingFlowStoreProvider,\n type PushChannel,\n usePendingFlowSettlement,\n} from '@entifix/react-integration';\nimport { type ReactNode, useMemo } from 'react';\n\nimport { makeIndexedDbStateStorage } from './idb-state-storage.js';\nimport { ANONYMOUS_WORKSPACE_SCOPE } from './workspace-scope.js';\n\n/**\n * How long a pending flow nobody can account for is kept before it is\n * dropped: no push arrived, and its status read answers nothing. Long enough\n * for a flow that waits on a person, short enough that a lost one does not\n * hold a form open across a working day.\n */\nexport const PENDING_FLOW_MAX_AGE_MS = 30 * 60 * 1000;\n\n// Module scope: a storage per render would reopen the database each time.\nconst pendingFlowStorage = makeIndexedDbStateStorage(\n 'entifix-pending-flows',\n 'flows',\n);\n\nexport interface PendingFlowsProviderProps {\n /**\n * Whose pending flows these are — `workspaceScopeKey({ userId,\n * organizationId })`, or `ANONYMOUS_WORKSPACE_SCOPE` for nobody in\n * particular, which keeps flow ids and their age only.\n *\n * Required for the reason `PendingTransactionsProviderProps.scope` is:\n * IndexedDB belongs to the browser profile, not to whoever signed in.\n */\n readonly scope: string;\n /** The tab's push channel, where each pending flow's outcome arrives. */\n readonly channel: PushChannel;\n /**\n * Reads a flow's status link when its push may have been missed —\n * `buildFlowStatusReader()` over REST. Omitted, a flow settles by push\n * alone, and one whose push was missed is dropped at the age bound.\n */\n readonly readStatus?: FlowStatusRead;\n readonly maxAgeMs?: number;\n /** Defaults to IndexedDB, so a pending write survives a reload. */\n readonly storage?: PendingFlowStorage;\n readonly children: ReactNode;\n}\n\n/**\n * Waits on every write this browser handed to a flow, and tells the operator\n * once when one fails\n * ([ADR 0022](../../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).\n *\n * It holds the pending-flow store the generated CRUD records into, persisted\n * per principal, and settles each flow from its push or from a status read\n * after a reconnect. A failed flow is shown through the host's\n * `ToastRegion`, translated, exactly once — however many tabs or\n * redeliveries report it.\n *\n * ⚠️ **Mount it inside a `ToastProvider`, and above the plain routes**, not\n * only the workspace: a create is `/<basePath>/new` on the route host.\n */\nexport function PendingFlowsProvider({\n scope,\n channel,\n readStatus,\n maxAgeMs = PENDING_FLOW_MAX_AGE_MS,\n storage = pendingFlowStorage,\n children,\n}: PendingFlowsProviderProps) {\n const toasts = useToasts();\n\n // A store per principal: a sign-in under another scope must never read the\n // previous one's pending writes.\n const store = useMemo(\n () =>\n makePendingFlowStore({\n storage,\n key: `pending-flows:${scope}`,\n anonymous: scope === ANONYMOUS_WORKSPACE_SCOPE,\n }),\n [scope, storage],\n );\n\n usePendingFlowSettlement({\n channel,\n store,\n maxAgeMs,\n ...(readStatus === undefined ? {} : { readStatus }),\n onFailure: failure => {\n toasts?.showFailure(failure);\n },\n });\n\n if (toasts === undefined)\n throw new Error(\n 'PendingFlowsProvider must sit inside a ToastProvider: a failed flow has nowhere else to be shown',\n );\n\n return (\n <PendingFlowStoreProvider store={store}>\n {children}\n </PendingFlowStoreProvider>\n );\n}\n"],"names":["useToasts","makePendingFlowStore","PendingFlowStoreProvider","usePendingFlowSettlement","useMemo","makeIndexedDbStateStorage","ANONYMOUS_WORKSPACE_SCOPE","PENDING_FLOW_MAX_AGE_MS","pendingFlowStorage","PendingFlowsProvider","scope","channel","readStatus","maxAgeMs","storage","children","toasts","store","key","anonymous","undefined","onFailure","failure","showFailure","Error"],"mappings":"AAAA;;;AAEA,SAASA,SAAS,QAAQ,0BAA0B;AACpD,SAEEC,oBAAoB,EAEpBC,wBAAwB,EAExBC,wBAAwB,QACnB,6BAA6B;AACpC,SAAyBC,OAAO,QAAQ,QAAQ;AAEhD,SAASC,yBAAyB,QAAQ,yBAAyB;AACnE,SAASC,yBAAyB,QAAQ,uBAAuB;AAEjE;;;;;CAKC,GACD,OAAO,MAAMC,0BAA0B,KAAK,KAAK,KAAK;AAEtD,0EAA0E;AAC1E,MAAMC,qBAAqBH,0BACzB,yBACA;AA2BF;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASI,qBAAqB,EACnCC,KAAK,EACLC,OAAO,EACPC,UAAU,EACVC,WAAWN,uBAAuB,EAClCO,UAAUN,kBAAkB,EAC5BO,QAAQ,EACkB;IAC1B,MAAMC,SAAShB;IAEf,2EAA2E;IAC3E,iCAAiC;IACjC,MAAMiB,QAAQb,QACZ,IACEH,qBAAqB;YACnBa;YACAI,KAAK,CAAC,cAAc,EAAER,OAAO;YAC7BS,WAAWT,UAAUJ;QACvB,IACF;QAACI;QAAOI;KAAQ;IAGlBX,yBAAyB;QACvBQ;QACAM;QACAJ;OACID,eAAeQ,YAAY,CAAC,IAAI;QAAER;IAAW;QACjDS,WAAWC,CAAAA;YACTN,0BAAAA,OAAQO,WAAW,CAACD;QACtB;;IAGF,IAAIN,WAAWI,WACb,MAAM,IAAII,MACR;IAGJ,qBACE,KAACtB;QAAyBe,OAAOA;kBAC9BF;;AAGP"}
|
package/package.json
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
|
-
"version": "0.
|
|
24
|
+
"version": "0.14.0",
|
|
25
25
|
"description": "Next.js application shell: back-office chrome, workspace tabs, CRUD screens derived from entity metadata, and session and proxy routes.",
|
|
26
26
|
"license": "MIT",
|
|
27
27
|
"repository": {
|
|
@@ -51,23 +51,23 @@
|
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@tanstack/react-query": "^5.105.1",
|
|
54
|
-
"effect": "4.0.
|
|
54
|
+
"effect": "4.0.7",
|
|
55
55
|
"i18next": "26.6.0",
|
|
56
56
|
"next": "16.4.3",
|
|
57
57
|
"react": "19.3.1",
|
|
58
58
|
"react-dom": "19.3.1",
|
|
59
59
|
"zustand": "^5.0.16",
|
|
60
|
-
"@entifix/testing-unit": "0.
|
|
60
|
+
"@entifix/testing-unit": "0.14.0"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
63
|
"idb": "^8.0.4",
|
|
64
|
-
"@entifix/authz": "0.
|
|
65
|
-
"@entifix/business": "0.
|
|
66
|
-
"@entifix/
|
|
67
|
-
"@entifix/react-controls": "0.
|
|
68
|
-
"@entifix/
|
|
69
|
-
"@entifix/react-integration": "0.
|
|
70
|
-
"@entifix/transactions": "0.
|
|
64
|
+
"@entifix/authz": "0.14.0",
|
|
65
|
+
"@entifix/business": "0.14.0",
|
|
66
|
+
"@entifix/i18n": "0.14.0",
|
|
67
|
+
"@entifix/react-controls": "0.14.0",
|
|
68
|
+
"@entifix/core": "0.14.0",
|
|
69
|
+
"@entifix/react-integration": "0.14.0",
|
|
70
|
+
"@entifix/transactions": "0.14.0"
|
|
71
71
|
},
|
|
72
72
|
"files": [
|
|
73
73
|
"dist",
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
],
|
|
77
77
|
"peerDependencies": {
|
|
78
78
|
"@tanstack/react-query": ">=5.101 <6",
|
|
79
|
-
"effect": "^4.0.
|
|
79
|
+
"effect": "^4.0.7",
|
|
80
80
|
"i18next": ">=26 <27",
|
|
81
81
|
"next": ">=16 <17",
|
|
82
82
|
"react": ">=19 <20",
|