@cosmicdrift/kumiko-framework 0.415.0 → 0.417.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/agents/api/framework-engine.md +67 -13
  2. package/agents/api/framework-ui-types.md +81 -7
  3. package/agents/api/renderer-web.md +31 -3
  4. package/agents/api/types.md +114 -61
  5. package/agents/api.md +1 -1
  6. package/agents/boot-rules.md +36 -4
  7. package/agents/examples/dashboard-stats.md +51 -0
  8. package/agents/examples/embedded.md +24 -1
  9. package/agents/examples/event-sourcing.md +84 -0
  10. package/agents/examples/handbook-knowledge.md +129 -0
  11. package/agents/examples/list-table-options.md +71 -5
  12. package/agents/examples/managed-config.md +9 -1
  13. package/agents/examples/record-detail-layout.md +71 -6
  14. package/agents/examples/secrets-demo.md +3 -1
  15. package/agents/examples/signature.md +187 -0
  16. package/agents/examples/writeform-section.md +330 -0
  17. package/agents/examples.md +2 -0
  18. package/agents/features-index.md +4 -0
  19. package/agents/features.md +14 -0
  20. package/dist/api/server-routes.js +2 -0
  21. package/dist/db/queries/event-store.d.ts +3 -0
  22. package/dist/db/queries/event-store.js +12 -0
  23. package/dist/db/table-builder.js +3 -1
  24. package/dist/engine/boot-validator/boot-phases.js +5 -0
  25. package/dist/engine/boot-validator/boot-rules.d.ts +140 -5
  26. package/dist/engine/boot-validator/card-meta-overflow.js +5 -1
  27. package/dist/engine/boot-validator/cross-tenant-file-read.d.ts +3 -0
  28. package/dist/engine/boot-validator/cross-tenant-file-read.js +19 -0
  29. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +10 -0
  30. package/dist/engine/boot-validator/entity-declaration-rules.js +10 -0
  31. package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +16 -1
  32. package/dist/engine/boot-validator/list-row-guidance-rules.js +16 -1
  33. package/dist/engine/boot-validator/list-row-guidance.d.ts +8 -0
  34. package/dist/engine/boot-validator/list-row-guidance.js +31 -0
  35. package/dist/engine/boot-validator/list-table-options.d.ts +1 -1
  36. package/dist/engine/boot-validator/list-table-options.js +8 -6
  37. package/dist/engine/boot-validator/list-table-rules.d.ts +1 -1
  38. package/dist/engine/boot-validator/list-table-rules.js +1 -1
  39. package/dist/engine/boot-validator/query-output-columns.js +22 -0
  40. package/dist/engine/boot-validator/query-output-guidance.js +3 -0
  41. package/dist/engine/boot-validator/query-refs.js +4 -1
  42. package/dist/engine/boot-validator/relative-time-format.d.ts +1 -0
  43. package/dist/engine/boot-validator/relative-time-format.js +51 -0
  44. package/dist/engine/boot-validator/screens-actions-rules.d.ts +16 -1
  45. package/dist/engine/boot-validator/screens-actions-rules.js +16 -1
  46. package/dist/engine/boot-validator/screens-actions.d.ts +1 -1
  47. package/dist/engine/boot-validator/screens-actions.js +57 -15
  48. package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +2 -1
  49. package/dist/engine/boot-validator/screens-dashboard-narrow.js +43 -4
  50. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +12 -2
  51. package/dist/engine/boot-validator/screens-dashboard-rules.js +12 -2
  52. package/dist/engine/boot-validator/screens-dashboard.js +2 -1
  53. package/dist/engine/boot-validator/screens-forms-layout-rules.d.ts +5 -0
  54. package/dist/engine/boot-validator/screens-forms-layout-rules.js +5 -0
  55. package/dist/engine/boot-validator/screens-forms-rules.d.ts +60 -0
  56. package/dist/engine/boot-validator/screens-forms-rules.js +60 -0
  57. package/dist/engine/boot-validator/screens-forms.d.ts +1 -1
  58. package/dist/engine/boot-validator/screens-forms.js +108 -2
  59. package/dist/engine/boot-validator/screens-kind-config-edit.js +1 -0
  60. package/dist/engine/boot-validator/screens-kind-entity-list.js +3 -1
  61. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +15 -0
  62. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +15 -0
  63. package/dist/engine/boot-validator/screens-kind-projection-detail.js +110 -0
  64. package/dist/engine/boot-validator/screens-kind-projection-list.js +1 -1
  65. package/dist/engine/boot-validator/screens-lists-rules.d.ts +5 -0
  66. package/dist/engine/boot-validator/screens-lists-rules.js +5 -0
  67. package/dist/engine/boot-validator/screens-lists.js +4 -1
  68. package/dist/engine/boot-validator/screens.js +1 -2
  69. package/dist/engine/bridge-stub.js +1 -0
  70. package/dist/engine/build-config-feature-schema.js +29 -36
  71. package/dist/engine/config-access-rules.d.ts +3 -0
  72. package/dist/engine/config-access-rules.js +34 -0
  73. package/dist/engine/factories.d.ts +2 -0
  74. package/dist/engine/project-app-schema-for-roles.js +2 -0
  75. package/dist/engine/screen-helpers.js +7 -3
  76. package/dist/event-store/archive.d.ts +1 -0
  77. package/dist/event-store/archive.js +5 -1
  78. package/dist/event-store/event-store.d.ts +5 -0
  79. package/dist/event-store/event-store.js +23 -3
  80. package/dist/files/file-routes.d.ts +2 -0
  81. package/dist/files/file-routes.js +85 -22
  82. package/dist/files/foreign-tenant-file-read.d.ts +13 -0
  83. package/dist/files/foreign-tenant-file-read.js +64 -0
  84. package/dist/i18n/required-surface-keys.js +32 -6
  85. package/dist/pipeline/handler-context-events.js +15 -1
  86. package/dist/ui-types/card-column-roles.d.ts +3 -0
  87. package/dist/ui-types/card-column-roles.js +9 -5
  88. package/dist/ui-types/index.d.ts +1 -1
  89. package/package.json +3 -3
  90. package/src/changes.json +48 -0
@@ -32,11 +32,15 @@ export function resolveNavParentScreen(screens, detail, getId) {
32
32
  ? screens.find((s) => screenShortId(getId(s)) === screenShortId(explicitId))
33
33
  : undefined;
34
34
  })();
35
- // rowActions, toolbarActions, and drawer-kind actions (which mount inline
36
- // and have no page of their own) all count as "reached from" this list.
35
+ // rowActions, toolbarActions, the `actions` of a record screen, and drawer-kind actions (which
36
+ // mount inline and have no page of their own) all count as "reached from" that screen.
37
37
  const navigatesToDetail = (actions) => (actions ?? []).some((a) => (a.kind === "navigate" || a.kind === "drawer") &&
38
38
  a.screen !== undefined &&
39
39
  screenShortId(a.screen) === detailScreenId);
40
+ // A form opened only from a record screen (e.g. a status dialog) has that record as its parent.
41
+ const recordFromAction = screens.find((s) => (s.type === "projectionDetail" || s.type === "entityEdit") &&
42
+ screenShortId(getId(s)) !== detailScreenId &&
43
+ navigatesToDetail(s.actions));
40
44
  // The create button of an entityList navigates to its createScreen, so the
41
45
  // list is that screen's parent just like for a rowAction target.
42
46
  const listFromRowAction = screens.find((s) => {
@@ -51,7 +55,7 @@ export function resolveNavParentScreen(screens, detail, getId) {
51
55
  const listFromEntity = detail.type === "entityEdit"
52
56
  ? screens.find((s) => s.type === "entityList" && s.entity === detail.entity)
53
57
  : undefined;
54
- return listFromExplicit ?? listFromRowAction ?? listFromEntity;
58
+ return listFromExplicit ?? listFromRowAction ?? recordFromAction ?? listFromEntity;
55
59
  }
56
60
  // Shared by boot-validators that walk the EditLayout shape (entityEdit's
57
61
  // layout, reused verbatim by projectionDetail/actionForm/configEdit/secretMint).
@@ -11,4 +11,5 @@ export type ArchiveStreamArgs = {
11
11
  };
12
12
  export declare function archiveStream(db: DbRunner, args: ArchiveStreamArgs): Promise<void>;
13
13
  export declare function isStreamArchived(db: DbRunner, tenantId: TenantId, aggregateId: string): Promise<boolean>;
14
+ export declare function selectArchivedAggregateIds(db: DbRunner, tenantId: TenantId, aggregateIds: readonly string[]): Promise<ReadonlySet<string>>;
14
15
  export declare function restoreStream(db: DbRunner, tenantId: TenantId, aggregateId: string): Promise<void>;
@@ -1,6 +1,6 @@
1
1
  // sql now comes from native dialect
2
2
  import { instant, table as pgTable, sql, text, uniqueIndex, uuid } from "../db/dialect.js";
3
- import { upsertArchivedStream } from "../db/queries/event-store.js";
3
+ import { selectArchivedAggregateIdsOf, upsertArchivedStream } from "../db/queries/event-store.js";
4
4
  import { deleteMany, fetchOne } from "../db/query.js";
5
5
  import { tableExists } from "../db/schema-inspection.js";
6
6
  import { ensureTableRowLevelSecurity, unsafePushTables } from "../db/table-push.js";
@@ -48,6 +48,10 @@ export async function isStreamArchived(db, tenantId, aggregateId) {
48
48
  const row = await fetchOne(db, archivedStreamsTable, { tenantId, aggregateId });
49
49
  return row !== undefined;
50
50
  }
51
+ // One query for a whole page of aggregates instead of one isStreamArchived probe each.
52
+ export async function selectArchivedAggregateIds(db, tenantId, aggregateIds) {
53
+ return new Set(await selectArchivedAggregateIdsOf(db, tenantId, aggregateIds));
54
+ }
51
55
  // Undo an archive — restores the stream to writable state. Ops tool. The
52
56
  // historical archivedAt is lost; if auditing needs the archive-history,
53
57
  // use domain events on the aggregate (e.g. "stream.archived" / "stream.
@@ -21,6 +21,11 @@ export declare function loadAggregate(db: DbRunner, aggregateId: string, tenantI
21
21
  readonly aggregateType?: string;
22
22
  readonly atVersion?: number;
23
23
  }): Promise<readonly StoredEvent[]>;
24
+ export declare function loadEventsOfAggregatesByType(db: DbRunner, tenantId: TenantId, args: {
25
+ readonly aggregateIds: readonly string[];
26
+ readonly eventTypes: readonly string[];
27
+ readonly includeArchived?: boolean;
28
+ }): Promise<readonly StoredEvent[]>;
24
29
  export declare function loadAggregateForWriting(db: DbRunner, aggregateId: string, tenantId: TenantId, options: {
25
30
  readonly aggregateType: string;
26
31
  }): Promise<{
@@ -5,9 +5,10 @@ import { requestContext } from "../api/request-context.js";
5
5
  import { encryptEventPayloadPii } from "../crypto/event-pii.js";
6
6
  import { instantToTimestamptzParam } from "../db/driver-value-preparation.js";
7
7
  import { constraintOf, isUniqueViolation } from "../db/pg-error.js";
8
- import { claimXactId, insertFirstEventRow, insertSubsequentEventRow, notifyPgChannel, runAtomicEventWrite, selectAggregateMaxVersion, selectEventsHighWaterMark, selectStreamMaxVersion, selectStreamMaxVersions, } from "../db/queries/event-store.js";
9
- import { selectMany } from "../db/query.js";
10
- import { isStreamArchived } from "./archive.js";
8
+ import { claimXactId, insertFirstEventRow, insertSubsequentEventRow, notifyPgChannel, runAtomicEventWrite, selectAggregateMaxVersion, selectEventRowsOfAggregatesByType, selectEventsHighWaterMark, selectStreamMaxVersion, selectStreamMaxVersions, } from "../db/queries/event-store.js";
9
+ import { coerceRow, selectMany } from "../db/query.js";
10
+ import { extractTableInfo } from "../db/table-info.js";
11
+ import { isStreamArchived, selectArchivedAggregateIds } from "./archive.js";
11
12
  import { IdempotentAppendConflictError, SeedTimeOrderError, VersionConflictError, } from "./errors.js";
12
13
  import { eventsTable } from "./events-schema.js";
13
14
  import { toStoredEvent } from "./row-to-stored-event.js";
@@ -224,6 +225,25 @@ export async function loadAggregate(db, aggregateId, tenantId, options) {
224
225
  return rows.map(toStoredEvent);
225
226
  });
226
227
  }
228
+ // Events of several aggregates filtered by event type in one query, so a list page does not
229
+ // load every stream (N+1). Ordered by the global id: within one aggregate that is version order.
230
+ // Archived streams are left out unless includeArchived, as in loadAggregate.
231
+ export async function loadEventsOfAggregatesByType(db, tenantId, args) {
232
+ const { aggregateIds, eventTypes, includeArchived } = args;
233
+ if (aggregateIds.length === 0 || eventTypes.length === 0)
234
+ return [];
235
+ return inEventStreamScope(tenantId, async () => {
236
+ const archivedIds = includeArchived
237
+ ? new Set()
238
+ : await selectArchivedAggregateIds(db, tenantId, aggregateIds);
239
+ const rawRows = await selectEventRowsOfAggregatesByType(db, tenantId, aggregateIds, eventTypes);
240
+ const info = extractTableInfo(eventsTable);
241
+ return rawRows
242
+ .map((raw) => coerceRow(raw, info))
243
+ .filter((row) => !archivedIds.has(row.aggregateId))
244
+ .map(toStoredEvent);
245
+ });
246
+ }
227
247
  // Events and the stream's latest version from ONE read, so both come from the same
228
248
  // snapshot: a commit landing between two separate statements would leave the caller
229
249
  // pinning a version its loaded events never covered. The aggregateType filter is applied
@@ -4,6 +4,7 @@ import { Hono } from "hono";
4
4
  import { type ClientIpResolver } from "../api/client-ip.ts";
5
5
  import type { DbConnection } from "../db/connection.ts";
6
6
  import { type Registry, type SessionUser, type TenantId } from "../engine/types/index.ts";
7
+ import { type ForeignTenantFileReadCheck } from "./foreign-tenant-file-read.ts";
7
8
  import type { FileProviderResolver } from "./provider-resolver.ts";
8
9
  import type { RecordReadCheck } from "./record-read-check.ts";
9
10
  import { type RecordWriteCheck } from "./record-write-check.ts";
@@ -41,6 +42,7 @@ export type FileRoutesOptions = {
41
42
  readonly unclaimedUploadReaders?: readonly string[];
42
43
  readonly accessGuard?: FileAccessGuard;
43
44
  readonly canReadRecord?: RecordReadCheck;
45
+ readonly canReadForeignTenantFile?: ForeignTenantFileReadCheck;
44
46
  readonly canWriteRecord?: RecordWriteCheck;
45
47
  };
46
48
  export declare const ANONYMOUS_UPLOADS_PER_WINDOW = 20;
@@ -25,6 +25,7 @@ import { isFileSubField } from "./file-field-slots.js";
25
25
  import { createFileContext, createTenantFileContext } from "./file-handle.js";
26
26
  import { fileRefEntity } from "./file-ref-entity.js";
27
27
  import { fileRefsTable } from "./file-ref-table.js";
28
+ import { collectCrossTenantFileReadQueries, foreignTenantFileReadDb, } from "./foreign-tenant-file-read.js";
28
29
  import { collectRecordOnlyFileEntityTypes } from "./record-only-file-entity-types.js";
29
30
  import { isStoredRecordLocked, RecordWriteDecisions, } from "./record-write-check.js";
30
31
  import { neutralFileNameForMimeType } from "./resolve-content-type.js";
@@ -117,6 +118,10 @@ export function createFileRoutes(options) {
117
118
  // Anonymous visitors share one user id and own no file by it; the check precedes an app's
118
119
  // accessGuard so a custom guard cannot reopen reads or deletes between visitors.
119
120
  const guard = (args) => isAnonymousSessionUser(args.user) ? "deny" : configuredGuard(args);
121
+ const crossTenantFileReadQueries = options.registry
122
+ ? collectCrossTenantFileReadQueries(options.registry)
123
+ : new Map();
124
+ const canReadForeignTenantFile = crossTenantFileReadQueries.size > 0 ? options.canReadForeignTenantFile : undefined;
120
125
  const executor = getFileRefExecutor();
121
126
  const piiSubjectFields = collectPiiSubjectFields(fileRefEntity);
122
127
  const api = new Hono();
@@ -365,10 +370,11 @@ export function createFileRoutes(options) {
365
370
  api.get("/files/:id", async (c) => {
366
371
  const user = getUser(c);
367
372
  const id = c.req.param("id");
368
- const fileRef = await loadReadableFileRef(id, user);
369
- if (!fileRef)
373
+ const readable = await loadReadableFile(id, user);
374
+ if (!readable)
370
375
  return c.json({ error: "not_found" }, 404);
371
- const decision = await guard({ fileRef, user, operation: "read" });
376
+ const { fileRef } = readable;
377
+ const decision = await readDecisionFor(readable, user);
372
378
  if (decision === "deny") {
373
379
  // 404 rather than 403 so the existence of the file isn't confirmed to
374
380
  // an unauthorised caller — matches the tenant-miss response.
@@ -400,10 +406,11 @@ export function createFileRoutes(options) {
400
406
  const user = getUser(c);
401
407
  const id = c.req.param("id");
402
408
  const name = c.req.param("name");
403
- const fileRef = await loadFileForTenant(id, user.tenantId);
404
- if (!fileRef)
409
+ const readable = await loadOwnOrForeignFile(id, user);
410
+ if (!readable)
405
411
  return c.json({ error: "not_found" }, 404);
406
- const decision = await guard({ fileRef, user, operation: "read" });
412
+ const { fileRef } = readable;
413
+ const decision = await readDecisionFor(readable, user);
407
414
  if (decision === "deny")
408
415
  return c.json({ error: "not_found" }, 404);
409
416
  // An unknown name and a denied file answer alike, so the route never
@@ -425,12 +432,12 @@ export function createFileRoutes(options) {
425
432
  }
426
433
  // Built per request: createFileContext caches the resolved provider, so
427
434
  // one shared across requests would serve tenant A's store to tenant B.
428
- const files = createFileContext(() => options.resolveProvider(user.tenantId), user.tenantId);
435
+ const files = createFileContext(() => options.resolveProvider(fileRef.tenantId), fileRef.tenantId);
429
436
  const derivatives = createDerivativesContext({
430
437
  files,
431
438
  registry,
432
- db,
433
- tenantId: user.tenantId,
439
+ db: readable.foreign ? foreignTenantFileReadDb(db) : db,
440
+ tenantId: fileRef.tenantId,
434
441
  });
435
442
  const result = await derivatives.variant(id, spec, name);
436
443
  const data = await files.refFromFileRef(result).read();
@@ -493,10 +500,11 @@ export function createFileRoutes(options) {
493
500
  api.get("/files/:id/download-url", async (c) => {
494
501
  const user = getUser(c);
495
502
  const id = c.req.param("id");
496
- const fileRef = await loadReadableFileRef(id, user);
497
- if (!fileRef)
503
+ const readable = await loadReadableFile(id, user);
504
+ if (!readable)
498
505
  return c.json({ error: "not_found" }, 404);
499
- const decision = await guard({ fileRef, user, operation: "read" });
506
+ const { fileRef } = readable;
507
+ const decision = await readDecisionFor(readable, user);
500
508
  if (decision === "deny")
501
509
  return c.json({ error: "not_found" }, 404);
502
510
  // Resolve after access-check: tenant-scoped provider, and capability
@@ -538,8 +546,8 @@ export function createFileRoutes(options) {
538
546
  ? await executor.detail({ id }, user, tenantDbFor(SYSTEM_TENANT_ID))
539
547
  : null);
540
548
  if (!row)
541
- return null;
542
- const fileRef = row; // @cast-boundary db-row (decrypted via executor.detail)
549
+ return loadForeignFileMeta(id, user);
550
+ const fileRef = fileRefOfRow(row);
543
551
  // detail()'s "pass"-ownership read widens to tenantId IN (self, SYSTEM),
544
552
  // narrower in loadFileForTenant's selectMany. Restore that here so meta
545
553
  // doesn't leak reference-tenant rows.
@@ -549,6 +557,21 @@ export function createFileRoutes(options) {
549
557
  const decision = await guard({ fileRef, user, operation: "read" });
550
558
  if (decision === "deny")
551
559
  return null;
560
+ return metaOf(fileRef);
561
+ }
562
+ // The foreign file is located and authorized first; only then is it decrypted through detail()
563
+ // in the file's own tenant.
564
+ async function loadForeignFileMeta(id, user) {
565
+ const readable = await loadForeignFile(id, user);
566
+ if (!readable || (await readDecisionFor(readable, user)) === "deny")
567
+ return null;
568
+ const row = await executor.detail({ id }, user, tenantDbFor(readable.fileRef.tenantId));
569
+ return row ? metaOf(fileRefOfRow(row)) : null;
570
+ }
571
+ function fileRefOfRow(row) {
572
+ return row; // @cast-boundary db-row (file_refs rows, decrypted where read via executor.detail)
573
+ }
574
+ function metaOf(fileRef) {
552
575
  return {
553
576
  id: fileRef.id,
554
577
  fileName: fileRef.fileName,
@@ -563,14 +586,54 @@ export function createFileRoutes(options) {
563
586
  const meta = await loadReadableFileMeta(c.req.param("id"), getUser(c));
564
587
  return meta ? c.json(meta) : c.json({ error: "not_found" }, 404);
565
588
  });
566
- // Read-only crossing: SYSTEM_TENANT_ID files (e.g. helpdesk attachments) are
567
- // visible to a SystemAdmin whose session sits in another tenant. Delete,
568
- // variant and upload keep using loadFileForTenant and stay tenant-equal.
569
- async function loadReadableFileRef(id, user) {
589
+ // Read-only crossings: SYSTEM_TENANT_ID files (e.g. helpdesk attachments) are visible to a
590
+ // SystemAdmin whose session sits in another tenant, and files of entities that declare
591
+ // crossTenantFileRead to users their query admits. Delete and upload keep using
592
+ // loadFileForTenant and stay tenant-equal.
593
+ async function loadReadableFile(id, user) {
570
594
  const own = await loadFileForTenant(id, user.tenantId);
571
- if (own || !canReadSystemTenantFile(user, SYSTEM_TENANT_ID))
572
- return own;
573
- return loadFileForTenant(id, SYSTEM_TENANT_ID, systemTenantReadDb(db));
595
+ if (own)
596
+ return { fileRef: own, foreign: false };
597
+ if (canReadSystemTenantFile(user, SYSTEM_TENANT_ID)) {
598
+ const system = await loadFileForTenant(id, SYSTEM_TENANT_ID, systemTenantReadDb(db));
599
+ if (system)
600
+ return { fileRef: system, foreign: false };
601
+ }
602
+ return loadForeignFile(id, user);
603
+ }
604
+ async function loadOwnOrForeignFile(id, user) {
605
+ const own = await loadFileForTenant(id, user.tenantId);
606
+ return own ? { fileRef: own, foreign: false } : loadForeignFile(id, user);
607
+ }
608
+ // Located across tenants only for declared entity types; whether the user may read it is decided
609
+ // by readDecisionFor, so a caller that skips it must not hand the file out.
610
+ async function loadForeignFile(id, user) {
611
+ if (canReadForeignTenantFile === undefined || isAnonymousSessionUser(user))
612
+ return null;
613
+ if (!isUuid(id))
614
+ return null;
615
+ const [row] = await selectMany(foreignTenantFileReadDb(db), fileRefsTable, {
616
+ id,
617
+ isDeleted: false,
618
+ });
619
+ const fileRef = row === undefined ? undefined : fileRefOfRow(row);
620
+ if (fileRef === undefined ||
621
+ fileRef.tenantId === user.tenantId ||
622
+ fileRef.entityType === null ||
623
+ fileRef.entityId === null ||
624
+ !crossTenantFileReadQueries.has(fileRef.entityType)) {
625
+ return null;
626
+ }
627
+ return { fileRef, foreign: true };
628
+ }
629
+ // A foreign tenant's file is decided by the declared query alone: the guard's privilegedRoles
630
+ // would otherwise hand it to any admin of any tenant.
631
+ async function readDecisionFor({ fileRef, foreign }, user) {
632
+ if (!foreign)
633
+ return guard({ fileRef, user, operation: "read" });
634
+ if (canReadForeignTenantFile === undefined || isAnonymousSessionUser(user))
635
+ return "deny";
636
+ return (await canReadForeignTenantFile({ fileRef, user })) ? "allow" : "deny";
574
637
  }
575
638
  async function loadFileForTenant(id, tenantId, readDb = db) {
576
639
  // fileRefsTable.id is a UUID column — a malformed id must fail here, not
@@ -582,7 +645,7 @@ export function createFileRoutes(options) {
582
645
  // isDeleted:false — soft-deleted (trashed) rows stay recoverable but must
583
646
  // never surface to reads/guards.
584
647
  const [row] = await selectMany(readDb, fileRefsTable, { id, tenantId, isDeleted: false });
585
- return row ?? null; // @cast-boundary db-row
648
+ return row === undefined ? null : fileRefOfRow(row);
586
649
  }
587
650
  return api;
588
651
  }
@@ -0,0 +1,13 @@
1
+ import type { TenantDb } from "@cosmicdrift/kumiko-types/tenant-db-types";
2
+ import type { DbConnection } from "../db/connection.ts";
3
+ import type { Registry, SessionUser } from "../engine/types/index.ts";
4
+ import type { FileRef } from "./file-routes.ts";
5
+ export type ForeignTenantFileReadCheck = (args: {
6
+ readonly fileRef: FileRef;
7
+ readonly user: SessionUser;
8
+ }) => Promise<boolean>;
9
+ type QueryAsUser = (type: string, payload: unknown, user: SessionUser) => Promise<unknown>;
10
+ export declare function collectCrossTenantFileReadQueries(registry: Registry): ReadonlyMap<string, string>;
11
+ export declare function createForeignTenantFileReadCheck(registry: Registry, query: QueryAsUser): ForeignTenantFileReadCheck;
12
+ export declare function foreignTenantFileReadDb(db: DbConnection): TenantDb;
13
+ export {};
@@ -0,0 +1,64 @@
1
+ import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
2
+ import { createTenantDb } from "../db/tenant-db.js";
3
+ import { SYSTEM_TENANT_ID } from "../engine/types/index.js";
4
+ import { isKumikoError } from "../errors/index.js";
5
+ import { createFallbackLogger } from "../logging/index.js";
6
+ const log = createFallbackLogger("files");
7
+ const cache = new WeakMap();
8
+ // Event-sourced read models (projection entities) are not in getAllEntities, so both sources count.
9
+ export function collectCrossTenantFileReadQueries(registry) {
10
+ const cached = cache.get(registry);
11
+ if (cached)
12
+ return cached;
13
+ const queryByEntityType = new Map();
14
+ for (const [name, entity] of registry.getAllEntities()) {
15
+ if (entity.crossTenantFileRead)
16
+ queryByEntityType.set(name, entity.crossTenantFileRead.query);
17
+ }
18
+ for (const projection of registry.getAllProjections().values()) {
19
+ const name = projection.source;
20
+ if (typeof name !== "string")
21
+ continue;
22
+ const declaration = registry.getReadModelEntity(name)?.crossTenantFileRead;
23
+ if (declaration)
24
+ queryByEntityType.set(name, declaration.query);
25
+ }
26
+ cache.set(registry, queryByEntityType);
27
+ return queryByEntityType;
28
+ }
29
+ // The declared query runs as the requesting user, so its own access and visibility rules decide.
30
+ // Only a record carrying the requested id counts; null, other shapes and access errors mean no; the caller's own guard never applies to a foreign tenant's file.
31
+ export function createForeignTenantFileReadCheck(registry, query) {
32
+ return async ({ fileRef, user }) => {
33
+ const { entityType, entityId } = fileRef;
34
+ if (entityType === null || entityId === null)
35
+ return false;
36
+ const queryQn = collectCrossTenantFileReadQueries(registry).get(entityType);
37
+ if (queryQn === undefined)
38
+ return false;
39
+ try {
40
+ const record = await query(queryQn, { id: entityId }, user);
41
+ return propertyOf(record, "id") === entityId;
42
+ }
43
+ catch (error) {
44
+ if (!isKumikoError(error) || error.httpStatus >= 500) {
45
+ log.error("cross-tenant file read check failed; file access denied", {
46
+ entityType,
47
+ queryQn,
48
+ error: error instanceof Error ? error.message : String(error),
49
+ });
50
+ }
51
+ return false;
52
+ }
53
+ };
54
+ }
55
+ // Reads file_refs rows of every tenant, never writes; callers narrow to declared entity types.
56
+ export function foreignTenantFileReadDb(db) {
57
+ return createTenantDb({
58
+ db,
59
+ tenantId: SYSTEM_TENANT_ID,
60
+ mode: "system",
61
+ reason: "cross-tenant file read of entities that declare crossTenantFileRead",
62
+ grants: { writesDeniedReason: "on the cross-tenant file read handle" },
63
+ });
64
+ }
@@ -73,6 +73,9 @@ function pushEditFieldTextKeys(out, spec, treatAsKey = false) {
73
73
  pushKey(out, affix, treatAsKey);
74
74
  }
75
75
  pushKey(out, spec.fillAction?.label, treatAsKey);
76
+ for (const chip of spec.aiAssist?.chips ?? [])
77
+ pushKey(out, chip.label, treatAsKey);
78
+ pushKey(out, spec.aiAssist?.prompt?.placeholder, treatAsKey);
76
79
  }
77
80
  // Group titles are translated exactly like the section title (computeEditViewModel).
78
81
  function pushSectionTitles(out, section, treatAsKey = false) {
@@ -91,7 +94,7 @@ function pushActionFormShapedKeys(out, featureName, step) {
91
94
  pushKey(out, section.title);
92
95
  continue;
93
96
  }
94
- if (section.kind === "relatedList")
97
+ if (section.kind === "relatedList" || section.kind === "stepList")
95
98
  continue; // rejected at boot, unreachable here
96
99
  pushSectionTitles(out, section);
97
100
  for (const f of sectionFieldSpecs(section)) {
@@ -108,8 +111,9 @@ function pushRowActionKeys(out, action) {
108
111
  pushKey(out, action.confirm);
109
112
  pushKey(out, action.confirmLabel);
110
113
  }
111
- if (action.kind === "clientAction")
114
+ if (action.kind === "clientAction" && action.successMessage !== false) {
112
115
  pushKey(out, action.successMessage);
116
+ }
113
117
  if (action.kind === "drawer") {
114
118
  pushKey(out, action.title);
115
119
  pushKey(out, action.subtitle);
@@ -251,10 +255,13 @@ function pushExpandableRowKeys(out, section) {
251
255
  pushRowActionKeys(out, section.emptyState.action);
252
256
  }
253
257
  }
258
+ function fieldTextRefKey(ref) {
259
+ return typeof ref === "string" ? ref : ref.key;
260
+ }
254
261
  function pushFieldLabelOrOverrideKey(ctx, labelEntity, fieldName, fieldLabels, treatAsKey = false) {
255
262
  const override = fieldLabels?.[fieldName];
256
263
  if (override !== undefined)
257
- pushKey(ctx.out, override, treatAsKey);
264
+ pushKey(ctx.out, fieldTextRefKey(override), treatAsKey);
258
265
  else
259
266
  ctx.out.add(fieldLabelKey(ctx.featureName, labelEntity, fieldName));
260
267
  }
@@ -304,7 +311,7 @@ function pushEditLayoutSectionKeys(ctx, sections, labelEntity, fieldLabels) {
304
311
  pushKey(ctx.out, section.title);
305
312
  continue;
306
313
  }
307
- if (section.kind === "relatedList")
314
+ if (section.kind === "relatedList" || section.kind === "stepList")
308
315
  continue; // rejected at boot, unreachable here
309
316
  pushSectionTitles(ctx.out, section);
310
317
  for (const f of sectionFieldSpecs(section)) {
@@ -324,6 +331,12 @@ function collectActionFormKeys(ctx, form) {
324
331
  pushKey(ctx.out, form.summary?.subtitle);
325
332
  for (const action of form.footerActions ?? [])
326
333
  pushKey(ctx.out, action.label);
334
+ for (const ref of Object.values(form.fieldDescriptions ?? {})) {
335
+ pushKey(ctx.out, fieldTextRefKey(ref));
336
+ }
337
+ pushKey(ctx.out, form.infoBand);
338
+ for (const badge of Object.values(form.fieldBadges ?? {}))
339
+ pushKey(ctx.out, badge.label);
327
340
  for (const link of form.successLinks ?? [])
328
341
  pushKey(ctx.out, link.label);
329
342
  for (const fact of form.successFacts ?? [])
@@ -358,7 +371,7 @@ function pushConfigEditSectionKeys(ctx, config) {
358
371
  pushKey(out, section.title);
359
372
  continue;
360
373
  }
361
- if (section.kind === "relatedList")
374
+ if (section.kind === "relatedList" || section.kind === "stepList")
362
375
  continue; // rejected at boot, unreachable here
363
376
  pushSectionTitles(out, section, treatDotFormAsKey);
364
377
  pushKey(out, section.description, treatDotFormAsKey);
@@ -402,6 +415,12 @@ function pushWriteFormSectionKeys(ctx, section) {
402
415
  function collectProjectionDetailKeys(ctx, detail) {
403
416
  for (const metric of detail.metrics ?? [])
404
417
  pushKey(ctx.out, metric.label);
418
+ pushKey(ctx.out, detail.header?.narrowTitle);
419
+ for (const section of detail.layout.sections) {
420
+ pushKey(ctx.out, section.tabLabel);
421
+ if ("descriptionNarrow" in section)
422
+ pushKey(ctx.out, section.descriptionNarrow);
423
+ }
405
424
  pushDetailGuidanceKeys(detail, (value) => pushKey(ctx.out, value), (action) => pushRowActionKeys(ctx.out, action));
406
425
  for (const section of detail.layout.sections) {
407
426
  if (isExtensionEditSection(section)) {
@@ -414,6 +433,10 @@ function collectProjectionDetailKeys(ctx, detail) {
414
433
  pushKey(ctx.out, bulk.confirm);
415
434
  continue;
416
435
  }
436
+ if (section.kind === "stepList") {
437
+ pushKey(ctx.out, section.title);
438
+ continue;
439
+ }
417
440
  if (isWriteFormEditSection(section)) {
418
441
  pushWriteFormSectionKeys(ctx, section);
419
442
  continue;
@@ -679,8 +702,11 @@ export function fieldValueTranslationKeysFromFeature(feature) {
679
702
  if (!entity)
680
703
  continue;
681
704
  for (const section of screen.layout.sections) {
682
- if (isExtensionEditSection(section) || section.kind === "relatedList")
705
+ if (isExtensionEditSection(section) ||
706
+ section.kind === "relatedList" ||
707
+ section.kind === "stepList") {
683
708
  continue;
709
+ }
684
710
  for (const spec of sectionFieldSpecs(section)) {
685
711
  const field = editFieldName(spec);
686
712
  const def = entity.fields[field];
@@ -3,7 +3,7 @@ import { InternalError, VersionConflictError } from "../errors/index.js";
3
3
  import { memberResolutionReadOnlyDenied } from "../errors/member-resolution.js";
4
4
  import { archiveStream as archiveStreamHelper, isStreamArchived, restoreStream as restoreStreamHelper, } from "../event-store/archive.js";
5
5
  import { IdempotentAppendConflictError as EventStoreIdempotentAppendConflictError, VersionConflictError as EventStoreVersionConflictError, } from "../event-store/errors.js";
6
- import { loadAggregate, loadAggregateAsOf, loadAggregateForWriting, } from "../event-store/event-store.js";
6
+ import { loadAggregate, loadAggregateAsOf, loadAggregateForWriting, loadEventsOfAggregatesByType, } from "../event-store/event-store.js";
7
7
  import { effectiveSnapshotGeneration, loadAggregateWithSnapshot, saveSnapshot, } from "../event-store/snapshot.js";
8
8
  import { makeUpcastCtx, upcastStoredEvent, upcastStoredEvents } from "../event-store/upcaster.js";
9
9
  import { appendDomainEventCore } from "./append-event-core.js";
@@ -120,6 +120,19 @@ export async function loadUpcastedAggregate(source, aggregateId, loadOptions) {
120
120
  });
121
121
  return upcastStoredEvents(events, registry.getEventUpcasters(), makeUpcastCtx(db, tenantId));
122
122
  }
123
+ /** Upcasters keep the event type, so the SQL type filter stays valid after upcasting. */
124
+ async function loadUpcastedEventsByTypes(source, args) {
125
+ const { db, registry, tenantId } = source;
126
+ const events = await loadEventsOfAggregatesByType(db, tenantId, args);
127
+ return upcastStoredEvents(events, registry.getEventUpcasters(), makeUpcastCtx(db, tenantId));
128
+ }
129
+ function buildLoadByTypes(scope) {
130
+ const { ctx, user, tx, registry } = scope;
131
+ return (args) => {
132
+ const db = requireDbSource(ctx, tx, "ctx.events.loadByTypes");
133
+ return loadUpcastedEventsByTypes({ db, registry, tenantId: user.tenantId }, args);
134
+ };
135
+ }
123
136
  function buildLoadAggregate(scope) {
124
137
  const { ctx, user, tx, registry } = scope;
125
138
  return (aggregateId, loadOptions) => {
@@ -174,6 +187,7 @@ export function buildEventStoreFacet(scope) {
174
187
  tryAppend: buildTryAppendEvent(scope),
175
188
  fetchForWriting: buildFetchForWriting(scope),
176
189
  load: buildLoadAggregate(scope),
190
+ loadByTypes: buildLoadByTypes(scope),
177
191
  archive: async (aggregateId, archiveArgs) => {
178
192
  const dbSource = requireDbSource(ctx, tx, `ctx.events.archive("${aggregateId}")`);
179
193
  await archiveStreamHelper(dbSource, {
@@ -6,11 +6,14 @@ export type CardRoleColumn = {
6
6
  readonly renderer?: unknown;
7
7
  readonly hideOnNarrow?: boolean;
8
8
  readonly narrowInline?: boolean;
9
+ readonly cardBadge?: boolean;
9
10
  readonly fileDisplay?: {
10
11
  readonly kind: string;
11
12
  };
12
13
  /** A "to do" hint column: never the default card title. */
13
14
  readonly hint?: unknown;
15
+ /** Leads the card like a hint column; covers computed columns, which need a renderer and so cannot take `hint`. */
16
+ readonly emphasis?: boolean;
14
17
  };
15
18
  export type CardColumnRoles<C extends CardRoleColumn> = {
16
19
  readonly image: C | undefined;
@@ -22,11 +22,15 @@ export function cardColumnRoles(columns) {
22
22
  const image = columns.find((col) => isImage(col) && col.hideOnNarrow !== true);
23
23
  // A narrow-hidden image must not turn into the title just because it is not the preview.
24
24
  const textColumns = columns.filter((col) => col !== image && !(isImage(col) && col.hideOnNarrow === true));
25
- const title = textColumns.find((col) => col.highlighted === true) ??
26
- textColumns.find((col) => col.hint === undefined) ??
27
- textColumns[0];
28
- const status = textColumns.find((col) => col !== title && col.type === "select" && col.renderer === undefined);
29
- const lead = textColumns.find((col) => col !== title && col !== status && col.hint !== undefined && col.hideOnNarrow !== true);
25
+ // A column the phone hides cannot be the card title.
26
+ const titleCandidates = textColumns.filter((col) => col.hideOnNarrow !== true);
27
+ const isLeadCandidate = (col) => col.hint !== undefined || col.emphasis === true;
28
+ const title = titleCandidates.find((col) => col.highlighted === true) ??
29
+ titleCandidates.find((col) => !isLeadCandidate(col)) ??
30
+ titleCandidates[0];
31
+ const status = textColumns.find((col) => col !== title && col.cardBadge === true && col.hideOnNarrow !== true) ??
32
+ textColumns.find((col) => col !== title && col.type === "select" && col.renderer === undefined);
33
+ const lead = textColumns.find((col) => col !== title && col !== status && isLeadCandidate(col) && col.hideOnNarrow !== true);
30
34
  const meta = textColumns.filter((col) => col !== title && col !== status && col !== lead && col.hideOnNarrow !== true);
31
35
  return { image, lead, title, status, meta };
32
36
  }
@@ -11,7 +11,7 @@ export type { EmbeddedDerivedCellDef, EntityDefinition, FieldDefinition, Options
11
11
  export type { AccessRule } from "../engine/types/handlers.ts";
12
12
  export { isOpenToAllGranted, isUiAccessGranted } from "../engine/types/handlers.ts";
13
13
  export type { IconKey, NavDefinition, NavIconKey } from "../engine/types/nav.ts";
14
- export type { ActionFormFooterAction, ActionFormLoad, ActionFormRedirect, ActionFormScreenDefinition, ActionFormSuccessFact, ActionFormSuccessItems, ActionFormSuccessLink, ConfigEditAction, ConfigEditScreenDefinition, CustomScreenDefinition, DashboardChartMarkerKind, DashboardChartPanel, DashboardCurrencyFormat, DashboardCustomPanel, DashboardDateParam, DashboardFeedPanel, DashboardFilterDefinition, DashboardI18nText, DashboardListFooterLink, DashboardListNarrow, DashboardListPanel, DashboardListRowToneMarker, DashboardMoneyParam, DashboardPanelDefinition, DashboardPanelEmptyState, DashboardPanelNarrow, DashboardPanelQueryOptions, DashboardPanelSpan, DashboardPanelVisibility, DashboardProgressListPanel, DashboardProgressTone, DashboardRefresh, DashboardRelativeTimeParam, DashboardScopeDefinition, DashboardScreenDefinition, DashboardScreenPanel, DashboardStatGroupLayout, DashboardStatGroupLink, DashboardStatGroupNarrow, DashboardStatGroupPanel, DashboardStatPanel, DashboardText, DashboardTextBlock, DashboardTextPanel, DashboardTextParam, DashboardTimeRangeDefinition, EditExtensionSection, EditFieldSpec, EditFieldsSection, EditLayout, EditRelatedListSection, EditSectionSpec, EditWriteFormSection, EmbeddedListEditSpec, EntityEditAction, EntityEditScreenDefinition, EntityListFacetConfig, EntityListScreenDefinition, FieldAffix, FieldCondition, FieldFillAction, FieldIconKey, FieldRenderer, FormWidth, ListBulkAction, ListColumnHint, ListColumnSpec, ListEmptyStateSpec, ListFacetSpec, ListRowDecoration, ListSortOption, ListSortSpec, ListTableOptions, ListTableSummaryRow, ListToolbarActionsPlacement, MetricNavigate, PlatformComponent, ProjectionDetailScreenDefinition, ProjectionListScreenDefinition, RecordBannerSpec, RecordBreadcrumbItem, RecordBreadcrumbSpec, RecordHeaderSubtitlePart, RecordNotice, RecordProgress, RecordProgressSpec, RecordProgressStep, RecordStep, RecordStepsSpec, RecordSummarySpec, RelatedListEmptyStateSpec, RelatedListEmptyStateVariant, RelatedListRowTone, RelatedListToolbarAction, RowAction, RowActionClientAction, RowActionDisplay, RowActionDrawer, RowActionMode, RowActionNavigate, RowActionWriteHandler, RowFieldExtractor, ScreenDefinition, ScreenFallback, ScreenFallbackByReason, ScreenFallbackReason, ScreenSlots, ScreenVisibility, SecretMintConfirmStep, SecretMintScreenDefinition, SecretsEditScreenDefinition, ToolbarAction, } from "../engine/types/screen.ts";
14
+ export type { ActionFormFooterAction, ActionFormLoad, ActionFormRedirect, ActionFormScreenDefinition, ActionFormSuccessFact, ActionFormSuccessItems, ActionFormSuccessLink, ConfigEditAction, ConfigEditScreenDefinition, CustomScreenDefinition, DashboardChartMarkerKind, DashboardChartPanel, DashboardCurrencyFormat, DashboardCustomPanel, DashboardDateParam, DashboardFeedPanel, DashboardFilterDefinition, DashboardI18nText, DashboardLayout, DashboardListFooterLink, DashboardListNarrow, DashboardListPanel, DashboardListRowToneMarker, DashboardMoneyParam, DashboardPanelColumn, DashboardPanelDefinition, DashboardPanelEmptyState, DashboardPanelNarrow, DashboardPanelQueryOptions, DashboardPanelSpan, DashboardPanelVisibility, DashboardProgressListPanel, DashboardProgressTone, DashboardRefresh, DashboardRelativeTimeParam, DashboardScopeDefinition, DashboardScreenDefinition, DashboardScreenPanel, DashboardStatGroupLayout, DashboardStatGroupLink, DashboardStatGroupNarrow, DashboardStatGroupPanel, DashboardStatPanel, DashboardText, DashboardTextBlock, DashboardTextPanel, DashboardTextParam, DashboardTimeRangeDefinition, EditExtensionSection, EditFieldSpec, EditFieldsSection, EditLayout, EditRelatedListSection, EditSectionSpec, EditStepListSection, EditWriteFormSection, EmbeddedListEditSpec, EntityEditAction, EntityEditScreenDefinition, EntityListFacetConfig, EntityListScreenDefinition, FieldAffix, FieldAiAssist, FieldAiAssistChip, FieldBadge, FieldCondition, FieldFillAction, FieldIconKey, FieldRenderer, FieldTextRef, FieldValueChips, FormWidth, ListBulkAction, ListColumnHint, ListColumnSpec, ListEmptyStateSpec, ListFacetSpec, ListRowDecoration, ListSortOption, ListSortSpec, ListTableOptions, ListTableSummaryRow, ListToolbarActionsPlacement, MetricNavigate, PlatformComponent, ProjectionDetailInitialTab, ProjectionDetailScreenDefinition, ProjectionListScreenDefinition, RecordBannerSpec, RecordBreadcrumbItem, RecordBreadcrumbSpec, RecordHeaderSubtitlePart, RecordNotice, RecordProgress, RecordProgressSpec, RecordProgressStep, RecordStep, RecordStepsSpec, RecordSummarySpec, RelatedListEmptyStateSpec, RelatedListEmptyStateVariant, RelatedListRowTone, RelatedListToolbarAction, RowAction, RowActionClientAction, RowActionDisplay, RowActionDrawer, RowActionMode, RowActionNavigate, RowActionWriteHandler, RowFieldExtractor, ScreenDefinition, ScreenFallback, ScreenFallbackByReason, ScreenFallbackReason, ScreenSlots, ScreenVisibility, SecretMintConfirmStep, SecretMintScreenDefinition, SecretsEditScreenDefinition, StepListItem, ToolbarAction, } from "../engine/types/screen.ts";
15
15
  export { MAX_BULK_SELECTION } from "../engine/types/screen.ts";
16
16
  export type { TargetRef } from "../engine/types/target-ref.ts";
17
17
  export type { TreeAction } from "../engine/types/tree-node.ts";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-framework",
3
- "version": "0.415.0",
3
+ "version": "0.417.0",
4
4
  "description": "Framework core — engine, pipeline, API, DB, and every other bit that makes Kumiko go.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -204,7 +204,7 @@
204
204
  "./package.json": "./package.json"
205
205
  },
206
206
  "dependencies": {
207
- "@cosmicdrift/kumiko-types": "0.415.0",
207
+ "@cosmicdrift/kumiko-types": "0.417.0",
208
208
  "bullmq": "^5.81.5",
209
209
  "hono": "^4.13.14",
210
210
  "i18next": "^26.5.12",
@@ -226,7 +226,7 @@
226
226
  }
227
227
  },
228
228
  "devDependencies": {
229
- "@cosmicdrift/kumiko-testing": "0.415.0",
229
+ "@cosmicdrift/kumiko-testing": "0.417.0",
230
230
  "bun-types": "^1.4.4",
231
231
  "fflate": "^0.8.3",
232
232
  "meilisearch": "^0.62.0",