@marktiderman/genesis-core 2.14.0 → 2.16.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 (101) hide show
  1. package/dist/aggregate-Y5IJ5aPn.d.ts +34 -0
  2. package/dist/{chunk-7PUFVNPB.js → chunk-2IGAUXYH.js} +5 -3
  3. package/dist/chunk-2IGAUXYH.js.map +1 -0
  4. package/dist/{chunk-KA3BUJ4H.js → chunk-42NVJJTT.js} +3 -3
  5. package/dist/{chunk-KA3BUJ4H.js.map → chunk-42NVJJTT.js.map} +1 -1
  6. package/dist/{chunk-JN47G4UE.js → chunk-7EFTWOMA.js} +56 -2
  7. package/dist/chunk-7EFTWOMA.js.map +1 -0
  8. package/dist/{chunk-P3FHXRS2.js → chunk-ALLWIK62.js} +6 -6
  9. package/dist/{chunk-P3FHXRS2.js.map → chunk-ALLWIK62.js.map} +1 -1
  10. package/dist/chunk-APFXV6FZ.js +130 -0
  11. package/dist/chunk-APFXV6FZ.js.map +1 -0
  12. package/dist/chunk-BDPRWVFW.js +17 -0
  13. package/dist/chunk-BDPRWVFW.js.map +1 -0
  14. package/dist/{chunk-S2VYJWB4.js → chunk-E3K2A3PK.js} +3 -3
  15. package/dist/{chunk-S2VYJWB4.js.map → chunk-E3K2A3PK.js.map} +1 -1
  16. package/dist/{chunk-OYDJGPDY.js → chunk-FXPODKCK.js} +5 -5
  17. package/dist/{chunk-OYDJGPDY.js.map → chunk-FXPODKCK.js.map} +1 -1
  18. package/dist/{chunk-SDAJSJNN.js → chunk-IYGVJFCV.js} +3 -3
  19. package/dist/{chunk-SDAJSJNN.js.map → chunk-IYGVJFCV.js.map} +1 -1
  20. package/dist/chunk-J54XXKQD.js +104 -0
  21. package/dist/chunk-J54XXKQD.js.map +1 -0
  22. package/dist/{chunk-KV2HW4G4.js → chunk-LB6FMQQM.js} +11 -3
  23. package/dist/chunk-LB6FMQQM.js.map +1 -0
  24. package/dist/{chunk-G6GQPXQS.js → chunk-M5IX7C6U.js} +5 -5
  25. package/dist/{chunk-G6GQPXQS.js.map → chunk-M5IX7C6U.js.map} +1 -1
  26. package/dist/{chunk-DFABPMEQ.js → chunk-POUI7GAI.js} +5 -5
  27. package/dist/{chunk-DFABPMEQ.js.map → chunk-POUI7GAI.js.map} +1 -1
  28. package/dist/{chunk-NE2D74BP.js → chunk-QGWQ6LK3.js} +5 -5
  29. package/dist/{chunk-NE2D74BP.js.map → chunk-QGWQ6LK3.js.map} +1 -1
  30. package/dist/{chunk-2K4747KX.js → chunk-R3YXYVWF.js} +7 -2
  31. package/dist/chunk-R3YXYVWF.js.map +1 -0
  32. package/dist/{chunk-RFHUOXZC.js → chunk-SOO54YYY.js} +4 -4
  33. package/dist/{chunk-RFHUOXZC.js.map → chunk-SOO54YYY.js.map} +1 -1
  34. package/dist/{chunk-YZV3Z6ZA.js → chunk-SQLM5CIJ.js} +3 -3
  35. package/dist/{chunk-YZV3Z6ZA.js.map → chunk-SQLM5CIJ.js.map} +1 -1
  36. package/dist/{chunk-WDPM5TBO.js → chunk-UDSTWXXZ.js} +3 -3
  37. package/dist/{chunk-WDPM5TBO.js.map → chunk-UDSTWXXZ.js.map} +1 -1
  38. package/dist/chunk-XPBS5YE4.js +24 -0
  39. package/dist/chunk-XPBS5YE4.js.map +1 -0
  40. package/dist/{chunk-AHFIS42U.js → chunk-ZYOJWU62.js} +5 -5
  41. package/dist/{chunk-AHFIS42U.js.map → chunk-ZYOJWU62.js.map} +1 -1
  42. package/dist/csv.d.ts +1 -1
  43. package/dist/form-types.d.ts +1 -1
  44. package/dist/headless/index.d.ts +334 -0
  45. package/dist/headless/index.js +490 -0
  46. package/dist/headless/index.js.map +1 -0
  47. package/dist/hooks/index.d.ts +4 -2
  48. package/dist/hooks/index.js +20 -17
  49. package/dist/hooks/mutation-mode.d.ts +1 -1
  50. package/dist/hooks/mutation-mode.js +5 -4
  51. package/dist/hooks/related-keys.d.ts +1 -1
  52. package/dist/hooks/use-aggregate.d.ts +25 -0
  53. package/dist/hooks/use-aggregate.js +10 -0
  54. package/dist/hooks/use-aggregate.js.map +1 -0
  55. package/dist/hooks/use-capabilities.d.ts +1 -1
  56. package/dist/hooks/use-capabilities.js +4 -2
  57. package/dist/hooks/use-draft.js +2 -2
  58. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  59. package/dist/hooks/use-infinite-resource.js +6 -4
  60. package/dist/hooks/use-link-options.d.ts +1 -1
  61. package/dist/hooks/use-link-options.js +8 -6
  62. package/dist/hooks/use-live.d.ts +1 -1
  63. package/dist/hooks/use-live.js +4 -2
  64. package/dist/hooks/use-one.d.ts +1 -1
  65. package/dist/hooks/use-one.js +6 -4
  66. package/dist/hooks/use-persisted-ui-state.js +4 -2
  67. package/dist/hooks/use-relation-label.d.ts +1 -1
  68. package/dist/hooks/use-relation-label.js +4 -2
  69. package/dist/hooks/use-resource-form.d.ts +1 -1
  70. package/dist/hooks/use-resource-form.js +8 -7
  71. package/dist/hooks/use-resource.d.ts +1 -1
  72. package/dist/hooks/use-resource.js +7 -6
  73. package/dist/hooks/use-write.d.ts +1 -1
  74. package/dist/index.d.ts +110 -6
  75. package/dist/index.js +129 -20
  76. package/dist/index.js.map +1 -1
  77. package/dist/navigation.d.ts +77 -1
  78. package/dist/navigation.js +32 -2
  79. package/dist/navigation.js.map +1 -1
  80. package/dist/provider/index.d.ts +12 -4
  81. package/dist/provider/index.js +3 -2
  82. package/dist/resource-view/index.d.ts +456 -166
  83. package/dist/resource-view/index.js +251 -5
  84. package/dist/resource-view/index.js.map +1 -1
  85. package/dist/schema/index.d.ts +3 -3
  86. package/dist/schema/index.js +1 -2
  87. package/dist/testing/index.d.ts +2 -2
  88. package/dist/{types-CtJxwoyv.d.ts → types-BriIV4e_.d.ts} +78 -3
  89. package/dist/workspaces-CxpiFu2-.d.ts +263 -0
  90. package/dist/workspaces.d.ts +2 -160
  91. package/dist/workspaces.js +2 -1
  92. package/dist/{write-outcome-Goy1v39G.d.ts → write-outcome-CkQXgtJq.d.ts} +1 -1
  93. package/package.json +14 -4
  94. package/dist/chunk-2K4747KX.js.map +0 -1
  95. package/dist/chunk-7PUFVNPB.js.map +0 -1
  96. package/dist/chunk-JN47G4UE.js.map +0 -1
  97. package/dist/chunk-KV2HW4G4.js.map +0 -1
  98. package/dist/chunk-UHOMTFBD.js +0 -72
  99. package/dist/chunk-UHOMTFBD.js.map +0 -1
  100. package/dist/chunk-YDMKMNDS.js +0 -8
  101. package/dist/chunk-YDMKMNDS.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/resource-view/errors.ts","../../src/resource-view/scope.ts","../../src/resource-view/link.ts","../../src/resource-view/define-view.ts","../../src/resource-view/picture.ts","../../src/resource-view/tree.ts","../../src/resource-view/record-view.ts"],"names":["own"],"mappings":";;;;;;;;;;;;AAGO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EACpC,QAAA;AAAA,EACT,WAAA,CAAY,UAAkB,QAAA,EAA6B;AACzD,IAAA,KAAA,CAAM,cAAc,QAAQ,CAAA,GAAA,EAAM,SAAS,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AACvD,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAAA,EAClB;AACF;;;ACFA,IAAM,KAAA,GAAQ,CAAC,GAAA,KAAgB,GAAA,CAAI,OAAA,CAAQ,cAAA,EAAgB,CAAC,CAAA,EAAG,CAAA,KAAc,CAAA,CAAE,WAAA,EAAa,CAAA;AAcrF,SAAS,WAAA,CAEd,MACA,KAAA,EACsC;AACtC,EAAA,MAAM,MAAkC,EAAC;AACzC,EAAA,MAAM,UAAoB,EAAC;AAC3B,EAAA,KAAA,MAAW,GAAA,IAAQ,IAAA,CAAK,UAAA,CAAW,KAAA,IAAS,EAAC,EAAyB;AACpE,IAAA,MAAM,KAAA,GAAQ,KAAA,IAAS,MAAA,CAAO,MAAA,CAAO,KAAA,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ACpF,MAAA,MAAM,GAAA,GAAM,OAAO,GAAG,CAAA;AACtB,MAAA,IAAI,KAAI,EAAG;AACT,QAAA,MAAM,OAAA,GAAU,OAAO,OAAO,GAAA,KAAQ,WAAW,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,GAAI,EAAC;AACxE,QAAA,MAAM,MAAM,OAAA,CAAQ,MAAA,CAAO,CAAC,GAAG,CAAC,CAAA,KAAM,EAAE,MAAM,IAAA,IAAQ,OAAO,MAAM,QAAA,IAAY,OAAO,MAAM,QAAA,IAAY,OAAO,MAAM,SAAA,CAAU,CAAA;AAC/H,QAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,IAAK,GAAA,CAAI,MAAA,EAAQ;AACtC,UAAA,MAAM,IAAI,oBAAoB,KAAA,EAAO;AAAA,YACnC,OAAA,CAAQ,WAAW,CAAA,GACf,CAAA,SAAA,EAAY,SAAS,CAAA,qDAAA,CAAA,GACrB,CAAA,SAAA,EAAY,SAAS,CAAA,mBAAA,EAAsB,GAAA,CAAI,IAAI,CAAC,CAAC,CAAC,CAAA,KAAM,CAAA,CAAA,EAAI,CAAC,CAAA,CAAA,CAAG,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,gBAAA;AAAA,WACrF,CAAA;AAAA,QACH;AAAA,MACF;AACA,MAAA,OAAO,MAAA,CAAO,MAAA,CAAO,EAAE,GAAG,KAAK,CAAA;AAAA,IACjC,CAAA;AAAA,IACA,YAAA;AAAA,IACA;AAAA,GACD,CAAA;AACH;AAMO,IAAM,eAAA,GAAkB;AAExB,IAAM,WAAA,GAAc","file":"index.js","sourcesContent":["// The error defineView and its helpers throw for a view that doesn't fit its contract.\n\n/** A view that names a field, preset or section its contract doesn't have. */\nexport class ViewDefinitionError extends Error {\n readonly problems: readonly string[];\n constructor(resource: string, problems: readonly string[]) {\n super(`defineView(${resource}): ${problems.join(\"; \")}`);\n this.name = \"ViewDefinitionError\";\n this.problems = problems;\n }\n}\n","// scopeValues: a view's scope keys, read from ViewerScope's `scope`, as a screen's `filter`.\n\nimport type { ResourceScope } from \"../hooks/viewer-scope\";\nimport { ViewDefinitionError } from \"./errors\";\nimport type { ResourceView } from \"./types\";\n\ntype ScopeValue = string | number | boolean | null;\n\nconst camel = (key: string) => key.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n\n/**\n * The view's declared scope keys with their values from the viewer's scope, ready to pass as a\n * screen's `filter`: `scope: [\"league_id\"]` reads `scope.league_id`, then `scope.leagueId`.\n *\n * ```tsx\n * <ResourceView view={brandsView} filter={scopeValues(brandsView, useViewerScope().scope)} />\n * ```\n *\n * In development a declared key with no single value (missing, `undefined`, or a list) throws\n * {@link ViewDefinitionError}, so a screen mounted outside its scope fails loudly. In production\n * it is left out; row-level security still decides what the viewer reads.\n */\nexport function scopeValues(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract\n view: Pick<ResourceView<any, any>, \"resource\" | \"definition\">,\n scope: ResourceScope | null | undefined,\n): Readonly<Record<string, ScopeValue>> {\n const out: Record<string, ScopeValue> = {};\n const missing: string[] = [];\n for (const key of (view.definition.scope ?? []) as readonly string[]) {\n const value = scope && Object.hasOwn(scope, key) ? scope[key] : scope?.[camel(key)];\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") out[key] = value;\n else missing.push(key);\n }\n if (missing.length && process.env.NODE_ENV !== \"production\") {\n throw new ViewDefinitionError(\n view.resource,\n missing.map((key) => `scope \"${key}\" has no single value in ViewerScope's scope`),\n );\n }\n return Object.freeze(out);\n}\n\n/**\n * The view's scope keys as a list filter, the way `ResourceView` applies them itself: like\n * {@link scopeValues}, but a list (`{ orgId: [\"o1\", \"o2\"] }`, a roll-up across organizations)\n * filters to any of its values, and a key the scope doesn't set is left out instead of throwing.\n * A single value also starts new rows; a list doesn't, so a new row in a roll-up asks which one.\n */\nexport function scopeFilter(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract\n view: Pick<ResourceView<any, any>, \"definition\">,\n scope: ResourceScope | null | undefined,\n): Readonly<Record<string, ScopeValue | readonly (string | number)[]>> {\n const out: Record<string, ScopeValue | readonly (string | number)[]> = {};\n if (!scope) return out;\n for (const key of (view.definition.scope ?? []) as readonly string[]) {\n const value = Object.hasOwn(scope, key) ? scope[key] : scope[camel(key)];\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") out[key] = value;\n else if (Array.isArray(value) && value.every((v) => typeof v === \"string\" || typeof v === \"number\")) out[key] = value as readonly (string | number)[];\n }\n return Object.freeze(out);\n}\n","// A link's picker (docs/RESOURCE-VIEW.md, \"Links in forms\"): which linked rows it lists. Pure, no\n// React: web's RelationField and native's link picker both send what `filters` returns through\n// the provider, so row-level security still decides what the viewer can pick.\n\nimport type { FilterParam } from \"../provider/types\";\nimport type { FieldReference } from \"../schema/types\";\nimport type { ResourceScope } from \"../hooks/viewer-scope\";\nimport { isDevelopment, reportError } from \"../errors\";\nimport { ViewDefinitionError } from \"./errors\";\nimport { scopeFilter } from \"./scope\";\nimport type { LinkFilter, LinkedView, ResolvedLink, ViewLink } from \"./types\";\n\n// A field name only goes into a request's `sort`, so nothing else rides along in it.\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * A screen's or a picker's filter as provider filters: a single value is `eq`, `null` is\n * `is_null` and a list is `in`.\n */\nexport function filterParams(filter: LinkFilter | null | undefined): FilterParam[] {\n return Object.entries(filter ?? {}).map(([field, value]): FilterParam =>\n value === null\n ? { field, operator: \"is_null\" }\n : Array.isArray(value)\n ? { field, operator: \"in\", value: [...(value as readonly (string | number)[])] }\n : { field, operator: \"eq\", value: value as string | number | boolean },\n );\n}\n\n/** Problems with a `link` as written, for defineView to report with the rest. */\nexport function linkProblems(name: string, link: unknown, reference: FieldReference | undefined): string[] {\n if (link === undefined) return [];\n const where = `fields.${name}.link`;\n if (!reference) return [`${where} is set, but \"${name}\" isn't a link`];\n if (!link || typeof link !== \"object\" || Array.isArray(link)) return [`${where} isn't an object`];\n const l = link as ViewLink;\n const problems: string[] = [];\n if (l.view !== undefined && typeof l.view !== \"function\") problems.push(...linkedViewProblems(where, l.view, reference, l.preset));\n else if (l.view === undefined && l.preset !== undefined) problems.push(`${where}.preset needs a view`);\n if (l.preset !== undefined && typeof l.preset !== \"string\") problems.push(`${where}.preset isn't a preset name`);\n if (l.filter !== undefined && typeof l.filter !== \"function\" && (!l.filter || typeof l.filter !== \"object\" || Array.isArray(l.filter))) {\n problems.push(`${where}.filter isn't a filter or a function`);\n }\n if (\n l.searchFields !== undefined &&\n (!Array.isArray(l.searchFields) || l.searchFields.some((f) => typeof f !== \"string\" || !IDENTIFIER.test(f)))\n ) {\n problems.push(`${where}.searchFields isn't a list of field names`);\n }\n if (l.orderBy === \"view\") {\n if (l.view === undefined) problems.push(`${where}.orderBy \"view\" needs a view`);\n } else if (l.orderBy !== undefined) {\n const o = l.orderBy as { field?: unknown; direction?: unknown } | null;\n if (!o || typeof o !== \"object\" || typeof o.field !== \"string\" || !IDENTIFIER.test(o.field)) {\n problems.push(`${where}.orderBy isn't \"view\" or { field, direction }`);\n } else if (o.direction !== undefined && o.direction !== \"asc\" && o.direction !== \"desc\") {\n problems.push(`${where}.orderBy.direction is \"asc\" or \"desc\", not ${String(o.direction)}`);\n }\n }\n return problems;\n}\n\nfunction linkedViewProblems(where: string, view: unknown, reference: FieldReference, preset: string | undefined): string[] {\n const v = view as LinkedView | null;\n if (!v || typeof v !== \"object\" || typeof v.resource !== \"string\") return [`${where}.view isn't a view`];\n // A view of another resource would list rows the link can't hold.\n if (v.resource !== reference.resource) return [`${where}.view is a view of \"${v.resource}\", but the link points at \"${reference.resource}\"`];\n if (preset !== undefined && !Object.hasOwn(v.definition.presets ?? {}, preset)) {\n return [`${where}.preset \"${preset}\" isn't one of ${v.resource}'s presets`];\n }\n return [];\n}\n\n/**\n * The resolved picker for a link: `owner` is the view's resource (for errors), `labelField` the\n * view field's own. A `view` given as a function is read, and checked, on the first `filters`.\n */\nexport function resolveLink(\n owner: string,\n name: string,\n reference: FieldReference,\n link: ViewLink | undefined,\n labelField: string | undefined,\n): ResolvedLink {\n let linked: LinkedView | undefined;\n let read = false;\n const linkedView = (): LinkedView | undefined => {\n if (read) return linked;\n read = true;\n linked = typeof link?.view === \"function\" ? link.view() : link?.view;\n if (linked && typeof link?.view === \"function\") {\n const problems = linkedViewProblems(`fields.${name}.link`, linked, reference, link.preset);\n if (problems.length) {\n const error = new ViewDefinitionError(owner, problems);\n // Read while a form renders: in development the mistake fails loudly; in production the\n // form still opens, its picker listing the linked resource under row-level security only.\n if (isDevelopment()) throw error;\n reportError(error, { source: \"core:resource-view-link\", tags: { resource: owner } });\n linked = undefined;\n }\n }\n return linked;\n };\n // No `link.view`: Genesis keeps no registry of views or tenant columns by resource, so nothing\n // here can add the linked resource's scope. The data provider's row-level security narrows the\n // list, and the server must refuse a cross-tenant link (docs/RESOURCE-VIEW.md, \"Links in forms\").\n return Object.freeze({\n resource: reference.resource,\n field: reference.field,\n // Read when asked: a view given as a function may not exist yet while this one is defined.\n get labelField() {\n return labelField ?? linkedView()?.labelField;\n },\n ...(link?.searchFields ? { searchFields: Object.freeze([...link.searchFields]) } : {}),\n // Read when asked, like the naming field: `\"view\"` reads a view given as a function.\n get orderBy() {\n const order = link?.orderBy === \"view\" ? linkedView()?.definition.orderBy : link?.orderBy;\n if (!order || typeof order.field !== \"string\" || !IDENTIFIER.test(order.field)) return undefined;\n const nulls = (order as { nulls?: unknown }).nulls;\n return Object.freeze({\n field: order.field,\n direction: order.direction === \"desc\" ? (\"desc\" as const) : (\"asc\" as const),\n ...(nulls === \"first\" || nulls === \"last\" ? { nulls } : {}),\n });\n },\n filters(scope?: ResourceScope | null, values: Readonly<Record<string, unknown>> = {}): FilterParam[] {\n const view = linkedView();\n const preset = view ? view.definition.presets?.[link?.preset ?? \"default\"]?.filter : undefined;\n const own = typeof link?.filter === \"function\" ? link.filter(values) : link?.filter;\n // The linked view's own list rules first, then the link's: a later field wins.\n return filterParams({ ...(view ? scopeFilter(view, scope) : {}), ...(preset as LinkFilter | undefined), ...own });\n },\n });\n}\n","// defineView: a contract plus what it means to people, checked once and frozen (the same rule as\n// genesis-sites' defineSection). Everything a renderer needs is resolved here, so web, native and\n// the extension draw the same labels, columns and form.\n\nimport { NO_VIEWER, type Viewer } from \"../viewer\";\nimport { encodeRecordKey, keyFields } from \"../schema/keys\";\nimport type { GalleryItem } from \"../gallery\";\nimport type { DataRow, FieldSchema, ResourceContract } from \"../schema/types\";\nimport { titleCase } from \"../utils\";\nimport { isTimeZone } from \"../dates\";\nimport { ViewDefinitionError } from \"./errors\";\nimport { linkProblems, resolveLink } from \"./link\";\nimport type {\n Allowed,\n ComputedColumn,\n DisplayHint,\n ResolvedColumn,\n ResolvedFormField,\n ResolvedViewAction,\n ResourceView,\n RowOf,\n RowSummary,\n ViewBoard,\n ViewCalendar,\n ViewDefinition,\n ViewField,\n ViewGallery,\n} from \"./types\";\n\n// Facts a contract may carry from `@genesis` comments. Read loosely so a contract emitted before\n// they existed still works.\ntype FieldFacts = FieldSchema & { readonly readOnly?: boolean; readonly sensitive?: boolean };\ntype ContractFacts = ResourceContract & {\n readonly label?: string;\n readonly labelField?: string;\n readonly noun?: string;\n readonly nounPlural?: string;\n};\n\n// In a file of its own so scope.ts and link.ts can throw it without importing this one.\nexport { ViewDefinitionError } from \"./errors\";\n\n/** The display a field gets when the view doesn't name one. */\nexport function deriveDisplay(field: FieldSchema): DisplayHint {\n if (field.references) return \"relation\";\n switch (field.widget) {\n case \"url\":\n return \"url\";\n case \"email\":\n return \"email\";\n case \"image\":\n return \"image\";\n case \"textarea\":\n return \"longText\";\n case \"date\":\n return \"date\";\n }\n if (field.enumValues?.length) return \"badge\";\n switch (field.type) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"json\":\n return \"json\";\n case \"relation\":\n return \"relation\";\n case \"datetime\":\n return /^date$/i.test(field.dbType ?? \"\") ? \"date\" : \"datetime\";\n }\n return \"text\";\n}\n\n// Plurals whose singular the rules below would get wrong.\nconst SAME_OR_IRREGULAR: Readonly<Record<string, string>> = {\n series: \"series\",\n species: \"species\",\n movies: \"movie\",\n cookies: \"cookie\",\n ties: \"tie\",\n pies: \"pie\",\n people: \"person\",\n};\n\n/** A table name's singular, for the default noun. A wrong guess is fixed with `@genesis {\"noun\"}`. */\nexport function singular(word: string): string {\n const last = word.split(\" \").pop()!;\n const head = word.slice(0, word.length - last.length);\n const lower = last.toLowerCase();\n const one = (s: string) => head + s;\n if (SAME_OR_IRREGULAR[lower]) return one(SAME_OR_IRREGULAR[lower]!);\n if (/[^aeiou]ies$/.test(lower)) return one(`${last.slice(0, -3)}y`);\n // statuses, addresses, boxes, matches, wishes, quizzes\n if (/(?:s|x|z|ch|sh)es$/.test(lower)) return one(last.slice(0, -2));\n if (/(?:ss|us|is)$/.test(lower) || !lower.endsWith(\"s\")) return word;\n return one(last.slice(0, -1));\n}\n\n// Singulars whose plural the rules below would get wrong: the irregulars above, inverted.\nconst PLURAL_OF: Readonly<Record<string, string>> = Object.fromEntries(\n Object.entries(SAME_OR_IRREGULAR).map(([many, one]) => [one, many]),\n);\n\n/** A noun's plural, the inverse of `singular`: entry → entries, box → boxes, person → people. */\nexport function plural(word: string): string {\n const last = word.split(\" \").pop()!;\n const head = word.slice(0, word.length - last.length);\n const lower = last.toLowerCase();\n const many = (s: string) => head + s;\n if (PLURAL_OF[lower]) return many(PLURAL_OF[lower]!);\n if (/[^aeiou]y$/.test(lower)) return many(`${last.slice(0, -1)}ies`);\n if (/(?:s|x|z|ch|sh)$/.test(lower)) return many(`${last}es`);\n return many(`${last}s`);\n}\n\n// The view's own operations (`view.can`): an action can't take their names.\nconst RESERVED_ACTIONS: ReadonlySet<string> = new Set([\"create\", \"update\", \"delete\"]);\n\nconst own = <V>(record: Readonly<Record<string, V>> | undefined, key: string): V | undefined =>\n record && Object.hasOwn(record, key) ? record[key] : undefined;\n\n/** A value in words: its entry in `labels`, else the value in title case (`draft` → \"Draft\"). */\nexport function valueText(labels: Readonly<Record<string, string>> | undefined, value: unknown): string {\n const key = String(value);\n return own(labels, key) ?? titleCase(key);\n}\n\nconst KIND: Readonly<Record<string, string>> = { datetime: \"date or timestamp\", boolean: \"yes/no\", number: \"number\" };\nconst LAYOUTS: readonly string[] = [\"month\", \"weeks\", \"agenda\", \"lanes\"];\n\n/** A calendar block's keys: anything else in one is a mistake `defineView` names. */\nconst CALENDAR_KEYS: readonly string[] = [\n \"field\", \"endField\", \"durationField\", \"durationUnit\", \"allDayField\", \"laneBy\", \"layout\", \"phoneLayout\", \"weeks\", \"weekStartsOn\",\n];\n\n/**\n * What's wrong with a calendar block for these fields, one sentence each (empty when it's fine).\n * `defineView` checks the view's own block with it; a renderer checks a screen's overrides merged\n * over that block with it too, so neither can name a field that isn't there or isn't a date.\n *\n * @stability Beta\n */\nexport function calendarProblems(fields: readonly Pick<FieldSchema, \"name\" | \"type\" | \"array\">[], calendar: Partial<ViewCalendar>): string[] {\n const problems: string[] = [];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const typed = (name: string | undefined, where: string, type: string) => {\n if (name === undefined) return;\n const f = byName.get(name);\n if (!f) problems.push(`${where} names \"${name}\", which isn't a field`);\n else if (f.type !== type || f.array) problems.push(`${where} \"${name}\" isn't a ${KIND[type]} field`);\n };\n typed(calendar.field, \"calendar.field\", \"datetime\");\n typed(calendar.endField, \"calendar.endField\", \"datetime\");\n typed(calendar.durationField, \"calendar.durationField\", \"number\");\n typed(calendar.allDayField, \"calendar.allDayField\", \"boolean\");\n if (calendar.durationUnit !== undefined && ![\"minutes\", \"hours\", \"days\"].includes(calendar.durationUnit)) {\n problems.push(`calendar.durationUnit \"${String(calendar.durationUnit)}\" isn't minutes, hours or days`);\n }\n if (calendar.durationUnit !== undefined && calendar.durationField === undefined) problems.push(\"calendar.durationUnit needs a durationField\");\n if (calendar.laneBy !== undefined && !byName.has(calendar.laneBy)) problems.push(`calendar.laneBy names \"${calendar.laneBy}\", which isn't a field`);\n for (const key of [\"layout\", \"phoneLayout\"] as const) {\n const value = calendar[key];\n if (value !== undefined && !LAYOUTS.includes(value)) problems.push(`calendar.${key} \"${String(value)}\" isn't month, weeks, agenda or lanes`);\n }\n if (calendar.weeks !== undefined && ![1, 2, 3, 4].includes(calendar.weeks)) problems.push(`calendar.weeks is 1 to 4, not ${String(calendar.weeks)}`);\n if (calendar.weekStartsOn !== undefined && calendar.weekStartsOn !== 0 && calendar.weekStartsOn !== 1) {\n problems.push(`calendar.weekStartsOn is 0 (Sunday) or 1 (Monday), not ${String(calendar.weekStartsOn)}`);\n }\n return problems;\n}\n\n/** A board block's keys: anything else in one is a mistake `defineView` names. */\nconst BOARD_KEYS: readonly string[] = [\"field\", \"columns\", \"cardFields\", \"limits\"];\n\n/**\n * The values a board's field can hold, in the contract's order: an enum's choices, or `true`\n * and `false` for a yes/no field. Undefined when the field has no fixed set of values.\n *\n * @stability Beta\n */\nexport function boardChoices(field: Pick<FieldSchema, \"type\" | \"array\" | \"enumValues\"> | undefined): readonly string[] | undefined {\n if (!field || field.array) return undefined;\n if (field.enumValues?.length) return field.enumValues;\n if (field.type === \"boolean\") return [\"true\", \"false\"];\n return undefined;\n}\n\n/** A gallery block's keys: anything else in one is a mistake `defineView` names. */\nconst GALLERY_KEYS: readonly string[] = [\"image\", \"width\", \"height\", \"caption\", \"alt\", \"rowHeight\"];\n\n/**\n * What's wrong with a gallery block for these fields, one sentence each (empty when it's fine).\n *\n * @stability Beta\n */\nexport function galleryProblems(fields: readonly Pick<FieldSchema, \"name\" | \"type\" | \"array\">[], gallery: Partial<ViewGallery>): string[] {\n const problems: string[] = [];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const named = (key: \"image\" | \"width\" | \"height\" | \"caption\" | \"alt\", type?: \"string\" | \"number\") => {\n const name = gallery[key];\n if (name === undefined) return;\n const field = byName.get(name);\n if (!field) problems.push(`gallery.${key} names \"${name}\", which isn't a field`);\n else if (type && (field.type !== type || field.array)) problems.push(`gallery.${key} \"${name}\" is a ${field.array ? \"list\" : field.type}, not a ${type === \"string\" ? \"text\" : \"number\"} field`);\n };\n named(\"image\", \"string\");\n named(\"width\", \"number\");\n named(\"height\", \"number\");\n named(\"caption\");\n named(\"alt\");\n if ((gallery.width === undefined) !== (gallery.height === undefined)) problems.push(\"gallery.width and gallery.height go together: a ratio needs both\");\n const { rowHeight } = gallery;\n if (rowHeight !== undefined && !(typeof rowHeight === \"number\" && Number.isFinite(rowHeight) && rowHeight > 0)) problems.push(`gallery.rowHeight is a height above 0, not ${String(rowHeight)}`);\n return problems;\n}\n\n/**\n * What's wrong with a board block for these fields, one sentence each (empty when it's fine).\n *\n * @stability Beta\n */\nexport function boardProblems(\n fields: readonly Pick<FieldSchema, \"name\" | \"type\" | \"array\" | \"enumValues\">[],\n board: Partial<ViewBoard>,\n): string[] {\n const problems: string[] = [];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const field = board.field === undefined ? undefined : byName.get(board.field);\n if (board.field !== undefined && !field) problems.push(`board.field names \"${board.field}\", which isn't a field`);\n const choices = boardChoices(field);\n if (field && !choices) problems.push(`board.field \"${board.field}\" has no fixed values: use an enum or a yes/no field`);\n if (board.columns !== undefined) {\n if (!Array.isArray(board.columns) || board.columns.length === 0) problems.push(\"board.columns isn't a list of values\");\n else {\n const seen = new Set<string>();\n for (const value of board.columns) {\n if (choices && !choices.includes(value)) problems.push(`board.columns lists \"${String(value)}\", which isn't a value of ${board.field}`);\n if (seen.has(value)) problems.push(`board.columns lists \"${String(value)}\" twice`);\n seen.add(value);\n }\n }\n }\n for (const name of board.cardFields ?? []) {\n if (!byName.has(name)) problems.push(`board.cardFields names \"${name}\", which isn't a field`);\n }\n for (const [value, limit] of Object.entries(board.limits ?? {})) {\n const columns = board.columns ?? choices;\n if (columns && !columns.includes(value)) problems.push(`board.limits has \"${value}\", which isn't one of the board's columns`);\n if (!Number.isInteger(limit) || limit < 1) problems.push(`board.limits.${value} is a whole number of cards, 1 or more, not ${String(limit)}`);\n }\n return problems;\n}\n\n/**\n * Describe what a resource means to people. The result is frozen and platform-neutral:\n *\n * ```ts\n * export const brandsView = defineView(contracts[\"public.brands\"], {\n * fields: { status: { display: \"badge\", tones: { active: \"success\" } } },\n * columns: { default: [\"name\", \"status\", \"created_at\"], compact: [\"name\"] },\n * can: {\n * delete: (row) => (row.is_default ? \"The default brand stays.\" : true),\n * update: (row, viewer) => (row.owner_id === viewer.id ? true : \"Only its owner edits a brand.\"),\n * },\n * actions: [{ name: \"archive\", label: \"Archive\", can: (row) => (row.is_default ? \"The default brand stays.\" : true) }],\n * });\n * ```\n *\n * Throws {@link ViewDefinitionError} when it names something the contract doesn't have, so a\n * renamed column fails at start-up, not as a blank cell.\n */\nexport function defineView<C extends ResourceContract, Row extends DataRow = RowOf<C>>(\n contract: C,\n definition: ViewDefinition<C, Row> = {},\n): ResourceView<C, Row> {\n const facts = contract as ContractFacts;\n const fields = contract.fields as readonly FieldFacts[];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const keys = new Set(keyFields(contract));\n const scope = new Set<string>(definition.scope ?? []);\n // Copied and frozen, so changing the objects passed in can't change the view afterwards.\n const viewFields = Object.freeze(\n Object.fromEntries(\n Object.entries(definition.fields ?? {}).map(([k, v]) => {\n const f = { ...(v as ViewField) };\n // Maps only: anything else is left as given for the checks below to name.\n const map = (m: unknown) => Boolean(m) && typeof m === \"object\" && !Array.isArray(m);\n if (map(f.tones)) f.tones = Object.freeze({ ...f.tones });\n if (map(f.labels)) f.labels = Object.freeze({ ...f.labels });\n return [k, Object.freeze(f)];\n }),\n ),\n ) as Readonly<Record<string, NonNullable<ViewDefinition<C, Row>[\"fields\"]>[never]>>;\n const columnLists = Object.freeze(\n Object.fromEntries(\n Object.entries(definition.columns ?? {}).map(([k, list]) => [\n k,\n Object.freeze((list ?? []).map((c) => (typeof c === \"string\" ? c : Object.freeze({ ...c })))),\n ]),\n ),\n ) as Readonly<Record<string, readonly (string | ComputedColumn<Row>)[] | undefined>>;\n const formItems = Object.freeze(\n (definition.form ?? []).map((item) => (typeof item === \"string\" ? item : Object.freeze({ ...item, fields: Object.freeze([...item.fields]) }))),\n );\n const presets = Object.freeze(\n Object.fromEntries(\n Object.entries(definition.presets ?? {}).map(([k, p]) => [k, Object.freeze({ ...p, ...(p.filter ? { filter: Object.freeze({ ...p.filter }) } : {}) })]),\n ),\n ) as NonNullable<ViewDefinition<C, Row>[\"presets\"]>;\n const actionList = Object.freeze(\n // Names are trimmed, so \" archive\" and \"archive\" are one name.\n (Array.isArray(definition.actions) ? definition.actions : []).map((a) =>\n a && typeof a === \"object\" ? Object.freeze({ ...a, ...(typeof a.name === \"string\" ? { name: a.name.trim() } : {}) }) : a,\n ),\n );\n\n // ── Check every name once ────────────────────────────────────────────\n const problems: string[] = [];\n const known = (name: string, where: string) => {\n if (!byName.has(name)) problems.push(`${where} names \"${name}\", which isn't a field`);\n };\n for (const name of Object.keys(viewFields)) known(name, \"fields\");\n for (const [name, v] of Object.entries(viewFields)) {\n if (v?.labels === undefined) continue;\n if (!v.labels || typeof v.labels !== \"object\" || Array.isArray(v.labels)) {\n problems.push(`fields.${name}.labels isn't a map of values to words`);\n continue;\n }\n const values = byName.get(name)?.enumValues;\n for (const [value, words] of Object.entries(v.labels)) {\n if (typeof words !== \"string\" || !words.trim()) problems.push(`fields.${name}.labels.${value} isn't text`);\n if (values?.length && !values.includes(value)) problems.push(`fields.${name}.labels names \"${value}\", which isn't one of its values`);\n }\n }\n // A clock is \"viewer\", \"scope\" or a zone this runtime knows. Never a quiet fallback: a field\n // drawn on the wrong clock shows the wrong times with nothing to say so.\n for (const [name, v] of Object.entries(viewFields)) {\n const zone: unknown = v?.timeZone;\n if (zone === undefined || zone === \"viewer\" || zone === \"scope\") continue;\n if (zone === \"practice\") {\n problems.push(\n `fields.${name}.timeZone \"practice\" was renamed \"scope\" in genesis-core 2; run \\`genesis codemod genesis-core-2-scope-names\\``,\n );\n } else if (!isTimeZone(zone)) {\n problems.push(`fields.${name}.timeZone \"${String(zone)}\" isn't \"viewer\", \"scope\" or a time zone this runtime knows`);\n }\n }\n for (const [name, v] of Object.entries(viewFields)) {\n if (v?.missingLabel === undefined) continue;\n if (typeof v.missingLabel !== \"string\" || !v.missingLabel.trim()) problems.push(`fields.${name}.missingLabel isn't text`);\n else if (!byName.get(name)?.references) problems.push(`fields.${name}.missingLabel is set, but \"${name}\" isn't a link`);\n }\n for (const [name, v] of Object.entries(viewFields)) problems.push(...linkProblems(name, v?.link, byName.get(name)?.references));\n if (definition.editLinks !== undefined && typeof definition.editLinks !== \"boolean\") problems.push(\"editLinks isn't true or false\");\n for (const [name, v] of Object.entries(viewFields)) {\n if (v?.labelField === undefined) continue;\n if (typeof v.labelField !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(v.labelField)) {\n problems.push(`fields.${name}.labelField isn't a field name`);\n } else if (!byName.get(name)?.references) {\n problems.push(`fields.${name}.labelField is set, but \"${name}\" isn't a link`);\n }\n }\n for (const [preset, list] of Object.entries(columnLists)) {\n const seen = new Set<string>();\n for (const column of list ?? []) {\n const key = typeof column === \"string\" ? column : column.key;\n if (typeof column === \"string\") known(column, `columns.${preset}`);\n else if (byName.has(column.key)) problems.push(`columns.${preset}: computed \"${column.key}\" clashes with a field`);\n if (seen.has(key)) problems.push(`columns.${preset} lists \"${key}\" twice`);\n seen.add(key);\n }\n }\n const formSeen = new Set<string>();\n for (const item of formItems) {\n for (const name of typeof item === \"string\" ? [item] : item.fields) {\n known(name, \"form\");\n if (formSeen.has(name)) problems.push(`form lists \"${name}\" twice`);\n formSeen.add(name);\n }\n }\n for (const name of scope) known(name, \"scope\");\n if (definition.groupBy) known(definition.groupBy, \"groupBy\");\n // A copy, frozen like the other blocks: changing the object passed in can't change the view.\n // Checked as written first: a plain object with a field, and only keys a calendar has.\n const rawCalendar = definition.calendar as unknown;\n let calendar: Readonly<ViewCalendar> | undefined;\n if (rawCalendar !== undefined) {\n if (!rawCalendar || typeof rawCalendar !== \"object\" || Array.isArray(rawCalendar)) {\n problems.push(\"calendar isn't an object\");\n } else {\n for (const key of Object.keys(rawCalendar)) if (!CALENDAR_KEYS.includes(key)) problems.push(`calendar.${key} isn't a calendar setting`);\n if ((rawCalendar as { field?: unknown }).field === undefined) problems.push(\"calendar.field is required\");\n calendar = Object.freeze({ ...(rawCalendar as ViewCalendar) });\n problems.push(...calendarProblems(fields, calendar));\n }\n }\n const rawBoard = definition.board as unknown;\n let board: Readonly<ViewBoard> | undefined;\n if (rawBoard !== undefined) {\n if (!rawBoard || typeof rawBoard !== \"object\" || Array.isArray(rawBoard)) {\n problems.push(\"board isn't an object\");\n } else {\n for (const key of Object.keys(rawBoard)) if (!BOARD_KEYS.includes(key)) problems.push(`board.${key} isn't a board setting`);\n if ((rawBoard as { field?: unknown }).field === undefined) problems.push(\"board.field is required\");\n const given = rawBoard as ViewBoard;\n board = Object.freeze({\n ...given,\n ...(given.columns ? { columns: Object.freeze([...given.columns]) } : {}),\n ...(given.cardFields ? { cardFields: Object.freeze([...given.cardFields]) } : {}),\n ...(given.limits ? { limits: Object.freeze({ ...given.limits }) } : {}),\n });\n problems.push(...boardProblems(fields, board));\n }\n }\n const rawGallery = definition.gallery as unknown;\n let gallery: Readonly<ViewGallery> | undefined;\n if (rawGallery !== undefined) {\n if (!rawGallery || typeof rawGallery !== \"object\" || Array.isArray(rawGallery)) {\n problems.push(\"gallery isn't an object\");\n } else {\n for (const key of Object.keys(rawGallery)) if (!GALLERY_KEYS.includes(key)) problems.push(`gallery.${key} isn't a gallery setting`);\n if ((rawGallery as { image?: unknown }).image === undefined) problems.push(\"gallery.image is required\");\n gallery = Object.freeze({ ...(rawGallery as ViewGallery) });\n problems.push(...galleryProblems(fields, gallery));\n }\n }\n if (definition.orderBy) {\n known(definition.orderBy.field, \"orderBy\");\n const { nulls } = definition.orderBy as { nulls?: unknown };\n if (nulls !== undefined && nulls !== \"first\" && nulls !== \"last\") problems.push(`orderBy.nulls is \"first\" or \"last\", not ${String(nulls)}`);\n }\n for (const [name, preset] of Object.entries(presets)) {\n if (preset.columns && preset.columns !== \"default\" && !own(columnLists, preset.columns)) {\n problems.push(`presets.${name} uses columns \"${preset.columns}\", which isn't defined`);\n }\n for (const field of Object.keys(preset.filter ?? {})) known(field, `presets.${name}.filter`);\n }\n if (facts.labelField) known(facts.labelField, \"the contract's labelField\");\n const actionSeen = new Set<string>();\n if (definition.actions !== undefined && !Array.isArray(definition.actions)) problems.push(\"actions isn't a list\");\n actionList.forEach((action, i) => {\n const where = `actions[${i}]`;\n if (!action || typeof action !== \"object\") {\n problems.push(`${where} isn't an action`);\n return;\n }\n if (typeof action.name !== \"string\" || !action.name.trim()) problems.push(`${where} has no name`);\n else if (RESERVED_ACTIONS.has(action.name)) problems.push(`${where} is named \"${action.name}\", which is reserved for the view's own ${action.name}`);\n else if (actionSeen.has(action.name)) problems.push(`actions lists \"${action.name}\" twice`);\n else actionSeen.add(action.name);\n if (typeof action.label !== \"string\" || !action.label.trim()) problems.push(`${where} has no label`);\n if (action.confirm !== undefined && typeof action.confirm !== \"string\") problems.push(`${where}.confirm isn't text`);\n if (action.description !== undefined && typeof action.description !== \"string\") {\n problems.push(`${where}.description isn't text`);\n }\n if (action.can !== undefined && typeof action.can !== \"function\") problems.push(`${where}.can isn't a function`);\n if (action.destructive !== undefined && typeof action.destructive !== \"boolean\") problems.push(`${where}.destructive isn't true or false`);\n });\n if (problems.length) throw new ViewDefinitionError(contract.name, problems);\n\n // ── Words ────────────────────────────────────────────────────────────\n const copy = definition.copy ?? {};\n const base = contract.name.split(\".\").pop() ?? contract.name;\n const noun = copy.noun ?? facts.noun ?? singular(base.replace(/_/g, \" \"));\n // Several: the view's, the contract's, the noun's plural; with only a derived noun, the\n // contract's label when it reads as a plural (\"People\"), else the table name.\n const labelWords = facts.label?.toLowerCase();\n const nounPlural =\n copy.nounPlural ??\n facts.nounPlural ??\n (copy.noun || facts.noun ? plural(noun) : labelWords && singular(labelWords) !== labelWords ? labelWords : base.replace(/_/g, \" \"));\n const title = copy.title ?? facts.label ?? titleCase(nounPlural);\n const labelField = facts.labelField ?? fields.find((f) => /^(name|title|label|full_name|display_name)$/.test(f.name))?.name;\n\n const label = (name: string): string => own(viewFields, name)?.label ?? byName.get(name)?.label ?? titleCase(name);\n const display = (name: string): DisplayHint => {\n const field = byName.get(name);\n return own(viewFields, name)?.display ?? (field ? deriveDisplay(field) : \"text\");\n };\n const valueLabel = (name: string, value: unknown): string => valueText(own(viewFields, name)?.labels, value);\n // A field the provider says this user can't read is left out everywhere, even when listed.\n const readable = (name: string) => byName.get(name)?.permissions?.read !== false;\n // A link is edited in a form (a picker over the linked rows, never a typed id) only when the view\n // opts in: `fields.<link>.link` (`{}` is enough) or `editLinks: true`. Otherwise it stays\n // read-only, as before 2.x links had pickers; a screen fills a required one (its `filter`,\n // `defaults`). The default flips in 3.0.\n const editLinks = definition.editLinks === true;\n const linkEditable = (f: FieldFacts) => Boolean(f.references) && (editLinks || own(viewFields, f.name)?.link !== undefined);\n // Read-only: what the server fills (generated, `@genesis readonly`), what this user can't change,\n // what the view says, and a link the view hasn't opted in. Scope (tenant) links stay out of\n // forms altogether (below).\n const readOnly = (field: FieldFacts) =>\n Boolean(\n field.generated ||\n field.readOnly ||\n (field.references && !linkEditable(field)) ||\n field.permissions?.update === false ||\n own(viewFields, field.name)?.readOnly,\n );\n // Left out of defaults (a view still lists them on purpose): the key, scope (tenant) columns,\n // sensitive values, and links, whose words cost a lookup.\n const quiet = (f: FieldFacts) => keys.has(f.name) || scope.has(f.name) || Boolean(f.sensitive) || Boolean(f.references);\n // An opted-in link a new row can't do without (no default, never empty) is in a derived form\n // anyway: without it, the form could never save. Other links are in a form when the view lists them.\n const neededLink = (f: FieldFacts) => linkEditable(f) && !f.nullable && !f.optional && !f.hasDefault && !scope.has(f.name);\n\n // ── Columns ──────────────────────────────────────────────────────────\n const defaultColumns: readonly (string | ComputedColumn<Row>)[] =\n own(columnLists, \"default\") ?? fields.filter((f) => !quiet(f)).map((f) => f.name);\n const presetNames = Object.freeze([\"default\", ...Object.keys(columnLists).filter((p) => p !== \"default\")]);\n // One field as a column: its words, hint, tones and guards. Cached, so every list and card shares it.\n const fieldColumns = new Map<string, ResolvedColumn<Row>>();\n const fieldColumn = (column: string): ResolvedColumn<Row> => {\n const cached = fieldColumns.get(column);\n if (cached) return cached;\n const v = own(viewFields, column);\n const resolved: ResolvedColumn<Row> = Object.freeze({\n key: column,\n label: label(column),\n display: display(column),\n field: byName.get(column)!,\n value: (row: Row) => row[column],\n ...(v?.tones ? { tones: v.tones } : {}),\n ...(v?.labels ? { labels: v.labels } : {}),\n ...(v?.labelField ? { labelField: v.labelField } : {}),\n ...(v?.missingLabel ? { missingLabel: v.missingLabel } : {}),\n ...(v?.when ? { when: (row: Row, viewer: Viewer = NO_VIEWER) => v.when!(row, viewer) } : {}),\n ...(v?.timeZone ? { timeZone: v.timeZone } : {}),\n });\n fieldColumns.set(column, resolved);\n return resolved;\n };\n const resolvedColumns = new Map<string, readonly ResolvedColumn<Row>[]>();\n const columns = (preset = \"default\"): readonly ResolvedColumn<Row>[] => {\n const cached = resolvedColumns.get(preset);\n if (cached) return cached;\n const list = preset === \"default\" ? defaultColumns : own(columnLists, preset);\n if (!list) throw new ViewDefinitionError(contract.name, [`no column preset \"${preset}\"`]);\n const out = Object.freeze(\n list.filter((column) => typeof column !== \"string\" || readable(column)).map((column): ResolvedColumn<Row> => {\n if (typeof column !== \"string\") {\n return Object.freeze({ key: column.key, label: column.label, display: column.display ?? \"text\", value: column.value });\n }\n return fieldColumn(column);\n }),\n );\n resolvedColumns.set(preset, out);\n return out;\n };\n\n // ── Form ─────────────────────────────────────────────────────────────\n // One picker per link, made once: what it lists, what names a row, the filters it sends.\n const links = new Map(\n fields\n .filter((f) => linkEditable(f))\n .map((f) => [f.name, resolveLink(contract.name, f.name, f.references!, own(viewFields, f.name)?.link, own(viewFields, f.name)?.labelField)]),\n );\n type Placed = { name: string; section: string | null; sectionTitle: string | null };\n const placed: readonly Placed[] = definition.form\n ? formItems.flatMap((item): Placed[] =>\n typeof item === \"string\"\n ? [{ name: item, section: null, sectionTitle: null }]\n : item.fields.map((name) => ({ name, section: item.section, sectionTitle: item.title ?? titleCase(item.section) })),\n )\n : fields\n // JSON needs an editor of its own, so it is never in a derived form.\n // A key the person types (a code, a slug) stays; one the server fills doesn't.\n .filter(\n (f) =>\n !readOnly(f) &&\n (!quiet(f) || (keys.has(f.name) && !f.hasDefault && !f.sensitive) || (neededLink(f) && !f.sensitive)) &&\n f.type !== \"json\" &&\n !f.array,\n )\n .map((f): Placed => ({ name: f.name, section: null, sectionTitle: null }));\n // A key the server fills (a default) is never sent on create; no key is sent on edit.\n const serverKey = (f: FieldFacts, mode: \"create\" | \"edit\") => keys.has(f.name) && (mode === \"edit\" || Boolean(f.hasDefault));\n const resolvedForms = new Map<string, readonly ResolvedFormField[]>();\n const form = (mode: \"create\" | \"edit\"): readonly ResolvedFormField[] => {\n const cached = resolvedForms.get(mode);\n if (cached) return cached;\n const out = Object.freeze(placed\n .filter(({ name }) => !scope.has(name) && readable(name) && !serverKey(byName.get(name)!, mode))\n .map(({ name, section, sectionTitle }) => {\n const field = byName.get(name)!;\n const v = own(viewFields, name);\n const locked = readOnly(field);\n return Object.freeze({\n field,\n label: label(name),\n display: display(name),\n required: !locked && !field.nullable && !field.optional && (mode === \"edit\" || !field.hasDefault),\n readOnly: locked,\n section,\n sectionTitle,\n ...(v?.max !== undefined ? { max: v.max } : {}),\n ...(v?.autoComplete ? { autoComplete: v.autoComplete } : {}),\n ...(v?.inputMode ? { inputMode: v.inputMode } : {}),\n ...(v?.enterKeyHint ? { enterKeyHint: v.enterKeyHint } : {}),\n ...(v?.labelField ? { labelField: v.labelField } : {}),\n ...(v?.missingLabel ? { missingLabel: v.missingLabel } : {}),\n ...(field.enumValues?.length\n ? { options: Object.freeze(field.enumValues.map((value) => Object.freeze({ value, label: valueLabel(name, value) }))) }\n : {}),\n ...(links.has(name) ? { link: links.get(name)! } : {}),\n ...(v?.visible ? { visible: v.visible } : {}),\n });\n }));\n resolvedForms.set(mode, out);\n return out;\n };\n const writable = (mode: \"create\" | \"edit\") => Object.freeze(form(mode).filter((f) => !f.readOnly).map((f) => f.field.name));\n\n // ── Guards and summary ───────────────────────────────────────────────\n const guards = definition.can ?? {};\n // `can(\"create\", viewer)` and `can(\"update\", row, viewer)`; no viewer means no one (fail closed).\n function can(action: \"create\" | \"update\" | \"delete\", rowOrViewer?: Row | Viewer, maybeViewer?: Viewer): Allowed {\n // Plain JavaScript can pass a row to create: that row would be read as the viewer.\n if (action === \"create\" && maybeViewer !== undefined) throw new TypeError(`[genesis-core] ${contract.name}: can(\"create\", viewer) takes no row`);\n if (action === \"create\") return guards.create?.((rowOrViewer as Viewer | undefined) ?? NO_VIEWER) ?? true;\n const guard = guards[action];\n const row = rowOrViewer as Row | undefined;\n return guard && row ? guard(row, maybeViewer ?? NO_VIEWER) : true;\n }\n const actionGuards = new Map(actionList.map((a) => [a.name, a.can]));\n const resolvedActions: readonly ResolvedViewAction[] = Object.freeze(\n actionList.map((a) =>\n Object.freeze({\n name: a.name,\n label: a.label,\n ...(a.confirm !== undefined ? { confirm: a.confirm } : {}),\n ...(a.description !== undefined ? { description: a.description } : {}),\n ...(a.destructive ? { destructive: true } : {}),\n }),\n ),\n );\n function canAction(name: string, row: Row, viewer: Viewer = NO_VIEWER): Allowed {\n if (!actionGuards.has(name)) throw new ViewDefinitionError(contract.name, [`no action \"${name}\"`]);\n const guard = actionGuards.get(name);\n if (!guard) return true;\n const result: unknown = guard(row, viewer);\n // Only `true` allows; a reason is shown as given; anything else (false, \"\", undefined) refuses.\n if (result === true) return true;\n return typeof result === \"string\" && result.trim() ? result : \"This isn't allowed.\";\n }\n const summary = (row: Row): RowSummary => {\n if (definition.summary) return definition.summary(row);\n const value = labelField ? row[labelField] : undefined;\n return { title: value === null || value === undefined || value === \"\" ? titleCase(noun) : String(value) };\n };\n\n const galleryItem = (row: Row, override?: Partial<ViewGallery>): GalleryItem | undefined => {\n const block = { ...gallery, ...override };\n if (!block.image) return undefined;\n // A row without an image is still a photo: an empty `src`, which the grids draw as a placeholder.\n const image = row[block.image];\n const src = typeof image === \"string\" ? image : \"\";\n const number = (name: string | undefined) => {\n const value = name ? Number(row[name]) : NaN;\n return Number.isFinite(value) && value > 0 ? value : undefined;\n };\n const text = (name: string | undefined) => {\n const value = name ? row[name] : undefined;\n return value === null || value === undefined || value === \"\" ? undefined : String(value);\n };\n const width = number(block.width);\n const height = number(block.height);\n const caption = text(block.caption);\n const alt = text(block.alt) ?? summary(row).title;\n return {\n id: String(encodeRecordKey(contract, row as DataRow)),\n src,\n alt,\n ...(width !== undefined && height !== undefined ? { width, height } : {}),\n ...(caption !== undefined ? { caption } : {}),\n };\n };\n\n return Object.freeze({\n contract,\n definition: Object.freeze({\n ...definition,\n fields: viewFields,\n columns: columnLists,\n presets,\n ...(definition.form ? { form: formItems } : {}),\n ...(definition.scope ? { scope: Object.freeze([...definition.scope]) } : {}),\n ...(definition.actions ? { actions: actionList } : {}),\n ...(calendar ? { calendar } : {}),\n ...(board ? { board } : {}),\n ...(gallery ? { gallery } : {}),\n }) as Readonly<ViewDefinition<C, Row>>,\n resource: contract.name,\n noun,\n nounPlural,\n title,\n labelField,\n presets: presetNames,\n field: (name: string) => byName.get(name),\n column: (name: string) => (byName.has(name) && readable(name) ? fieldColumn(name) : undefined),\n label,\n display,\n valueLabel,\n columns,\n form,\n writable,\n can: can as ResourceView<C, Row>[\"can\"],\n actions: () => resolvedActions,\n canAction,\n summary,\n galleryItem,\n });\n}\n","// rowPicture: what to draw for a row's picture (docs/RESOURCE-VIEW.md, \"summary\"). Pure, so web,\n// native and the extension draw the same image or initials, behind the same URL check.\n\nimport { isSafeUrl } from \"../urls\";\nimport type { RowPicture, RowSummary } from \"./types\";\n\nlet segmenter: Intl.Segmenter | null | undefined;\n\n// The first letter of a word, as a whole character: \"é\" keeps its accent, \"李\" is a letter, and\n// punctuation, digits and emoji never count.\nconst LETTER = /^\\p{L}/u;\nfunction lettersOf(word: string): string[] {\n if (segmenter === undefined) {\n segmenter = typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\" ? new Intl.Segmenter(undefined, { granularity: \"grapheme\" }) : null;\n }\n const parts = segmenter ? Array.from(segmenter.segment(word), (s) => s.segment) : Array.from(word);\n return parts.filter((part) => LETTER.test(part));\n}\nfunction firstLetter(word: string): string {\n return lettersOf(word)[0] ?? \"\";\n}\n\n/**\n * First and last initial of a name, from letters only: \"Ada Lovelace\" → \"AL\", \"Ana-María López\"\n * → \"AL\", \"李 小龙\" → \"李小\", \"Cher\" → \"C\". Empty when the name has no letters (\" \", \"🎉🎉\").\n *\n * `distinct: true` gives a one-word name its first two letters (\"Probe\" → \"Pr\", \"Polish\" → \"Po\"),\n * so people who share an initial still differ in a list. Names of two words or more are unchanged.\n */\nexport function initialsOf(name: string | undefined, options: { distinct?: boolean | undefined } = {}): string {\n const words = (name ?? \"\").trim().split(/\\s+/);\n const letters = words.map(firstLetter).filter(Boolean);\n if (letters.length === 0) return \"\";\n const upper = (l: string) => (l.toUpperCase().length === l.length ? l.toUpperCase() : l);\n if (letters.length === 1 && options.distinct) {\n const word = words.find((w) => firstLetter(w))!;\n const second = lettersOf(word)[1];\n // One character each: \"ß\" stays \"ß\" rather than becoming \"SS\".\n return upper(letters[0]!) + (second ? (second.toLowerCase().length === second.length ? second.toLowerCase() : second) : \"\");\n }\n const pair = letters.length === 1 ? [letters[0]!] : [letters[0]!, letters[letters.length - 1]!];\n // One character each: \"ß\" stays \"ß\" rather than becoming \"SS\".\n return pair.map(upper).join(\"\");\n}\n\n/** An image source: `isSafeUrl`, and only http(s) or a root-relative path (never mailto, tel or `#x`). */\nfunction isImageSrc(src: unknown): src is string {\n if (!isSafeUrl(src)) return false;\n const value = src.trim();\n return value.startsWith(\"/\") || /^https?:/i.test(value);\n}\n\n/**\n * What to draw for a summary's picture:\n *\n * ```ts\n * rowPicture({ title: \"Ada\", image: { src: \"https://…/ada.png\", name: \"Ada Lovelace\" } });\n * // { kind: \"image\", src: \"https://…/ada.png\", alt: \"\", fallback: \"AL\" }\n * rowPicture({ title: \"Ada\", image: { src: \"javascript:x\", name: \"Ada Lovelace\" } });\n * // { kind: \"initials\", text: \"AL\" }\n * ```\n *\n * `null` when the summary has no `image`, or neither a safe `src` nor a `name` with letters.\n */\nexport function rowPicture(summary: RowSummary): RowPicture | null {\n const image = summary.image;\n if (!image) return null;\n const initials = initialsOf(image.name);\n if (isImageSrc(image.src)) return { kind: \"image\", src: image.src.trim(), alt: image.alt ?? \"\", fallback: initials };\n return initials ? { kind: \"initials\", text: initials } : null;\n}\n","// Tree mode: nested records drawn from a flat list. Each row names its parent; the tree is built\n// from the data, never from nested input, so caching and writes stay the flat list's. No React:\n// genesis-ui's `useResourceView` holds the state and draws it, and a native list can reuse it.\n// docs/RESOURCE-VIEW.md, \"Tree mode\".\n\n/**\n * A screen's `tree` (`<ResourceView tree={{ getParentId }} />`): rows nest under the row\n * `getParentId` names. Client-side data only: every row is loaded, and children are never\n * fetched on expand.\n */\nexport interface ResourceTree<T> {\n /** The parent row's key (the same text as the row key), or `null` / `undefined` / `\"\"` for a root. */\n getParentId: (row: T) => string | null | undefined;\n /**\n * Which rows start open (uncontrolled): `true` every parent, a number the parents shallower\n * than that depth (`1` opens the roots), `false` none. Default `false`.\n */\n defaultExpanded?: boolean | number;\n /** The open rows by key, controlled. Leave unset and the screen keeps its own. */\n expanded?: ReadonlySet<string>;\n /** Called with the next open set whenever a row opens or closes. */\n onExpandedChange?: (expanded: Set<string>) => void;\n /** Selecting a row selects its descendants too, and clearing it clears them. Default `false`. */\n cascadeSelect?: boolean;\n}\n\n/** How to read the tree out of flat rows. */\nexport interface TreeOptions<T> {\n /** A row's own id. */\n getId: (row: T) => string;\n /** The parent's id; `null`, `undefined` or `\"\"` for a root. A parent that isn't loaded makes a root too. */\n getParentId: (row: T) => string | null | undefined;\n /**\n * Which nodes are open: their ids, or `\"all\"`. A closed node's descendants aren't returned.\n * While `match` is set, every ancestor of a match is open regardless, so each match shows.\n */\n expanded: ReadonlySet<string> | \"all\";\n /**\n * The filter, when one is active: rows that match it, and their ancestors (so a match keeps its\n * context), are kept; everything else is left out. Undefined: no filter, every row is kept.\n */\n match?: (row: T) => boolean;\n /**\n * The sort, applied within each set of siblings (stable: ties keep the rows' order). Without it,\n * siblings keep the rows' order, so a list sorted beforehand is sorted within siblings too.\n */\n compare?: (a: T, b: T) => number;\n}\n\n/** One visible row of the tree, in display order. */\nexport interface TreeNode<T> {\n row: T;\n id: string;\n /** The parent's id as drawn: `null` for a root (a missing parent, or a broken cycle, counts as none). */\n parentId: string | null;\n /** 0 for a root. */\n depth: number;\n /** Whether it has children among the kept rows (so a toggle makes sense). */\n hasChildren: boolean;\n /** Whether it is open. Always false without children. */\n expanded: boolean;\n /** False for an ancestor kept only as a match's context; true otherwise, and always true without a filter. */\n matched: boolean;\n /** 1-based position among its kept siblings, and how many there are (`aria-posinset`, `aria-setsize`). */\n position: number;\n siblings: number;\n}\n\n/** What {@link treeRows} returns. */\nexport interface TreeResult<T> {\n /** The rows to draw, in order: each parent before its children, siblings in input order. */\n visible: TreeNode<T>[];\n /** Every kept row's node by id, collapsed ones included. */\n nodes: ReadonlyMap<string, TreeNode<T>>;\n /** Every descendant of a node among the kept rows, depth-first, collapsed or not. */\n descendants: (id: string) => string[];\n /** The ids of every kept node that has children: \"expand all\". */\n parents: () => string[];\n}\n\nconst rootish = (parent: string | null | undefined): parent is null | undefined | \"\" => parent == null || parent === \"\";\n\n/**\n * Build the tree from flat rows. Siblings are sorted by `compare`, else keep the rows' order, so\n * either way the sort applies within each set of siblings. A row whose parent isn't among `rows` is a root,\n * and so is a row whose parent would close a cycle (each cycle loses one link). Duplicate ids keep\n * the first row.\n */\nexport function treeRows<T>(rows: readonly T[], options: TreeOptions<T>): TreeResult<T> {\n const { getId, getParentId, expanded, match, compare } = options;\n const byId = new Map<string, T>();\n const order: string[] = [];\n for (const row of rows) {\n const id = getId(row);\n if (byId.has(id)) continue;\n byId.set(id, row);\n order.push(id);\n }\n\n // The parent each row hangs from: absent, unloaded or cyclic parents make a root.\n const parentOf = new Map<string, string | null>();\n const resolving = new Set<string>();\n const resolve = (id: string): string | null => {\n if (parentOf.has(id)) return parentOf.get(id)!;\n const raw = getParentId(byId.get(id)!);\n let parent: string | null = rootish(raw) || raw === id || !byId.has(raw) ? null : raw;\n if (parent !== null) {\n resolving.add(id);\n // Walk up: meeting a row still being resolved means a cycle; break it here.\n if (resolving.has(parent)) parent = null;\n else resolve(parent);\n resolving.delete(id);\n }\n parentOf.set(id, parent);\n return parent;\n };\n for (const id of order) resolve(id);\n // A cycle's other members may have resolved through the broken one before it broke: recheck\n // that every chain ends at a root.\n for (const id of order) {\n const seen = new Set<string>([id]);\n let at = parentOf.get(id) ?? null;\n while (at !== null && !seen.has(at)) {\n seen.add(at);\n at = parentOf.get(at) ?? null;\n }\n if (at !== null) parentOf.set(id, null);\n }\n\n // What the filter keeps: matches, and every ancestor of one.\n let kept: Set<string> | null = null;\n const matched = new Set<string>();\n if (match) {\n kept = new Set();\n for (const id of order) {\n if (!match(byId.get(id)!)) continue;\n matched.add(id);\n for (let at: string | null = id; at !== null && !kept.has(at); at = parentOf.get(at) ?? null) kept.add(at);\n }\n }\n\n const children = new Map<string | null, string[]>();\n for (const id of order) {\n if (kept && !kept.has(id)) continue;\n const parent = parentOf.get(id) ?? null;\n const list = children.get(parent);\n if (list) list.push(id);\n else children.set(parent, [id]);\n }\n // Sort within siblings only: a child never leaves its parent. Array sort is stable.\n if (compare) for (const list of children.values()) list.sort((a, b) => compare(byId.get(a)!, byId.get(b)!));\n\n const isOpen = (id: string) => (match ? true : expanded === \"all\" || expanded.has(id));\n const nodes = new Map<string, TreeNode<T>>();\n const visible: TreeNode<T>[] = [];\n const visit = (parent: string | null, depth: number, shown: boolean) => {\n const ids = children.get(parent) ?? [];\n ids.forEach((id, index) => {\n const hasChildren = (children.get(id)?.length ?? 0) > 0;\n const open = hasChildren && isOpen(id);\n const node: TreeNode<T> = {\n row: byId.get(id)!,\n id,\n parentId: parent,\n depth,\n hasChildren,\n expanded: open,\n matched: match ? matched.has(id) : true,\n position: index + 1,\n siblings: ids.length,\n };\n nodes.set(id, node);\n if (shown) visible.push(node);\n visit(id, depth + 1, shown && open);\n });\n };\n visit(null, 0, true);\n\n const descendants = (id: string): string[] => {\n const out: string[] = [];\n const walk = (at: string) => {\n for (const child of children.get(at) ?? []) {\n out.push(child);\n walk(child);\n }\n };\n walk(id);\n return out;\n };\n const parents = () => [...nodes.values()].filter((n) => n.hasChildren).map((n) => n.id);\n return { visible, nodes, descendants, parents };\n}\n\n/**\n * The open ids a tree starts with: `true` opens every parent, a number opens parents shallower\n * than that depth (`1` opens the roots), `false` or nothing opens none.\n */\nexport function initialExpanded<T>(rows: readonly T[], options: Omit<TreeOptions<T>, \"expanded\" | \"match\">, open: boolean | number | undefined): Set<string> {\n if (!open) return new Set();\n const tree = treeRows(rows, { ...options, expanded: \"all\" });\n const depth = open === true ? Infinity : open;\n return new Set(tree.parents().filter((id) => tree.nodes.get(id)!.depth < depth));\n}\n\n/** The open set with `id` opened or closed: a new set, or the same one when nothing changes. */\nexport function setExpanded(expanded: ReadonlySet<string>, id: string, open: boolean): ReadonlySet<string> {\n if (expanded.has(id) === open) return expanded;\n const next = new Set(expanded);\n if (open) next.add(id);\n else next.delete(id);\n return next;\n}\n\n/**\n * The selection after toggling `id` with cascade: the node and every descendant take the node's\n * new state. Without cascade, use a plain toggle; selection never cascades by default.\n */\nexport function cascadeSelection(selected: ReadonlySet<string>, id: string, descendants: readonly string[]): Set<string> {\n const next = new Set(selected);\n const on = !selected.has(id);\n for (const at of [id, ...descendants]) {\n if (on) next.add(at);\n else next.delete(at);\n }\n return next;\n}\n","// defineRecordView: one record's screen from a view (docs/RESOURCE-VIEW.md, \"RecordView\").\n// A header (the row's summary and the view's actions), sections (a child list, a few settings, or\n// a slot the screen fills) and readiness checks. Checked once and frozen like defineView, with no\n// React, so web and native draw the same screen from it.\n\nimport { encodeRecordKey } from \"../schema/keys\";\nimport type { Identifier } from \"../provider/types\";\nimport { readinessOf, type Readiness } from \"../resource\";\nimport type { DataRow, FieldSchema, ResourceContract } from \"../schema/types\";\nimport { ViewDefinitionError } from \"./errors\";\nimport type { Viewer } from \"../viewer\";\nimport type { Allowed, FieldNameOf, ResolvedFormField, ResourceView, RowOf, ViewTone } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a child list can be any resource\ntype AnyView = ResourceView<ResourceContract<any>, any>;\n\n/** Equality filters for a child list, sent to the server: `{ brand_id: brand.id }`. `null` is \"is empty\". */\nexport type RecordViewFilter = Readonly<Record<string, string | number | boolean | null>>;\n\ninterface SectionBase {\n /** Unique in the record view; the screen's route segment or slot key. */\n id: string;\n label: string;\n}\n\n/** A child list: another view, filtered by this record. */\nexport interface RecordViewListSection<Row extends DataRow = DataRow> extends SectionBase {\n list: { view: AnyView; filter: (row: Row) => RecordViewFilter };\n settings?: never;\n}\n\n/** A few of this record's own fields, edited in place. Each must be in `view.writable(\"edit\")`. */\nexport interface RecordViewSettingsSection<Name extends string = string> extends SectionBase {\n settings: readonly Name[];\n list?: never;\n}\n\n/** A section the screen fills itself, through a slot keyed by `id`. */\nexport interface RecordViewSlotSection extends SectionBase {\n list?: never;\n settings?: never;\n}\n\nexport type RecordViewSection<Row extends DataRow = DataRow, Name extends string = string> =\n | RecordViewListSection<Row>\n | RecordViewSettingsSection<Name>\n | RecordViewSlotSection;\n\n/** One readiness check: \"Has a logo\", ok or not, and why not. */\nexport interface RecordViewReadinessItem {\n /** A stable key for the check; default its position and title. */\n id?: string;\n title: string;\n ok: boolean;\n reason?: string;\n /** Genesis chip tones only. Default `success` when ok, `warning` when not. */\n tone?: ViewTone;\n}\n\n/** What `defineRecordView` accepts. */\nexport interface RecordViewDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> {\n /** The view actions the header offers, by name, in order. Default: every view action. */\n header?: { actions?: readonly string[] };\n sections: readonly RecordViewSection<Row, FieldNameOf<C>>[];\n readiness?: (row: Row) => readonly RecordViewReadinessItem[];\n}\n\n/** A section as a renderer draws it. */\nexport type ResolvedRecordViewSection =\n | { readonly id: string; readonly label: string; readonly kind: \"list\"; readonly view: AnyView }\n | { readonly id: string; readonly label: string; readonly kind: \"settings\"; readonly settings: readonly string[] }\n | { readonly id: string; readonly label: string; readonly kind: \"slot\" };\n\n/** A header action with whether this row allows it. */\nexport interface RecordViewHeaderAction {\n readonly name: string;\n readonly label: string;\n readonly confirm?: string;\n readonly description?: string;\n readonly destructive?: boolean;\n /** `true`, or the view guard's reason. Only narrows what the server allows. */\n readonly allowed: Allowed;\n}\n\n/** The header for one row: the view's summary plus the header's actions. */\nexport interface RecordViewHeader {\n readonly title: string;\n readonly subtitle?: string;\n readonly chips: readonly { label: string; tone?: ViewTone }[];\n readonly actions: readonly RecordViewHeaderAction[];\n}\n\n/** What a screen and its provider add to the header: they only narrow the view's guards. */\nexport interface RecordViewHeaderOptions<Row extends DataRow = DataRow> {\n /** The screen's own rule: `false` hides the action, a sentence refuses it with that reason. */\n can?: (action: string, row: Row) => Allowed | boolean;\n /** Whether anything can run actions here (the screen's `onAction`, or the provider's `runAction`). `false` hides them all. */\n runnable?: boolean;\n /** The action names the provider reports serving (`ResourceSchema.actions`), when it reports them. Others are hidden. */\n served?: readonly string[];\n /** Who is looking (`useViewer()`), for the view's action guards. Without it they get no one. */\n viewer?: Viewer;\n}\n\n/** A readiness check with its tone resolved. */\nexport interface ResolvedReadinessItem {\n /** Stable, for list keys: the check's `id`, or its position and title. */\n readonly key: string;\n readonly title: string;\n readonly ok: boolean;\n readonly reason?: string;\n readonly tone: ViewTone;\n}\n\n/** What `defineRecordView` returns: frozen, with pure helpers for the renderers. */\nexport interface RecordView<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> {\n readonly view: ResourceView<C, Row>;\n readonly sections: readonly ResolvedRecordViewSection[];\n /** The header's action names, in order. */\n readonly headerActions: readonly string[];\n readonly hasReadiness: boolean;\n section(id: string): ResolvedRecordViewSection | undefined;\n /** The record's address for the provider: its key fields (`keyFields`), composite keys encoded. */\n recordId(row: Row): Identifier;\n /**\n * Why settings can't be saved for this row and viewer: the view's `can(\"update\", row, viewer)`\n * reason, or `null` when they can. Renderers then show the settings read-only with the reason.\n * Without a viewer the guard gets no one, so one that needs the viewer locks them.\n */\n settingsLocked(row: Row, viewer?: Viewer): string | null;\n headerFor(row: Row, options?: RecordViewHeaderOptions<Row>): RecordViewHeader;\n /**\n * Settings fields as the view's form resolves them (`view.form(\"edit\")`), in the order listed:\n * one section's, or every settings section's without an id.\n */\n settingsFields(sectionId?: string): readonly ResolvedFormField[];\n /** Only the section's listed keys that `values` has: what a save sends. */\n settingsPatch(sectionId: string, values: Readonly<Record<string, unknown>>): Record<string, unknown>;\n /**\n * A list section's filter for this row. In development, a filter with no key, or a value that\n * isn't a string, number, boolean or null, throws: it would show every child row.\n */\n listFilter(sectionId: string, row: Row): RecordViewFilter;\n /** The readiness checks for this row, tones resolved; empty without `readiness`. */\n readinessFor(row: Row): readonly ResolvedReadinessItem[];\n /**\n * The checks in one chip's terms (genesis-core/resource's `readinessOf`): an unmet `danger`\n * check is a problem, any other unmet check one to look at. `null` without `readiness`. Draw\n * it with `readinessChip`.\n */\n readinessSummary(row: Row): Readiness | null;\n}\n\nconst WORKSPACE = Symbol.for(\"genesis.resource-workspace\");\n/** The reason shown when a guard refuses without one. */\nconst REFUSED = \"This isn't allowed.\";\nconst TONES: ReadonlySet<string> = new Set<ViewTone>([\"success\", \"warning\", \"danger\", \"info\", \"muted\"]);\nconst SECTION_KEYS: ReadonlySet<string> = new Set([\"id\", \"label\", \"list\", \"settings\"]);\nconst dev = () => process.env.NODE_ENV !== \"production\";\n\n/** Why a field can't be a setting edited in place, or null when it can. */\nfunction unsettable(field: FieldSchema | undefined): string | null {\n if (!field) return null;\n const facts = field as FieldSchema & { sensitive?: boolean };\n if (field.type === \"json\") return \"is JSON\";\n if (field.array) return \"is a list\";\n if (field.references || field.type === \"relation\") return \"is a link\";\n if (facts.sensitive) return \"is sensitive\";\n return null;\n}\n\n/**\n * Whether two values are the same as a settings form holds them: 2 and \"2\", and null, undefined\n * and \"\", are the same. A settings section compares an edit with the row through it, so an edit\n * back to the stored value isn't a change (web and native RecordView).\n */\nexport function sameFormValue(a: unknown, b: unknown): boolean {\n const text = (v: unknown) => (v === null || v === undefined ? \"\" : Array.isArray(v) ? v.join(\",\") : String(v));\n return text(a) === text(b);\n}\n\n/** Whether a value is a record view (`defineRecordView`'s result). */\nexport function isRecordView(value: unknown): value is RecordView {\n return typeof value === \"object\" && value !== null && (value as Record<symbol, unknown>)[WORKSPACE] === true;\n}\n\nfunction isView(value: unknown): value is AnyView {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as AnyView).columns === \"function\" &&\n typeof (value as AnyView).resource === \"string\"\n );\n}\n\n/**\n * One record's screen from its view:\n *\n * ```ts\n * export const brandRecordView = defineRecordView(brandsView, {\n * header: { actions: [\"archive\"] },\n * sections: [\n * { id: \"products\", label: \"Products\", list: { view: productsView, filter: (b) => ({ brand_id: b.id }) } },\n * { id: \"settings\", label: \"Settings\", settings: [\"name\", \"website\"] },\n * { id: \"activity\", label: \"Activity\" }, // the screen fills it\n * ],\n * readiness: (b) => [{ title: \"Has a website\", ok: !!b.website, reason: \"Add the website.\" }],\n * });\n * ```\n *\n * Throws {@link ViewDefinitionError} for a settings field the view can't write, a header action\n * the view doesn't define, a repeated section id, or a section that holds another record view.\n */\nexport function defineRecordView<C extends ResourceContract, Row extends DataRow = RowOf<C>>(\n view: ResourceView<C, Row>,\n definition: RecordViewDefinition<C, Row>,\n): RecordView<C, Row> {\n const where = `${view.resource} record view`;\n const problems: string[] = [];\n const writable = new Set(view.writable(\"edit\"));\n const actionNames = new Set(view.actions().map((a) => a.name));\n\n // ── Sections ─────────────────────────────────────────────────────────\n const input = Array.isArray(definition?.sections) ? definition.sections : [];\n if (!Array.isArray(definition?.sections)) problems.push(\"sections isn't a list\");\n else if (input.length === 0) problems.push(\"sections is empty\");\n const ids = new Set<string>();\n const settingsSeen = new Set<string>();\n const sections: ResolvedRecordViewSection[] = [];\n const filters = new Map<string, (row: Row) => RecordViewFilter>();\n input.forEach((raw, i) => {\n const at = `sections[${i}]`;\n if (!raw || typeof raw !== \"object\") {\n problems.push(`${at} isn't a section`);\n return;\n }\n const s = raw as RecordViewSection<Row> & Record<string, unknown>;\n const name = typeof s.id === \"string\" && s.id.trim() ? s.id : undefined;\n if (!name) problems.push(`${at} has no id`);\n else if (ids.has(name)) problems.push(`sections lists \"${name}\" twice`);\n else ids.add(name);\n const label = `sections.${name ?? i}`;\n if (typeof s.label !== \"string\" || !s.label.trim()) problems.push(`${label} has no label`);\n if (isRecordView(s) || \"sections\" in s || \"workspace\" in s) {\n problems.push(`${label} holds a record view; sections don't nest`);\n return;\n }\n const unknown = Object.keys(s).filter((k) => !SECTION_KEYS.has(k));\n if (unknown.length) problems.push(`${label} has ${unknown.map((k) => `\"${k}\"`).join(\", \")}, which isn't a section key (id, label, list, settings)`);\n const hasList = s.list !== undefined;\n const hasSettings = s.settings !== undefined;\n if (hasList && hasSettings) {\n problems.push(`${label} has both list and settings; a section has one`);\n return;\n }\n if (hasList) {\n const list = s.list as { view?: unknown; filter?: unknown };\n if (isRecordView(list?.view)) problems.push(`${label}.list.view is a record view; sections don't nest`);\n else if (!isView(list?.view)) problems.push(`${label}.list.view isn't a view`);\n if (typeof list?.filter !== \"function\") problems.push(`${label}.list.filter isn't a function`);\n if (name && isView(list?.view) && !isRecordView(list.view) && typeof list.filter === \"function\") {\n filters.set(name, list.filter as (row: Row) => RecordViewFilter);\n sections.push(Object.freeze({ id: name, label: s.label, kind: \"list\", view: list.view }));\n }\n return;\n }\n if (hasSettings) {\n if (!Array.isArray(s.settings)) {\n problems.push(`${label}.settings isn't a list`);\n return;\n }\n if (s.settings.length === 0) problems.push(`${label}.settings lists no fields`);\n for (const field of s.settings as readonly string[]) {\n const why = unsettable(view.field(field));\n if (why) problems.push(`${label}.settings names \"${field}\", which ${why}; it needs an editor of its own`);\n else if (!writable.has(field)) problems.push(`${label}.settings names \"${field}\", which the view can't write on edit`);\n if (settingsSeen.has(field)) problems.push(`settings lists \"${field}\" twice`);\n settingsSeen.add(field);\n }\n if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: \"settings\", settings: Object.freeze((s.settings as readonly string[]).map(String)) }));\n return;\n }\n if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: \"slot\" }));\n });\n\n // ── Header and readiness ─────────────────────────────────────────────\n const requested = definition?.header?.actions;\n if (requested !== undefined && !Array.isArray(requested)) problems.push(\"header.actions isn't a list\");\n const headerActions = Object.freeze(\n Array.isArray(requested) ? [...requested] : view.actions().map((a) => a.name),\n );\n const headerSeen = new Set<string>();\n for (const name of headerActions) {\n if (!actionNames.has(name)) problems.push(`header.actions names \"${name}\", which isn't a view action`);\n if (headerSeen.has(name)) problems.push(`header.actions lists \"${name}\" twice`);\n headerSeen.add(name);\n }\n if (definition?.readiness !== undefined && typeof definition.readiness !== \"function\") {\n problems.push(\"readiness isn't a function\");\n }\n if (problems.length) throw new ViewDefinitionError(where, problems);\n\n const frozenSections = Object.freeze(sections);\n const byId = new Map(frozenSections.map((s) => [s.id, s]));\n const actionByName = new Map(view.actions().map((a) => [a.name, a]));\n const readiness = definition.readiness;\n\n const settingsOf = (sectionId: string): readonly string[] => {\n const s = byId.get(sectionId);\n if (!s || s.kind !== \"settings\") throw new ViewDefinitionError(where, [`no settings section \"${sectionId}\"`]);\n return s.settings;\n };\n const resolvedSettings = new Map<string, readonly ResolvedFormField[]>();\n const settingsFields = (sectionId?: string): readonly ResolvedFormField[] => {\n const key = sectionId ?? \"\";\n const cached = resolvedSettings.get(key);\n if (cached) return cached;\n const names =\n sectionId === undefined\n ? frozenSections.flatMap((s) => (s.kind === \"settings\" ? s.settings : []))\n : settingsOf(sectionId);\n const form = new Map(view.form(\"edit\").map((f) => [f.field.name, f]));\n const out = Object.freeze(names.map((n) => form.get(n)).filter((f): f is ResolvedFormField => f !== undefined));\n resolvedSettings.set(key, out);\n return out;\n };\n\n const headerFor = (row: Row, options: RecordViewHeaderOptions<Row> = {}): RecordViewHeader => {\n const summary = view.summary(row);\n const served = options.served ? new Set(options.served) : null;\n const actions: RecordViewHeaderAction[] = [];\n if (options.runnable !== false) {\n for (const name of headerActions) {\n if (served && !served.has(name)) continue;\n const own = options.can?.(name, row);\n if (own === false) continue;\n // Guards only narrow: the screen's refusal wins, then the view's.\n const allowed: Allowed = typeof own === \"string\" ? own || REFUSED : view.canAction(name, row, options.viewer);\n actions.push(Object.freeze({ ...actionByName.get(name)!, allowed }));\n }\n }\n return Object.freeze({\n title: summary.title,\n ...(summary.subtitle !== undefined ? { subtitle: summary.subtitle } : {}),\n chips: Object.freeze([...(summary.chips ?? [])]),\n actions: Object.freeze(actions),\n });\n };\n\n const readinessFor = (row: Row): readonly ResolvedReadinessItem[] => {\n if (!readiness) return Object.freeze([]);\n return Object.freeze(\n readiness(row).map((item, i) => {\n let tone = item.tone ?? (item.ok ? \"success\" : \"warning\");\n if (!TONES.has(tone)) {\n if (dev()) console.warn(`[genesis-core] ${where}: readiness \"${item.title}\" has tone \"${String(tone)}\", which isn't a chip tone; showing it muted.`);\n tone = \"muted\";\n }\n return Object.freeze({\n key: item.id ?? `${i}:${item.title}`,\n title: item.title,\n ok: Boolean(item.ok),\n ...(item.reason !== undefined ? { reason: item.reason } : {}),\n tone,\n });\n }),\n );\n };\n\n const readinessSummary = (row: Row): Readiness | null =>\n readiness\n ? readinessOf(\n readinessFor(row)\n .filter((r) => !r.ok)\n .map((r) => ({ level: r.tone === \"danger\" ? (\"error\" as const) : (\"warning\" as const) })),\n )\n : null;\n\n return Object.freeze({\n [WORKSPACE]: true,\n view,\n sections: frozenSections,\n headerActions,\n hasReadiness: Boolean(readiness),\n section: (id: string) => byId.get(id),\n recordId: (row: Row) => encodeRecordKey(view.contract, row),\n settingsLocked: (row: Row, viewer?: Viewer) => {\n const allowed = view.can(\"update\", row, viewer);\n return allowed === true ? null : typeof allowed === \"string\" && allowed.trim() ? allowed : REFUSED;\n },\n headerFor,\n settingsFields,\n settingsPatch: (sectionId: string, values: Readonly<Record<string, unknown>>) => {\n const patch: Record<string, unknown> = {};\n for (const name of settingsOf(sectionId)) if (Object.hasOwn(values, name)) patch[name] = values[name];\n return patch;\n },\n listFilter: (sectionId: string, row: Row) => {\n const filter = filters.get(sectionId);\n if (!filter) throw new ViewDefinitionError(where, [`no list section \"${sectionId}\"`]);\n const out = filter(row);\n if (dev()) {\n const entries = out && typeof out === \"object\" ? Object.entries(out) : [];\n const bad = entries.filter(([, v]) => !(v === null || typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\"));\n if (entries.length === 0 || bad.length) {\n throw new ViewDefinitionError(where, [\n entries.length === 0\n ? `sections.${sectionId}.list.filter gave no keys, which would list every row`\n : `sections.${sectionId}.list.filter gives ${bad.map(([k]) => `\"${k}\"`).join(\", \")} no single value`,\n ]);\n }\n }\n return Object.freeze({ ...out });\n },\n readinessFor,\n readinessSummary,\n }) as RecordView<C, Row>;\n}\n\n// The names before record views were called record views (\"workspace\" now means where the viewer\n// is working: docs/adr/0004-workspaces.md). Kept for one minor release.\n\n/** @deprecated Renamed `defineRecordView`. */\nexport const defineWorkspace = defineRecordView;\n/** @deprecated Renamed `isRecordView`. */\nexport const isWorkspace = isRecordView;\n/** @deprecated Renamed `RecordView`. */\nexport type ResourceWorkspace<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> = RecordView<C, Row>;\n/** @deprecated Renamed `RecordViewDefinition`. */\nexport type WorkspaceDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> = RecordViewDefinition<C, Row>;\n/** @deprecated Renamed `RecordViewSection`. */\nexport type WorkspaceSection<Row extends DataRow = DataRow, Name extends string = string> = RecordViewSection<Row, Name>;\n/** @deprecated Renamed `RecordViewHeaderAction`. */\nexport type WorkspaceHeaderAction = RecordViewHeaderAction;\n"]}
1
+ {"version":3,"sources":["../../src/resource-view/errors.ts","../../src/resource-view/scope.ts","../../src/resource-view/link.ts","../../src/resource-view/types.ts","../../src/resource-view/define-view.ts","../../src/resource-view/picture.ts","../../src/resource-view/group.ts","../../src/resource-view/tree.ts","../../src/resource-view/record-view.ts","../../src/resource-view/widget.ts"],"names":["own"],"mappings":";;;;;;;;;;;;;AAGO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EACpC,QAAA;AAAA,EACT,WAAA,CAAY,UAAkB,QAAA,EAA6B;AACzD,IAAA,KAAA,CAAM,cAAc,QAAQ,CAAA,GAAA,EAAM,SAAS,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AACvD,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAAA,EAClB;AACF;;;ACFA,IAAM,KAAA,GAAQ,CAAC,GAAA,KAAgB,GAAA,CAAI,OAAA,CAAQ,cAAA,EAAgB,CAAC,CAAA,EAAG,CAAA,KAAc,CAAA,CAAE,WAAA,EAAa,CAAA;AAcrF,SAAS,WAAA,CAEd,MACA,KAAA,EACsC;AACtC,EAAA,MAAM,MAAkC,EAAC;AACzC,EAAA,MAAM,UAAoB,EAAC;AAC3B,EAAA,KAAA,MAAW,GAAA,IAAQ,IAAA,CAAK,UAAA,CAAW,KAAA,IAAS,EAAC,EAAyB;AACpE,IAAA,MAAM,KAAA,GAAQ,KAAA,IAAS,MAAA,CAAO,MAAA,CAAO,KAAA,EAAO,GAAG,CAAA,GAAI,KAAA,CAAM,GAAG,CAAA,GAAI,KAAA,GAAQ,KAAA,CAAM,GAAG,CAAC,CAAA;AAClF,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,KA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,MAAA,IAAa,EAAE,IAAA,GAAO,CAAA,CAAA,EAAI,OAAO,IAAA;AACxG,EAAA,OAAO,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAA,GAAQ,IAAI,CAAA;AACjC","file":"index.js","sourcesContent":["// The error defineView and its helpers throw for a view that doesn't fit its contract.\n\n/** A view that names a field, preset or section its contract doesn't have. */\nexport class ViewDefinitionError extends Error {\n readonly problems: readonly string[];\n constructor(resource: string, problems: readonly string[]) {\n super(`defineView(${resource}): ${problems.join(\"; \")}`);\n this.name = \"ViewDefinitionError\";\n this.problems = problems;\n }\n}\n","// scopeValues: a view's scope keys, read from ViewerScope's `scope`, as a screen's `filter`.\n\nimport type { ResourceScope } from \"../hooks/viewer-scope\";\nimport { ViewDefinitionError } from \"./errors\";\nimport type { ResourceView } from \"./types\";\n\ntype ScopeValue = string | number | boolean | null;\n\nconst camel = (key: string) => key.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n\n/**\n * The view's declared scope keys with their values from the viewer's scope, ready to pass as a\n * screen's `filter`: `scope: [\"league_id\"]` reads `scope.league_id`, then `scope.leagueId`.\n *\n * ```tsx\n * <ResourceView view={brandsView} filter={scopeValues(brandsView, useViewerScope().scope)} />\n * ```\n *\n * In development a declared key with no single value (missing, `undefined`, or a list) throws\n * {@link ViewDefinitionError}, so a screen mounted outside its scope fails loudly. In production\n * it is left out; row-level security still decides what the viewer reads.\n */\nexport function scopeValues(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract\n view: Pick<ResourceView<any, any>, \"resource\" | \"definition\">,\n scope: ResourceScope | null | undefined,\n): Readonly<Record<string, ScopeValue>> {\n const out: Record<string, ScopeValue> = {};\n const missing: string[] = [];\n for (const key of (view.definition.scope ?? []) as readonly string[]) {\n const value = scope && Object.hasOwn(scope, key) ? scope[key] : scope?.[camel(key)];\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") out[key] = value;\n else missing.push(key);\n }\n if (missing.length && process.env.NODE_ENV !== \"production\") {\n throw new ViewDefinitionError(\n view.resource,\n missing.map((key) => `scope \"${key}\" has no single value in ViewerScope's scope`),\n );\n }\n return Object.freeze(out);\n}\n\n/**\n * The view's scope keys as a list filter, the way `ResourceView` applies them itself: like\n * {@link scopeValues}, but a list (`{ orgId: [\"o1\", \"o2\"] }`, a roll-up across organizations)\n * filters to any of its values, and a key the scope doesn't set is left out instead of throwing.\n * A single value also starts new rows; a list doesn't, so a new row in a roll-up asks which one.\n */\nexport function scopeFilter(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract\n view: Pick<ResourceView<any, any>, \"definition\">,\n scope: ResourceScope | null | undefined,\n): Readonly<Record<string, ScopeValue | readonly (string | number)[]>> {\n const out: Record<string, ScopeValue | readonly (string | number)[]> = {};\n if (!scope) return out;\n for (const key of (view.definition.scope ?? []) as readonly string[]) {\n const value = Object.hasOwn(scope, key) ? scope[key] : scope[camel(key)];\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") out[key] = value;\n else if (Array.isArray(value) && value.every((v) => typeof v === \"string\" || typeof v === \"number\")) out[key] = value as readonly (string | number)[];\n }\n return Object.freeze(out);\n}\n","// A link's picker (docs/RESOURCE-VIEW.md, \"Links in forms\"): which linked rows it lists. Pure, no\n// React: web's RelationField and native's link picker both send what `filters` returns through\n// the provider, so row-level security still decides what the viewer can pick.\n\nimport type { FilterParam } from \"../provider/types\";\nimport type { FieldReference } from \"../schema/types\";\nimport type { ResourceScope } from \"../hooks/viewer-scope\";\nimport { isDevelopment, reportError } from \"../errors\";\nimport { ViewDefinitionError } from \"./errors\";\nimport { scopeFilter } from \"./scope\";\nimport type { LinkFilter, LinkedView, ResolvedLink, ViewLink } from \"./types\";\n\n// A field name only goes into a request's `sort`, so nothing else rides along in it.\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * A screen's or a picker's filter as provider filters: a single value is `eq`, `null` is\n * `is_null` and a list is `in`.\n */\nexport function filterParams(filter: LinkFilter | null | undefined): FilterParam[] {\n return Object.entries(filter ?? {}).map(([field, value]): FilterParam =>\n value === null\n ? { field, operator: \"is_null\" }\n : Array.isArray(value)\n ? { field, operator: \"in\", value: [...(value as readonly (string | number)[])] }\n : { field, operator: \"eq\", value: value as string | number | boolean },\n );\n}\n\n/** Problems with a `link` as written, for defineView to report with the rest. */\nexport function linkProblems(name: string, link: unknown, reference: FieldReference | undefined): string[] {\n if (link === undefined) return [];\n const where = `fields.${name}.link`;\n if (!reference) return [`${where} is set, but \"${name}\" isn't a link`];\n if (!link || typeof link !== \"object\" || Array.isArray(link)) return [`${where} isn't an object`];\n const l = link as ViewLink;\n const problems: string[] = [];\n if (l.view !== undefined && typeof l.view !== \"function\") problems.push(...linkedViewProblems(where, l.view, reference, l.preset));\n else if (l.view === undefined && l.preset !== undefined) problems.push(`${where}.preset needs a view`);\n if (l.preset !== undefined && typeof l.preset !== \"string\") problems.push(`${where}.preset isn't a preset name`);\n if (l.filter !== undefined && typeof l.filter !== \"function\" && (!l.filter || typeof l.filter !== \"object\" || Array.isArray(l.filter))) {\n problems.push(`${where}.filter isn't a filter or a function`);\n }\n if (\n l.searchFields !== undefined &&\n (!Array.isArray(l.searchFields) || l.searchFields.some((f) => typeof f !== \"string\" || !IDENTIFIER.test(f)))\n ) {\n problems.push(`${where}.searchFields isn't a list of field names`);\n }\n if (l.orderBy === \"view\") {\n if (l.view === undefined) problems.push(`${where}.orderBy \"view\" needs a view`);\n } else if (l.orderBy !== undefined) {\n const o = l.orderBy as { field?: unknown; direction?: unknown } | null;\n if (!o || typeof o !== \"object\" || typeof o.field !== \"string\" || !IDENTIFIER.test(o.field)) {\n problems.push(`${where}.orderBy isn't \"view\" or { field, direction }`);\n } else if (o.direction !== undefined && o.direction !== \"asc\" && o.direction !== \"desc\") {\n problems.push(`${where}.orderBy.direction is \"asc\" or \"desc\", not ${String(o.direction)}`);\n }\n }\n return problems;\n}\n\nfunction linkedViewProblems(where: string, view: unknown, reference: FieldReference, preset: string | undefined): string[] {\n const v = view as LinkedView | null;\n if (!v || typeof v !== \"object\" || typeof v.resource !== \"string\") return [`${where}.view isn't a view`];\n // A view of another resource would list rows the link can't hold.\n if (v.resource !== reference.resource) return [`${where}.view is a view of \"${v.resource}\", but the link points at \"${reference.resource}\"`];\n if (preset !== undefined && !Object.hasOwn(v.definition.presets ?? {}, preset)) {\n return [`${where}.preset \"${preset}\" isn't one of ${v.resource}'s presets`];\n }\n return [];\n}\n\n/**\n * The resolved picker for a link: `owner` is the view's resource (for errors), `labelField` the\n * view field's own. A `view` given as a function is read, and checked, on the first `filters`.\n */\nexport function resolveLink(\n owner: string,\n name: string,\n reference: FieldReference,\n link: ViewLink | undefined,\n labelField: string | undefined,\n): ResolvedLink {\n let linked: LinkedView | undefined;\n let read = false;\n const linkedView = (): LinkedView | undefined => {\n if (read) return linked;\n read = true;\n linked = typeof link?.view === \"function\" ? link.view() : link?.view;\n if (linked && typeof link?.view === \"function\") {\n const problems = linkedViewProblems(`fields.${name}.link`, linked, reference, link.preset);\n if (problems.length) {\n const error = new ViewDefinitionError(owner, problems);\n // Read while a form renders: in development the mistake fails loudly; in production the\n // form still opens, its picker listing the linked resource under row-level security only.\n if (isDevelopment()) throw error;\n reportError(error, { source: \"core:resource-view-link\", tags: { resource: owner } });\n linked = undefined;\n }\n }\n return linked;\n };\n // No `link.view`: Genesis keeps no registry of views or tenant columns by resource, so nothing\n // here can add the linked resource's scope. The data provider's row-level security narrows the\n // list, and the server must refuse a cross-tenant link (docs/RESOURCE-VIEW.md, \"Links in forms\").\n return Object.freeze({\n resource: reference.resource,\n field: reference.field,\n // Read when asked: a view given as a function may not exist yet while this one is defined.\n get labelField() {\n return labelField ?? linkedView()?.labelField;\n },\n ...(link?.searchFields ? { searchFields: Object.freeze([...link.searchFields]) } : {}),\n // Read when asked, like the naming field: `\"view\"` reads a view given as a function.\n get orderBy() {\n const order = link?.orderBy === \"view\" ? linkedView()?.definition.orderBy : link?.orderBy;\n if (!order || typeof order.field !== \"string\" || !IDENTIFIER.test(order.field)) return undefined;\n const nulls = (order as { nulls?: unknown }).nulls;\n return Object.freeze({\n field: order.field,\n direction: order.direction === \"desc\" ? (\"desc\" as const) : (\"asc\" as const),\n ...(nulls === \"first\" || nulls === \"last\" ? { nulls } : {}),\n });\n },\n filters(scope?: ResourceScope | null, values: Readonly<Record<string, unknown>> = {}): FilterParam[] {\n const view = linkedView();\n const preset = view ? view.definition.presets?.[link?.preset ?? \"default\"]?.filter : undefined;\n const own = typeof link?.filter === \"function\" ? link.filter(values) : link?.filter;\n // The linked view's own list rules first, then the link's: a later field wins.\n return filterParams({ ...(view ? scopeFilter(view, scope) : {}), ...(preset as LinkFilter | undefined), ...own });\n },\n });\n}\n","// What a resource means to people (docs/RESOURCE-VIEW.md, \"View\"). Types only: no React, no\n// DOM, so web, native and the extension all import the same view.\n\nimport type { GalleryItem } from \"../gallery\";\nimport type { ChipTone } from \"../resource/status\";\nimport type { DataRow, FieldSchema, ResourceContract, RowAction, RowOf } from \"../schema/types\";\nimport type { Viewer } from \"../viewer\";\nimport type { FilterParam } from \"../provider/types\";\nimport type { ResourceScope } from \"../hooks/viewer-scope\";\n\nexport type { RowOf, Viewer };\n\n/** A chip's colour: the one Genesis tone set (`ChipTone`, genesis-core/resource). */\nexport type ViewTone = ChipTone;\n\n/**\n * How a value is shown. A hint: each platform registers one renderer per hint, so the shared view\n * never imports a platform. Derived from the field when the view doesn't say.\n */\nexport type DisplayHint =\n | \"text\"\n | \"longText\"\n | \"number\"\n | \"currency\"\n | \"percent\"\n | \"boolean\"\n | \"badge\"\n | \"date\"\n | \"datetime\"\n | \"relation\"\n | \"url\"\n | \"email\"\n | \"image\"\n | \"json\";\n\n/** The field names a contract declares; `string` when the contract isn't a literal. */\nexport type FieldNameOf<C extends ResourceContract> = C[\"fields\"][number][\"name\"];\n\n/** What a view says about one field. Every key is optional; the contract fills the rest. */\nexport interface ViewField<Row extends DataRow = DataRow> {\n /** The field's label. Default: the contract's label, then the name in title case. */\n label?: string;\n display?: DisplayHint;\n /** A badge's tone per value, e.g. `{ active: \"success\", archived: \"muted\" }`. */\n tones?: Readonly<Record<string, ViewTone>>;\n /**\n * The words for a value, e.g. `{ draft: \"In progress\" }`: badges, form choices, group titles.\n * A value without one shows in title case. Keys must be the field's enum values, if it has any.\n */\n labels?: Readonly<Record<string, string>>;\n /**\n * For a link (`relation`): the linked row's field that names it, e.g. `\"full_name\"`. Default:\n * the linked resource's `labelField` (`provider.describe`), else a `name`/`title`-like field.\n */\n labelField?: string;\n /**\n * For a link: the words when the linked row is hidden from this viewer or gone, e.g.\n * `\"Someone you can't see\"`. Default: the catalogue's `common.hiddenLink`. Never the raw id.\n */\n missingLabel?: string;\n /**\n * For a link: edit it in the view's forms with a picker, and how the picker lists the rows it\n * can point at. Setting it (`{}` is enough) opts the link in; without it (or the view's\n * `editLinks`) a link stays read-only. `view` narrows it to the linked view's rules (its scope\n * and default filter); `filter` adds more.\n */\n link?: ViewLink;\n /** Longest text a form accepts. Feeds the derived validation. */\n max?: number;\n /**\n * In a form: the browser's autofill token (`email`, `tel`, `given-name`, `one-time-code`,\n * `off`, ...). Unset, the input carries no `autocomplete` attribute and gets no token from its\n * type, so the browser applies its own heuristics (it may still offer to fill it). Set a token\n * where the form is about the viewer, and `off` on a form about someone else (an admin editing\n * a member) to ask the browser not to fill in the person at the keyboard.\n */\n autoComplete?: string;\n /** In a form: which on-screen keyboard a phone shows. Unset, it follows the field's type. */\n inputMode?: \"none\" | \"text\" | \"decimal\" | \"numeric\" | \"tel\" | \"search\" | \"email\" | \"url\";\n /** In a form: the label on the keyboard's Return key (`next`, `done`, `go`, `search`, `send`). */\n enterKeyHint?: \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"search\" | \"send\";\n /** Shown read-only even where the server would accept a write. Never widens. */\n readOnly?: boolean;\n /**\n * Show the cell only when the row (and the viewer) say so: for values a server function masks\n * by policy (`(row) => row.author_visible`). The masking itself is the server's. It hides\n * table cells and the peek only: not workspace settings, an edit form's prefilled values, a\n * view's `summary` or header, or sorting and searching on the column.\n */\n when?: (row: Row, viewer: Viewer) => boolean;\n /** In a form: show the field only while this holds for the form's values. A hidden field isn't saved. */\n visible?: (values: Readonly<Record<string, unknown>>) => boolean;\n /**\n * A timestamp's clock: the viewer's (default), the scope's (the zone of whatever the screen is\n * scoped to: ViewerScope's `scopeTimeZone`, or NativeResourceView's prop), or a fixed IANA zone.\n * Closed: any other word (the removed `\"practice\"`) is a type error, and `defineView` refuses a\n * zone the runtime doesn't know.\n */\n timeZone?: ViewTimeZone;\n}\n\n/**\n * A picker's filter: equality per field. `null` is \"is empty\", a list is \"any of\". Sent to the\n * server with the list request, never applied to loaded rows.\n */\nexport type LinkFilter = Readonly<Record<string, string | number | boolean | null | readonly (string | number)[]>>;\n\n/** The parts of the linked resource's view a picker reads. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract and row\nexport type LinkedView = Pick<ResourceView<any, any>, \"resource\" | \"definition\" | \"labelField\">;\n\n/**\n * How a link's picker lists the linked rows (`fields.owner_id.link`). The list always goes through\n * the provider, so row-level security decides what the viewer can pick; these only narrow it.\n */\nexport interface ViewLink {\n /**\n * The linked resource's view. Its `scope` keys (read from the viewer's scope, as its own lists\n * do), its `default` preset's filter (or `preset`'s) and its `labelField` apply to the picker.\n * A function for two views that link each other (`() => usersView`).\n */\n view?: LinkedView | (() => LinkedView);\n /** One of the linked view's presets whose filter the picker uses. Default: its `default` preset. */\n preset?: string;\n /**\n * More filters: fixed, or from the form's values, for a picker that follows another field\n * (`(values) => ({ project_id: values.project_id })`, the tasks of the chosen project).\n */\n filter?: LinkFilter | ((values: Readonly<Record<string, unknown>>) => LinkFilter);\n /** The linked fields a search matches. Default: the naming field (`labelField`). */\n searchFields?: readonly string[];\n /**\n * The order the picker lists rows in. Default: by the naming field, then the key. `\"view\"`\n * uses the linked view's own `orderBy` (a `position` its list is sorted by) and needs `view`;\n * a linked view without one keeps the default. `{ field, direction }` names a linked field.\n */\n orderBy?: \"view\" | LinkOrder;\n}\n\n/** A picker's order: a field of the linked resource, ascending unless it says so. */\nexport interface LinkOrder {\n field: string;\n direction?: \"asc\" | \"desc\";\n /** Where rows with no value go. Unset, the store decides. */\n nulls?: \"first\" | \"last\";\n}\n\n/** A link's picker, resolved: what to list, what names a row, and the filters to send. */\nexport interface ResolvedLink {\n /** The linked resource. */\n resource: string;\n /** The linked field the link stores (its key, usually `id`). */\n field: string;\n /** The linked field that names a row: the view field's, else the linked view's. Undefined: the provider's `describe`. */\n readonly labelField: string | undefined;\n /** The linked fields a search matches. Unset: the naming field. */\n searchFields?: readonly string[];\n /**\n * The order the picker lists rows in (`link.orderBy`, or the linked view's `orderBy` for\n * `\"view\"`), then the key. Undefined: by the naming field, then the key.\n */\n readonly orderBy?: { readonly field: string; readonly direction: \"asc\" | \"desc\"; readonly nulls?: \"first\" | \"last\" | undefined } | undefined;\n /**\n * The filters a picker sends: the linked view's scope keys from `scope` (as its own lists apply\n * them), its preset's filter, then the link's own `filter` for these form values.\n */\n filters(scope?: ResourceScope | null, values?: Readonly<Record<string, unknown>>): FilterParam[];\n}\n\n/**\n * An IANA zone name as written: `\"UTC\"`, `\"GMT\"` or `Area/Location` (`\"Europe/Berlin\"`). The\n * type keeps a bare word out; `defineView` checks the runtime knows the zone.\n */\nexport type TimeZoneName = \"UTC\" | \"GMT\" | `${string}/${string}`;\n\n/** A view field's clock: the viewer's, the scope's, or a fixed zone. */\nexport type ViewTimeZone = \"viewer\" | \"scope\" | TimeZoneName;\n\n/** A column computed from the row, never stored or sent. */\nexport interface ComputedColumn<Row extends DataRow = DataRow> {\n /** The column's key; must not clash with a field name. */\n key: string;\n label: string;\n value: (row: Row) => unknown;\n display?: DisplayHint;\n}\n\n/** One entry in a column list: a field by name, or a computed column. */\nexport type ViewColumn<Name extends string, Row extends DataRow> = Name | ComputedColumn<Row>;\n\n/** A form laid out in order: fields, and fields under a heading. */\nexport type ViewFormItem<Name extends string> = Name | { section: string; title?: string; fields: readonly Name[] };\n\n/**\n * A named tab of the list: which columns, and which rows (`{ status: \"open\" }` is an equality\n * filter, sent to the server, never applied to loaded rows).\n */\nexport interface ViewPreset<Name extends string> {\n label?: string;\n columns?: string;\n filter?: Readonly<Partial<Record<Name, string | number | boolean | null>>>;\n}\n\n/** `true` when allowed, or the reason it isn't, in one sentence for the disabled control. */\nexport type Allowed = true | string;\n\n/**\n * Row rules the server can't cheaply express (\"the default brand can't be deleted\"). They only\n * narrow: the effective right is the server's AND these. An invariant goes in the database too.\n *\n * Each gets the viewer (`useViewer()`: id, scope, roles). Outside a ViewerScope it is\n * `{ id: null, scope: {} }`, so a guard that needs it refuses with its reason. Pure and\n * synchronous; never a security check (row-level security is the boundary).\n */\nexport interface ViewGuards<Row extends DataRow> {\n create?: (viewer: Viewer) => Allowed;\n update?: (row: Row, viewer: Viewer) => Allowed;\n delete?: (row: Row, viewer: Viewer) => Allowed;\n}\n\n/**\n * A named operation on one row, shaped like core's {@link RowAction} (which a provider reports),\n * plus a guard. The guard only narrows: the server still decides whether the action runs.\n *\n * ```ts\n * actions: [{ name: \"archive\", label: \"Archive\", confirm: \"Archive this brand?\", can: (r) => (r.is_default ? \"The default brand stays.\" : true) }]\n * ```\n */\nexport interface ViewAction<Row extends DataRow = DataRow> extends RowAction {\n /** Drawn as destructive (red, the menu's destructive style). */\n destructive?: boolean;\n can?: (row: Row, viewer: Viewer) => Allowed;\n}\n\n/** An action as a renderer lists it: the words only. Ask `view.canAction` whether a row allows it. */\nexport type ResolvedViewAction = RowAction & { readonly destructive?: boolean };\n\n/** A row in one line, for pickers, notifications and page bars. */\nexport interface RowSummary {\n title: string;\n subtitle?: string;\n chips?: readonly { label: string; tone?: ViewTone }[];\n /**\n * A picture beside the row: `src` is shown only when `isSafeUrl` accepts it; otherwise the\n * initials of `name`. `alt` defaults to empty (decorative). Resolve it with `rowPicture`.\n */\n image?: RowImage;\n}\n\n/** A row's picture, as a view's `summary` gives it. */\nexport interface RowImage {\n src?: string;\n /** Whose picture: the initials come from it when there is no safe `src`. */\n name?: string;\n /** Alternative text. Default empty: the picture is decorative (the row's title names it). */\n alt?: string;\n}\n\n/** A row's picture, ready to draw: an image (with initials for when it fails to load), or initials. */\nexport type RowPicture =\n | { readonly kind: \"image\"; readonly src: string; readonly alt: string; readonly fallback: string }\n | { readonly kind: \"initials\"; readonly text: string };\n\n/**\n * The words a view shows. Each one is a step in a chain, and each step overrides the one before:\n * words derived from the resource's name, then the contract's (`noun`, `nounPlural`, `label`, which\n * `genesis introspect` reads from the table comment's `@genesis {...}`), then these, then the\n * screen's own props. Templates take `{noun}`, `{nouns}`, `{count}` and `{total}`.\n */\nexport interface ViewCopy {\n /** One row, in a sentence: \"brand\". Default: the contract's `noun`, then the table name's singular. */\n noun?: string;\n /**\n * Several: \"brands\". Default: the contract's `nounPlural`, then the plural of a `noun` the view or\n * contract gives (\"entry\" → \"entries\"); with only a noun derived from the name, the contract's\n * label when it reads as a plural (\"People\"), else the table name.\n */\n nounPlural?: string;\n /** The page title. Default: the contract's label, then the plural noun in title case. */\n title?: string;\n subtitle?: string;\n empty?: { title?: string; body?: string };\n /** The create button. Default \"New\". */\n create?: string;\n /**\n * The form's words. Titles: default \"New {noun}\" and \"Edit {noun}\" (the UI catalogue's `form`).\n * Submit buttons: default \"Create\" and \"Save\". Descriptions (read out with the title): default\n * the UI catalogue's `form.createDescription` and `form.editDescription`.\n */\n form?: {\n createTitle?: string;\n editTitle?: string;\n createSubmit?: string;\n editSubmit?: string;\n createDescription?: string;\n editDescription?: string;\n };\n /**\n * The count beside the title. Default \"{count} {noun}\" for one, \"{count} {nouns}\" for more, and\n * \"{count} of {total}\" when filtered (the UI catalogue's `page.count*`).\n */\n count?: { one?: string; other?: string; filtered?: string };\n}\n\n/** How a calendar lays out its window: a month grid, 1–4 weeks, a day-by-day agenda, or a row per lane. */\nexport type ViewCalendarLayout = \"month\" | \"weeks\" | \"agenda\" | \"lanes\";\n\n/** What a calendar's `durationField` counts. */\nexport type ViewCalendarDurationUnit = \"minutes\" | \"hours\" | \"days\";\n\n/**\n * How the view's rows show as a calendar: ResourceView's `mode=\"calendar\"` on the web,\n * NativeResourceView's later. Plain values only, so every platform reads the same block; a screen\n * overrides the layout, weeks and anchor, and adds functions (dot colours, `onSelect`).\n */\nexport interface ViewCalendar<Name extends string = string> {\n /** The date or timestamp field that places each row. */\n field: Name;\n /** Where a row ends: its last day for a date field, its end instant for a timestamp. */\n endField?: Name;\n /**\n * A number field holding how long a row runs, for a row with no end column: its end is the\n * start plus this many `durationUnit`s. A row whose `endField` has a value keeps that end.\n */\n durationField?: Name;\n /** What `durationField` counts. Default `minutes`. */\n durationUnit?: ViewCalendarDurationUnit;\n /** A yes/no field: the row is all day, its timestamp shown without a time. */\n allDayField?: Name;\n /** The field whose value (or list of values) names a row's lanes: a dot each, a lane each. */\n laneBy?: Name;\n /** Default `month`. */\n layout?: ViewCalendarLayout;\n /**\n * The layout on a phone (below 768px), until the person picks one from the layout switch:\n * `\"agenda\"` turns a month grid too narrow to read into a day-by-day list. Unset, a phone shows\n * `layout`, as before.\n */\n phoneLayout?: ViewCalendarLayout;\n /** For `weeks`, `agenda` and `lanes`: 1 to 4. Default 2. */\n weeks?: 1 | 2 | 3 | 4;\n /** 0 Sunday or 1 Monday (default). */\n weekStartsOn?: 0 | 1;\n}\n\n/**\n * How the view's rows show as a board: a column per value of one field, a card per row.\n * ResourceView's `mode=\"board\"` draws it, and moving a card between columns writes the field\n * through the provider. Plain values only, so every platform reads the same block.\n */\nexport interface ViewBoard<Name extends string = string> {\n /** The field whose value is a card's column: a field with choices (an enum) or a yes/no one. */\n field: Name;\n /**\n * The columns, in order, as values of `field`. Default: its choices in the contract's order,\n * then a \"No value\" column when it can be empty. Listing them shows only those.\n */\n columns?: readonly string[];\n /** The fields a card shows under its title, in order. Default none: the title alone. */\n cardFields?: readonly Name[];\n /**\n * The most cards a column should hold, by value (`{ doing: 3 }`): a work-in-progress limit.\n * A column over its limit says so; nothing stops a move into it.\n */\n limits?: Readonly<Record<string, number>>;\n}\n\n/**\n * How the view's rows show as a gallery: ResourceView's `mode=\"grid\"` draws a photo per row in\n * justified rows (the layout `GalleryGrid` uses, from `@marktiderman/genesis-core/gallery`) in\n * place of cards. Plain field names only, so every platform reads the same block.\n */\nexport interface ViewGallery<Name extends string = string> {\n /** The field holding the image's URL. */\n image: Name;\n /** The image's width and height in pixels, when the rows store them: rows pack by their ratio, 4:3 without. */\n width?: Name;\n height?: Name;\n /** A short line under the photo in the viewer. Default none. */\n caption?: Name;\n /** The photo's text alternative. Default the row's label (the view's `labelField`). */\n alt?: Name;\n /** The target row height, px on the web and points on a phone. Default 180, as `GalleryGrid`. */\n rowHeight?: number;\n}\n\n/**\n * How a record opens from a view (a record page, ADR 0021): a **side peek** (a panel at the edge,\n * the list still beside it), a **center peek** (a dialog over the list) or a full **page** (the\n * record's own route).\n *\n * @stability Beta\n */\nexport type RecordOpen = \"side-peek\" | \"center-peek\" | \"page\";\n\n/** The open modes, in the order a picker lists them. @stability Beta */\nexport const RECORD_OPEN_MODES: readonly RecordOpen[] = Object.freeze([\"side-peek\", \"center-peek\", \"page\"]);\n\n/** What `defineView` accepts. */\nexport interface ViewDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> {\n copy?: ViewCopy;\n fields?: { readonly [K in FieldNameOf<C>]?: ViewField<Row> };\n /**\n * Column lists by preset name. `default` is the full list; others (`compact`) are what a screen\n * picks. Without `default`: every field that isn't sensitive, generated-only or the key.\n */\n columns?: { readonly default?: readonly ViewColumn<FieldNameOf<C>, Row>[] } & {\n readonly [preset: string]: readonly ViewColumn<FieldNameOf<C>, Row>[] | undefined;\n };\n /** Tabs: columns plus filters. */\n presets?: Readonly<Record<string, ViewPreset<FieldNameOf<C>>>>;\n /** The record form. Default: every writable field, in contract order. */\n form?: readonly ViewFormItem<FieldNameOf<C>>[];\n /**\n * Edit every link in this view's forms with a picker. Default false: a link is read-only (and\n * never sent) unless its `fields.<link>.link` is set (`{}` is enough). The default flips in 3.0.\n */\n editLinks?: boolean;\n can?: ViewGuards<Row>;\n /** Named operations on one row, in the order a menu shows them. Names are unique. */\n actions?: readonly ViewAction<Row>[];\n summary?: (row: Row) => RowSummary;\n /** The scope keys this view needs above it (`[\"org_id\"]`). They stay out of forms. */\n scope?: readonly FieldNameOf<C>[];\n /** How the rows show as a calendar (`mode=\"calendar\"`). */\n calendar?: ViewCalendar<FieldNameOf<C>>;\n /** How the rows show as a board (`mode=\"board\"`). */\n board?: ViewBoard<FieldNameOf<C>>;\n /** How the rows show as a gallery of photos (`mode=\"grid\"`), in place of cards. */\n gallery?: ViewGallery<FieldNameOf<C>>;\n /** Group rows under headers by this field. */\n groupBy?: FieldNameOf<C>;\n /**\n * How a record opens from every view type of this view (ADR 0021): `side-peek` (default),\n * `center-peek` or `page`. A screen's own `open` (or ResourcePage's older `detail`) wins.\n */\n open?: RecordOpen;\n /**\n * The record view a peek renders: a function, because the record view is defined from this\n * view, with its return type named so TypeScript needn't infer one from the other:\n * `recordView: (): AnyRecordView => brandRecordView`. Without one, a peek shows the view's\n * columns as today.\n */\n recordView?: () => import(\"./record-view\").AnyRecordView;\n /**\n * Default order; `manual: true` turns on drag to reorder, writing this field. `nulls` says where\n * rows with no value go (unset, the store decides: Postgres puts them first on a descending sort).\n */\n orderBy?: { field: FieldNameOf<C>; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\"; manual?: boolean };\n /** Bumped when stored preferences (saved views, column order) change shape. */\n version?: number;\n}\n\n/** A column as a renderer draws it: everything resolved. */\nexport interface ResolvedColumn<Row extends DataRow = DataRow> {\n key: string;\n label: string;\n display: DisplayHint;\n /** The field behind it; absent for a computed column. */\n field?: FieldSchema;\n value: (row: Row) => unknown;\n tones?: Readonly<Record<string, ViewTone>>;\n /** The words for a value (`ViewField.labels`); `valueText` reads them. */\n labels?: Readonly<Record<string, string>>;\n /** For a link: the linked row's field that names it (`ViewField.labelField`). */\n labelField?: string;\n /** For a link: the words when its row is hidden or gone (`ViewField.missingLabel`). */\n missingLabel?: string;\n /** Whether to show the cell. Without a viewer it answers for no one (fail closed). */\n when?: (row: Row, viewer?: Viewer) => boolean;\n timeZone?: ViewField[\"timeZone\"];\n}\n\n/** A form field as a renderer draws it. */\nexport interface ResolvedFormField {\n field: FieldSchema;\n label: string;\n display: DisplayHint;\n required: boolean;\n readOnly: boolean;\n max?: number;\n /** The input's autofill token (`ViewField.autoComplete`). */\n autoComplete?: string;\n /** The keyboard a phone shows (`ViewField.inputMode`). */\n inputMode?: ViewField[\"inputMode\"];\n /** The Return key's label (`ViewField.enterKeyHint`). */\n enterKeyHint?: ViewField[\"enterKeyHint\"];\n /** For a link: the linked row's field that names it (`ViewField.labelField`). */\n labelField?: string;\n /** For a link: the words when its row is hidden or gone (`ViewField.missingLabel`). */\n missingLabel?: string;\n /** An enum field's choices, in the contract's order, with the view's words. */\n options?: readonly { value: string; label: string }[];\n /** For a link the view opted in (`fields.<link>.link`, `editLinks`): how its picker lists the linked rows. */\n link?: ResolvedLink;\n /** The heading it sits under, or null for none. */\n section: string | null;\n sectionTitle: string | null;\n visible?: (values: Readonly<Record<string, unknown>>) => boolean;\n}\n\n/** What `defineView` returns: frozen, with everything the renderers need resolved. */\nexport interface ResourceView<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> {\n readonly contract: C;\n readonly definition: Readonly<ViewDefinition<C, Row>>;\n /** The resource name the provider addresses. */\n readonly resource: string;\n readonly noun: string;\n readonly nounPlural: string;\n readonly title: string;\n /** The field that names a row, for links, pickers and the peek's title. */\n readonly labelField: string | undefined;\n /** The column presets this view has, `default` first. */\n readonly presets: readonly string[];\n field(name: string): FieldSchema | undefined;\n label(name: string): string;\n display(name: string): DisplayHint;\n /** A value in words: the field's `labels`, else title case. For badges, choices and group titles. */\n valueLabel(name: string, value: unknown): string;\n columns(preset?: string): readonly ResolvedColumn<Row>[];\n /**\n * One field as a column, resolved as a preset lists it (a board card's fields, say). Undefined\n * for a name that isn't a field or one the viewer can't read (`permissions.read: false`).\n */\n column(name: string): ResolvedColumn<Row> | undefined;\n form(mode: \"create\" | \"edit\"): readonly ResolvedFormField[];\n /** Fields a writer may send: the form's, never generated, read-only, key or scope fields. */\n writable(mode: \"create\" | \"edit\"): readonly string[];\n /**\n * Whether the view's guard allows it for this viewer: `true`, or the guard's reason. Without a\n * viewer, guards get `NO_VIEWER` (no one), so one that needs the viewer refuses.\n */\n can(action: \"create\", viewer?: Viewer): Allowed;\n can(action: \"update\" | \"delete\", row: Row, viewer?: Viewer): Allowed;\n /** The view's actions, in order, frozen. */\n actions(): readonly ResolvedViewAction[];\n /**\n * Whether this row allows the named action: `true`, or the guard's reason. Only narrows what the\n * server allows. Throws {@link ViewDefinitionError} for a name the view doesn't define.\n */\n canAction(name: string, row: Row, viewer?: Viewer): Allowed;\n summary(row: Row): RowSummary;\n /**\n * The row as a gallery photo, by the view's `gallery` block and any `override` a screen passes\n * (ResourceView's `gallery`): undefined without a gallery block. Its `id` is the row's key, its\n * `alt` the row's label unless the block names a field; a row without an image has an empty `src`,\n * which GalleryGrid and NativeGalleryGrid draw as a placeholder tile; leave those out of a Lightbox.\n */\n galleryItem(row: Row, override?: Partial<ViewGallery>): GalleryItem | undefined;\n}\n","// defineView: a contract plus what it means to people, checked once and frozen (the same rule as\n// genesis-sites' defineSection). Everything a renderer needs is resolved here, so web, native and\n// the extension draw the same labels, columns and form.\n\nimport { NO_VIEWER, type Viewer } from \"../viewer\";\nimport { encodeRecordKey, keyFields } from \"../schema/keys\";\nimport type { GalleryItem } from \"../gallery\";\nimport { fieldControl, type DataRow, type FieldSchema, type ResourceContract } from \"../schema/types\";\nimport { titleCase } from \"../utils\";\nimport { isTimeZone } from \"../dates\";\nimport { ViewDefinitionError } from \"./errors\";\nimport { linkProblems, resolveLink } from \"./link\";\nimport type {\n Allowed,\n ComputedColumn,\n DisplayHint,\n ResolvedColumn,\n ResolvedFormField,\n ResolvedViewAction,\n ResourceView,\n RowOf,\n RowSummary,\n ViewBoard,\n ViewCalendar,\n ViewDefinition,\n ViewField,\n ViewGallery,\n RecordOpen,\n} from \"./types\";\nimport { RECORD_OPEN_MODES } from \"./types\";\n\n// Facts a contract may carry from `@genesis` comments. Read loosely so a contract emitted before\n// they existed still works.\ntype FieldFacts = FieldSchema & { readonly readOnly?: boolean; readonly sensitive?: boolean };\ntype ContractFacts = ResourceContract & {\n readonly label?: string;\n readonly labelField?: string;\n readonly noun?: string;\n readonly nounPlural?: string;\n};\n\n// In a file of its own so scope.ts and link.ts can throw it without importing this one.\nexport { ViewDefinitionError } from \"./errors\";\n\n/** The display a field gets when the view doesn't name one. */\nexport function deriveDisplay(field: FieldSchema): DisplayHint {\n if (field.references) return \"relation\";\n switch (fieldControl(field)) {\n case \"url\":\n return \"url\";\n case \"email\":\n return \"email\";\n case \"image\":\n return \"image\";\n case \"textarea\":\n return \"longText\";\n case \"date\":\n return \"date\";\n }\n if (field.enumValues?.length) return \"badge\";\n switch (field.type) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"json\":\n return \"json\";\n case \"relation\":\n return \"relation\";\n case \"datetime\":\n return /^date$/i.test(field.dbType ?? \"\") ? \"date\" : \"datetime\";\n }\n return \"text\";\n}\n\n// Plurals whose singular the rules below would get wrong.\nconst SAME_OR_IRREGULAR: Readonly<Record<string, string>> = {\n series: \"series\",\n species: \"species\",\n movies: \"movie\",\n cookies: \"cookie\",\n ties: \"tie\",\n pies: \"pie\",\n people: \"person\",\n};\n\n/** A table name's singular, for the default noun. A wrong guess is fixed with `@genesis {\"noun\"}`. */\nexport function singular(word: string): string {\n const last = word.split(\" \").pop()!;\n const head = word.slice(0, word.length - last.length);\n const lower = last.toLowerCase();\n const one = (s: string) => head + s;\n if (SAME_OR_IRREGULAR[lower]) return one(SAME_OR_IRREGULAR[lower]!);\n if (/[^aeiou]ies$/.test(lower)) return one(`${last.slice(0, -3)}y`);\n // statuses, addresses, boxes, matches, wishes, quizzes\n if (/(?:s|x|z|ch|sh)es$/.test(lower)) return one(last.slice(0, -2));\n if (/(?:ss|us|is)$/.test(lower) || !lower.endsWith(\"s\")) return word;\n return one(last.slice(0, -1));\n}\n\n// Singulars whose plural the rules below would get wrong: the irregulars above, inverted.\nconst PLURAL_OF: Readonly<Record<string, string>> = Object.fromEntries(\n Object.entries(SAME_OR_IRREGULAR).map(([many, one]) => [one, many]),\n);\n\n/** A noun's plural, the inverse of `singular`: entry → entries, box → boxes, person → people. */\nexport function plural(word: string): string {\n const last = word.split(\" \").pop()!;\n const head = word.slice(0, word.length - last.length);\n const lower = last.toLowerCase();\n const many = (s: string) => head + s;\n if (PLURAL_OF[lower]) return many(PLURAL_OF[lower]!);\n if (/[^aeiou]y$/.test(lower)) return many(`${last.slice(0, -1)}ies`);\n if (/(?:s|x|z|ch|sh)$/.test(lower)) return many(`${last}es`);\n return many(`${last}s`);\n}\n\n// The view's own operations (`view.can`): an action can't take their names.\nconst RESERVED_ACTIONS: ReadonlySet<string> = new Set([\"create\", \"update\", \"delete\"]);\n\nconst own = <V>(record: Readonly<Record<string, V>> | undefined, key: string): V | undefined =>\n record && Object.hasOwn(record, key) ? record[key] : undefined;\n\n/** A value in words: its entry in `labels`, else the value in title case (`draft` → \"Draft\"). */\nexport function valueText(labels: Readonly<Record<string, string>> | undefined, value: unknown): string {\n const key = String(value);\n return own(labels, key) ?? titleCase(key);\n}\n\nconst KIND: Readonly<Record<string, string>> = { datetime: \"date or timestamp\", boolean: \"yes/no\", number: \"number\" };\nconst LAYOUTS: readonly string[] = [\"month\", \"weeks\", \"agenda\", \"lanes\"];\n\n/** A calendar block's keys: anything else in one is a mistake `defineView` names. */\nconst CALENDAR_KEYS: readonly string[] = [\n \"field\", \"endField\", \"durationField\", \"durationUnit\", \"allDayField\", \"laneBy\", \"layout\", \"phoneLayout\", \"weeks\", \"weekStartsOn\",\n];\n\n/**\n * What's wrong with a calendar block for these fields, one sentence each (empty when it's fine).\n * `defineView` checks the view's own block with it; a renderer checks a screen's overrides merged\n * over that block with it too, so neither can name a field that isn't there or isn't a date.\n *\n * @stability Beta\n */\nexport function calendarProblems(fields: readonly Pick<FieldSchema, \"name\" | \"type\" | \"array\">[], calendar: Partial<ViewCalendar>): string[] {\n const problems: string[] = [];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const typed = (name: string | undefined, where: string, type: string) => {\n if (name === undefined) return;\n const f = byName.get(name);\n if (!f) problems.push(`${where} names \"${name}\", which isn't a field`);\n else if (f.type !== type || f.array) problems.push(`${where} \"${name}\" isn't a ${KIND[type]} field`);\n };\n typed(calendar.field, \"calendar.field\", \"datetime\");\n typed(calendar.endField, \"calendar.endField\", \"datetime\");\n typed(calendar.durationField, \"calendar.durationField\", \"number\");\n typed(calendar.allDayField, \"calendar.allDayField\", \"boolean\");\n if (calendar.durationUnit !== undefined && ![\"minutes\", \"hours\", \"days\"].includes(calendar.durationUnit)) {\n problems.push(`calendar.durationUnit \"${String(calendar.durationUnit)}\" isn't minutes, hours or days`);\n }\n if (calendar.durationUnit !== undefined && calendar.durationField === undefined) problems.push(\"calendar.durationUnit needs a durationField\");\n if (calendar.laneBy !== undefined && !byName.has(calendar.laneBy)) problems.push(`calendar.laneBy names \"${calendar.laneBy}\", which isn't a field`);\n for (const key of [\"layout\", \"phoneLayout\"] as const) {\n const value = calendar[key];\n if (value !== undefined && !LAYOUTS.includes(value)) problems.push(`calendar.${key} \"${String(value)}\" isn't month, weeks, agenda or lanes`);\n }\n if (calendar.weeks !== undefined && ![1, 2, 3, 4].includes(calendar.weeks)) problems.push(`calendar.weeks is 1 to 4, not ${String(calendar.weeks)}`);\n if (calendar.weekStartsOn !== undefined && calendar.weekStartsOn !== 0 && calendar.weekStartsOn !== 1) {\n problems.push(`calendar.weekStartsOn is 0 (Sunday) or 1 (Monday), not ${String(calendar.weekStartsOn)}`);\n }\n return problems;\n}\n\n/** A board block's keys: anything else in one is a mistake `defineView` names. */\nconst BOARD_KEYS: readonly string[] = [\"field\", \"columns\", \"cardFields\", \"limits\"];\n\n/**\n * The values a board's field can hold, in the contract's order: an enum's choices, or `true`\n * and `false` for a yes/no field. Undefined when the field has no fixed set of values.\n *\n * @stability Beta\n */\nexport function boardChoices(field: Pick<FieldSchema, \"type\" | \"array\" | \"enumValues\"> | undefined): readonly string[] | undefined {\n if (!field || field.array) return undefined;\n if (field.enumValues?.length) return field.enumValues;\n if (field.type === \"boolean\") return [\"true\", \"false\"];\n return undefined;\n}\n\n/** A gallery block's keys: anything else in one is a mistake `defineView` names. */\nconst GALLERY_KEYS: readonly string[] = [\"image\", \"width\", \"height\", \"caption\", \"alt\", \"rowHeight\"];\n\n/**\n * What's wrong with a gallery block for these fields, one sentence each (empty when it's fine).\n *\n * @stability Beta\n */\nexport function galleryProblems(fields: readonly Pick<FieldSchema, \"name\" | \"type\" | \"array\">[], gallery: Partial<ViewGallery>): string[] {\n const problems: string[] = [];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const named = (key: \"image\" | \"width\" | \"height\" | \"caption\" | \"alt\", type?: \"string\" | \"number\") => {\n const name = gallery[key];\n if (name === undefined) return;\n const field = byName.get(name);\n if (!field) problems.push(`gallery.${key} names \"${name}\", which isn't a field`);\n else if (type && (field.type !== type || field.array)) problems.push(`gallery.${key} \"${name}\" is a ${field.array ? \"list\" : field.type}, not a ${type === \"string\" ? \"text\" : \"number\"} field`);\n };\n named(\"image\", \"string\");\n named(\"width\", \"number\");\n named(\"height\", \"number\");\n named(\"caption\");\n named(\"alt\");\n if ((gallery.width === undefined) !== (gallery.height === undefined)) problems.push(\"gallery.width and gallery.height go together: a ratio needs both\");\n const { rowHeight } = gallery;\n if (rowHeight !== undefined && !(typeof rowHeight === \"number\" && Number.isFinite(rowHeight) && rowHeight > 0)) problems.push(`gallery.rowHeight is a height above 0, not ${String(rowHeight)}`);\n return problems;\n}\n\n/**\n * What's wrong with a board block for these fields, one sentence each (empty when it's fine).\n *\n * @stability Beta\n */\nexport function boardProblems(\n fields: readonly Pick<FieldSchema, \"name\" | \"type\" | \"array\" | \"enumValues\">[],\n board: Partial<ViewBoard>,\n): string[] {\n const problems: string[] = [];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const field = board.field === undefined ? undefined : byName.get(board.field);\n if (board.field !== undefined && !field) problems.push(`board.field names \"${board.field}\", which isn't a field`);\n const choices = boardChoices(field);\n if (field && !choices) problems.push(`board.field \"${board.field}\" has no fixed values: use an enum or a yes/no field`);\n if (board.columns !== undefined) {\n if (!Array.isArray(board.columns) || board.columns.length === 0) problems.push(\"board.columns isn't a list of values\");\n else {\n const seen = new Set<string>();\n for (const value of board.columns) {\n if (choices && !choices.includes(value)) problems.push(`board.columns lists \"${String(value)}\", which isn't a value of ${board.field}`);\n if (seen.has(value)) problems.push(`board.columns lists \"${String(value)}\" twice`);\n seen.add(value);\n }\n }\n }\n for (const name of board.cardFields ?? []) {\n if (!byName.has(name)) problems.push(`board.cardFields names \"${name}\", which isn't a field`);\n }\n for (const [value, limit] of Object.entries(board.limits ?? {})) {\n const columns = board.columns ?? choices;\n if (columns && !columns.includes(value)) problems.push(`board.limits has \"${value}\", which isn't one of the board's columns`);\n if (!Number.isInteger(limit) || limit < 1) problems.push(`board.limits.${value} is a whole number of cards, 1 or more, not ${String(limit)}`);\n }\n return problems;\n}\n\n/**\n * Describe what a resource means to people. The result is frozen and platform-neutral:\n *\n * ```ts\n * export const brandsView = defineView(contracts[\"public.brands\"], {\n * fields: { status: { display: \"badge\", tones: { active: \"success\" } } },\n * columns: { default: [\"name\", \"status\", \"created_at\"], compact: [\"name\"] },\n * can: {\n * delete: (row) => (row.is_default ? \"The default brand stays.\" : true),\n * update: (row, viewer) => (row.owner_id === viewer.id ? true : \"Only its owner edits a brand.\"),\n * },\n * actions: [{ name: \"archive\", label: \"Archive\", can: (row) => (row.is_default ? \"The default brand stays.\" : true) }],\n * });\n * ```\n *\n * Throws {@link ViewDefinitionError} when it names something the contract doesn't have, so a\n * renamed column fails at start-up, not as a blank cell.\n */\nexport function defineView<C extends ResourceContract, Row extends DataRow = RowOf<C>>(\n contract: C,\n definition: ViewDefinition<C, Row> = {},\n): ResourceView<C, Row> {\n const facts = contract as ContractFacts;\n const fields = contract.fields as readonly FieldFacts[];\n const byName = new Map(fields.map((f) => [f.name, f]));\n const keys = new Set(keyFields(contract));\n const scope = new Set<string>(definition.scope ?? []);\n // Copied and frozen, so changing the objects passed in can't change the view afterwards.\n const viewFields = Object.freeze(\n Object.fromEntries(\n Object.entries(definition.fields ?? {}).map(([k, v]) => {\n const f = { ...(v as ViewField) };\n // Maps only: anything else is left as given for the checks below to name.\n const map = (m: unknown) => Boolean(m) && typeof m === \"object\" && !Array.isArray(m);\n if (map(f.tones)) f.tones = Object.freeze({ ...f.tones });\n if (map(f.labels)) f.labels = Object.freeze({ ...f.labels });\n return [k, Object.freeze(f)];\n }),\n ),\n ) as Readonly<Record<string, NonNullable<ViewDefinition<C, Row>[\"fields\"]>[never]>>;\n const columnLists = Object.freeze(\n Object.fromEntries(\n Object.entries(definition.columns ?? {}).map(([k, list]) => [\n k,\n Object.freeze((list ?? []).map((c) => (typeof c === \"string\" ? c : Object.freeze({ ...c })))),\n ]),\n ),\n ) as Readonly<Record<string, readonly (string | ComputedColumn<Row>)[] | undefined>>;\n const formItems = Object.freeze(\n (definition.form ?? []).map((item) => (typeof item === \"string\" ? item : Object.freeze({ ...item, fields: Object.freeze([...item.fields]) }))),\n );\n const presets = Object.freeze(\n Object.fromEntries(\n Object.entries(definition.presets ?? {}).map(([k, p]) => [k, Object.freeze({ ...p, ...(p.filter ? { filter: Object.freeze({ ...p.filter }) } : {}) })]),\n ),\n ) as NonNullable<ViewDefinition<C, Row>[\"presets\"]>;\n const actionList = Object.freeze(\n // Names are trimmed, so \" archive\" and \"archive\" are one name.\n (Array.isArray(definition.actions) ? definition.actions : []).map((a) =>\n a && typeof a === \"object\" ? Object.freeze({ ...a, ...(typeof a.name === \"string\" ? { name: a.name.trim() } : {}) }) : a,\n ),\n );\n\n // ── Check every name once ────────────────────────────────────────────\n const problems: string[] = [];\n const known = (name: string, where: string) => {\n if (!byName.has(name)) problems.push(`${where} names \"${name}\", which isn't a field`);\n };\n for (const name of Object.keys(viewFields)) known(name, \"fields\");\n for (const [name, v] of Object.entries(viewFields)) {\n if (v?.labels === undefined) continue;\n if (!v.labels || typeof v.labels !== \"object\" || Array.isArray(v.labels)) {\n problems.push(`fields.${name}.labels isn't a map of values to words`);\n continue;\n }\n const values = byName.get(name)?.enumValues;\n for (const [value, words] of Object.entries(v.labels)) {\n if (typeof words !== \"string\" || !words.trim()) problems.push(`fields.${name}.labels.${value} isn't text`);\n if (values?.length && !values.includes(value)) problems.push(`fields.${name}.labels names \"${value}\", which isn't one of its values`);\n }\n }\n // A clock is \"viewer\", \"scope\" or a zone this runtime knows. Never a quiet fallback: a field\n // drawn on the wrong clock shows the wrong times with nothing to say so.\n for (const [name, v] of Object.entries(viewFields)) {\n const zone: unknown = v?.timeZone;\n if (zone === undefined || zone === \"viewer\" || zone === \"scope\") continue;\n if (zone === \"practice\") {\n problems.push(\n `fields.${name}.timeZone \"practice\" was renamed \"scope\" in genesis-core 2; run \\`genesis codemod genesis-core-2-scope-names\\``,\n );\n } else if (!isTimeZone(zone)) {\n problems.push(`fields.${name}.timeZone \"${String(zone)}\" isn't \"viewer\", \"scope\" or a time zone this runtime knows`);\n }\n }\n for (const [name, v] of Object.entries(viewFields)) {\n if (v?.missingLabel === undefined) continue;\n if (typeof v.missingLabel !== \"string\" || !v.missingLabel.trim()) problems.push(`fields.${name}.missingLabel isn't text`);\n else if (!byName.get(name)?.references) problems.push(`fields.${name}.missingLabel is set, but \"${name}\" isn't a link`);\n }\n for (const [name, v] of Object.entries(viewFields)) problems.push(...linkProblems(name, v?.link, byName.get(name)?.references));\n if (definition.editLinks !== undefined && typeof definition.editLinks !== \"boolean\") problems.push(\"editLinks isn't true or false\");\n for (const [name, v] of Object.entries(viewFields)) {\n if (v?.labelField === undefined) continue;\n if (typeof v.labelField !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(v.labelField)) {\n problems.push(`fields.${name}.labelField isn't a field name`);\n } else if (!byName.get(name)?.references) {\n problems.push(`fields.${name}.labelField is set, but \"${name}\" isn't a link`);\n }\n }\n for (const [preset, list] of Object.entries(columnLists)) {\n const seen = new Set<string>();\n for (const column of list ?? []) {\n const key = typeof column === \"string\" ? column : column.key;\n if (typeof column === \"string\") known(column, `columns.${preset}`);\n else if (byName.has(column.key)) problems.push(`columns.${preset}: computed \"${column.key}\" clashes with a field`);\n if (seen.has(key)) problems.push(`columns.${preset} lists \"${key}\" twice`);\n seen.add(key);\n }\n }\n const formSeen = new Set<string>();\n for (const item of formItems) {\n for (const name of typeof item === \"string\" ? [item] : item.fields) {\n known(name, \"form\");\n if (formSeen.has(name)) problems.push(`form lists \"${name}\" twice`);\n formSeen.add(name);\n }\n }\n for (const name of scope) known(name, \"scope\");\n if (definition.groupBy) known(definition.groupBy, \"groupBy\");\n const rawOpen = (definition as { open?: unknown }).open;\n if (rawOpen !== undefined && !RECORD_OPEN_MODES.includes(rawOpen as RecordOpen)) {\n problems.push(`open is ${RECORD_OPEN_MODES.map((m) => `\"${m}\"`).join(\", \")}, not ${JSON.stringify(rawOpen)}`);\n }\n const rawRecordView = (definition as { recordView?: unknown }).recordView;\n if (rawRecordView !== undefined && typeof rawRecordView !== \"function\") problems.push(\"recordView is a function that returns the record view (`() => brandRecordView`)\");\n // A copy, frozen like the other blocks: changing the object passed in can't change the view.\n // Checked as written first: a plain object with a field, and only keys a calendar has.\n const rawCalendar = definition.calendar as unknown;\n let calendar: Readonly<ViewCalendar> | undefined;\n if (rawCalendar !== undefined) {\n if (!rawCalendar || typeof rawCalendar !== \"object\" || Array.isArray(rawCalendar)) {\n problems.push(\"calendar isn't an object\");\n } else {\n for (const key of Object.keys(rawCalendar)) if (!CALENDAR_KEYS.includes(key)) problems.push(`calendar.${key} isn't a calendar setting`);\n if ((rawCalendar as { field?: unknown }).field === undefined) problems.push(\"calendar.field is required\");\n calendar = Object.freeze({ ...(rawCalendar as ViewCalendar) });\n problems.push(...calendarProblems(fields, calendar));\n }\n }\n const rawBoard = definition.board as unknown;\n let board: Readonly<ViewBoard> | undefined;\n if (rawBoard !== undefined) {\n if (!rawBoard || typeof rawBoard !== \"object\" || Array.isArray(rawBoard)) {\n problems.push(\"board isn't an object\");\n } else {\n for (const key of Object.keys(rawBoard)) if (!BOARD_KEYS.includes(key)) problems.push(`board.${key} isn't a board setting`);\n if ((rawBoard as { field?: unknown }).field === undefined) problems.push(\"board.field is required\");\n const given = rawBoard as ViewBoard;\n board = Object.freeze({\n ...given,\n ...(given.columns ? { columns: Object.freeze([...given.columns]) } : {}),\n ...(given.cardFields ? { cardFields: Object.freeze([...given.cardFields]) } : {}),\n ...(given.limits ? { limits: Object.freeze({ ...given.limits }) } : {}),\n });\n problems.push(...boardProblems(fields, board));\n }\n }\n const rawGallery = definition.gallery as unknown;\n let gallery: Readonly<ViewGallery> | undefined;\n if (rawGallery !== undefined) {\n if (!rawGallery || typeof rawGallery !== \"object\" || Array.isArray(rawGallery)) {\n problems.push(\"gallery isn't an object\");\n } else {\n for (const key of Object.keys(rawGallery)) if (!GALLERY_KEYS.includes(key)) problems.push(`gallery.${key} isn't a gallery setting`);\n if ((rawGallery as { image?: unknown }).image === undefined) problems.push(\"gallery.image is required\");\n gallery = Object.freeze({ ...(rawGallery as ViewGallery) });\n problems.push(...galleryProblems(fields, gallery));\n }\n }\n if (definition.orderBy) {\n known(definition.orderBy.field, \"orderBy\");\n const { nulls } = definition.orderBy as { nulls?: unknown };\n if (nulls !== undefined && nulls !== \"first\" && nulls !== \"last\") problems.push(`orderBy.nulls is \"first\" or \"last\", not ${String(nulls)}`);\n }\n for (const [name, preset] of Object.entries(presets)) {\n if (preset.columns && preset.columns !== \"default\" && !own(columnLists, preset.columns)) {\n problems.push(`presets.${name} uses columns \"${preset.columns}\", which isn't defined`);\n }\n for (const field of Object.keys(preset.filter ?? {})) known(field, `presets.${name}.filter`);\n }\n if (facts.labelField) known(facts.labelField, \"the contract's labelField\");\n const actionSeen = new Set<string>();\n if (definition.actions !== undefined && !Array.isArray(definition.actions)) problems.push(\"actions isn't a list\");\n actionList.forEach((action, i) => {\n const where = `actions[${i}]`;\n if (!action || typeof action !== \"object\") {\n problems.push(`${where} isn't an action`);\n return;\n }\n if (typeof action.name !== \"string\" || !action.name.trim()) problems.push(`${where} has no name`);\n else if (RESERVED_ACTIONS.has(action.name)) problems.push(`${where} is named \"${action.name}\", which is reserved for the view's own ${action.name}`);\n else if (actionSeen.has(action.name)) problems.push(`actions lists \"${action.name}\" twice`);\n else actionSeen.add(action.name);\n if (typeof action.label !== \"string\" || !action.label.trim()) problems.push(`${where} has no label`);\n if (action.confirm !== undefined && typeof action.confirm !== \"string\") problems.push(`${where}.confirm isn't text`);\n if (action.description !== undefined && typeof action.description !== \"string\") {\n problems.push(`${where}.description isn't text`);\n }\n if (action.can !== undefined && typeof action.can !== \"function\") problems.push(`${where}.can isn't a function`);\n if (action.destructive !== undefined && typeof action.destructive !== \"boolean\") problems.push(`${where}.destructive isn't true or false`);\n });\n if (problems.length) throw new ViewDefinitionError(contract.name, problems);\n\n // ── Words ────────────────────────────────────────────────────────────\n const copy = definition.copy ?? {};\n const base = contract.name.split(\".\").pop() ?? contract.name;\n const noun = copy.noun ?? facts.noun ?? singular(base.replace(/_/g, \" \"));\n // Several: the view's, the contract's, the noun's plural; with only a derived noun, the\n // contract's label when it reads as a plural (\"People\"), else the table name.\n const labelWords = facts.label?.toLowerCase();\n const nounPlural =\n copy.nounPlural ??\n facts.nounPlural ??\n (copy.noun || facts.noun ? plural(noun) : labelWords && singular(labelWords) !== labelWords ? labelWords : base.replace(/_/g, \" \"));\n const title = copy.title ?? facts.label ?? titleCase(nounPlural);\n const labelField = facts.labelField ?? fields.find((f) => /^(name|title|label|full_name|display_name)$/.test(f.name))?.name;\n\n const label = (name: string): string => own(viewFields, name)?.label ?? byName.get(name)?.label ?? titleCase(name);\n const display = (name: string): DisplayHint => {\n const field = byName.get(name);\n return own(viewFields, name)?.display ?? (field ? deriveDisplay(field) : \"text\");\n };\n const valueLabel = (name: string, value: unknown): string => valueText(own(viewFields, name)?.labels, value);\n // A field the provider says this user can't read is left out everywhere, even when listed.\n const readable = (name: string) => byName.get(name)?.permissions?.read !== false;\n // A link is edited in a form (a picker over the linked rows, never a typed id) only when the view\n // opts in: `fields.<link>.link` (`{}` is enough) or `editLinks: true`. Otherwise it stays\n // read-only, as before 2.x links had pickers; a screen fills a required one (its `filter`,\n // `defaults`). The default flips in 3.0.\n const editLinks = definition.editLinks === true;\n const linkEditable = (f: FieldFacts) => Boolean(f.references) && (editLinks || own(viewFields, f.name)?.link !== undefined);\n // Read-only: what the server fills (generated, `@genesis readonly`), what this user can't change,\n // what the view says, and a link the view hasn't opted in. Scope (tenant) links stay out of\n // forms altogether (below).\n const readOnly = (field: FieldFacts) =>\n Boolean(\n field.generated ||\n field.readOnly ||\n (field.references && !linkEditable(field)) ||\n field.permissions?.update === false ||\n own(viewFields, field.name)?.readOnly,\n );\n // Left out of defaults (a view still lists them on purpose): the key, scope (tenant) columns,\n // sensitive values, and links, whose words cost a lookup.\n const quiet = (f: FieldFacts) => keys.has(f.name) || scope.has(f.name) || Boolean(f.sensitive) || Boolean(f.references);\n // An opted-in link a new row can't do without (no default, never empty) is in a derived form\n // anyway: without it, the form could never save. Other links are in a form when the view lists them.\n const neededLink = (f: FieldFacts) => linkEditable(f) && !f.nullable && !f.optional && !f.hasDefault && !scope.has(f.name);\n\n // ── Columns ──────────────────────────────────────────────────────────\n const defaultColumns: readonly (string | ComputedColumn<Row>)[] =\n own(columnLists, \"default\") ?? fields.filter((f) => !quiet(f)).map((f) => f.name);\n const presetNames = Object.freeze([\"default\", ...Object.keys(columnLists).filter((p) => p !== \"default\")]);\n // One field as a column: its words, hint, tones and guards. Cached, so every list and card shares it.\n const fieldColumns = new Map<string, ResolvedColumn<Row>>();\n const fieldColumn = (column: string): ResolvedColumn<Row> => {\n const cached = fieldColumns.get(column);\n if (cached) return cached;\n const v = own(viewFields, column);\n const resolved: ResolvedColumn<Row> = Object.freeze({\n key: column,\n label: label(column),\n display: display(column),\n field: byName.get(column)!,\n value: (row: Row) => row[column],\n ...(v?.tones ? { tones: v.tones } : {}),\n ...(v?.labels ? { labels: v.labels } : {}),\n ...(v?.labelField ? { labelField: v.labelField } : {}),\n ...(v?.missingLabel ? { missingLabel: v.missingLabel } : {}),\n ...(v?.when ? { when: (row: Row, viewer: Viewer = NO_VIEWER) => v.when!(row, viewer) } : {}),\n ...(v?.timeZone ? { timeZone: v.timeZone } : {}),\n });\n fieldColumns.set(column, resolved);\n return resolved;\n };\n const resolvedColumns = new Map<string, readonly ResolvedColumn<Row>[]>();\n const columns = (preset = \"default\"): readonly ResolvedColumn<Row>[] => {\n const cached = resolvedColumns.get(preset);\n if (cached) return cached;\n const list = preset === \"default\" ? defaultColumns : own(columnLists, preset);\n if (!list) throw new ViewDefinitionError(contract.name, [`no column preset \"${preset}\"`]);\n const out = Object.freeze(\n list.filter((column) => typeof column !== \"string\" || readable(column)).map((column): ResolvedColumn<Row> => {\n if (typeof column !== \"string\") {\n return Object.freeze({ key: column.key, label: column.label, display: column.display ?? \"text\", value: column.value });\n }\n return fieldColumn(column);\n }),\n );\n resolvedColumns.set(preset, out);\n return out;\n };\n\n // ── Form ─────────────────────────────────────────────────────────────\n // One picker per link, made once: what it lists, what names a row, the filters it sends.\n const links = new Map(\n fields\n .filter((f) => linkEditable(f))\n .map((f) => [f.name, resolveLink(contract.name, f.name, f.references!, own(viewFields, f.name)?.link, own(viewFields, f.name)?.labelField)]),\n );\n type Placed = { name: string; section: string | null; sectionTitle: string | null };\n const placed: readonly Placed[] = definition.form\n ? formItems.flatMap((item): Placed[] =>\n typeof item === \"string\"\n ? [{ name: item, section: null, sectionTitle: null }]\n : item.fields.map((name) => ({ name, section: item.section, sectionTitle: item.title ?? titleCase(item.section) })),\n )\n : fields\n // JSON needs an editor of its own, so it is never in a derived form.\n // A key the person types (a code, a slug) stays; one the server fills doesn't.\n .filter(\n (f) =>\n !readOnly(f) &&\n (!quiet(f) || (keys.has(f.name) && !f.hasDefault && !f.sensitive) || (neededLink(f) && !f.sensitive)) &&\n f.type !== \"json\" &&\n !f.array,\n )\n .map((f): Placed => ({ name: f.name, section: null, sectionTitle: null }));\n // A key the server fills (a default) is never sent on create; no key is sent on edit.\n const serverKey = (f: FieldFacts, mode: \"create\" | \"edit\") => keys.has(f.name) && (mode === \"edit\" || Boolean(f.hasDefault));\n const resolvedForms = new Map<string, readonly ResolvedFormField[]>();\n const form = (mode: \"create\" | \"edit\"): readonly ResolvedFormField[] => {\n const cached = resolvedForms.get(mode);\n if (cached) return cached;\n const out = Object.freeze(placed\n .filter(({ name }) => !scope.has(name) && readable(name) && !serverKey(byName.get(name)!, mode))\n .map(({ name, section, sectionTitle }) => {\n const field = byName.get(name)!;\n const v = own(viewFields, name);\n const locked = readOnly(field);\n return Object.freeze({\n field,\n label: label(name),\n display: display(name),\n required: !locked && !field.nullable && !field.optional && (mode === \"edit\" || !field.hasDefault),\n readOnly: locked,\n section,\n sectionTitle,\n ...(v?.max !== undefined ? { max: v.max } : {}),\n ...(v?.autoComplete ? { autoComplete: v.autoComplete } : {}),\n ...(v?.inputMode ? { inputMode: v.inputMode } : {}),\n ...(v?.enterKeyHint ? { enterKeyHint: v.enterKeyHint } : {}),\n ...(v?.labelField ? { labelField: v.labelField } : {}),\n ...(v?.missingLabel ? { missingLabel: v.missingLabel } : {}),\n ...(field.enumValues?.length\n ? { options: Object.freeze(field.enumValues.map((value) => Object.freeze({ value, label: valueLabel(name, value) }))) }\n : {}),\n ...(links.has(name) ? { link: links.get(name)! } : {}),\n ...(v?.visible ? { visible: v.visible } : {}),\n });\n }));\n resolvedForms.set(mode, out);\n return out;\n };\n const writable = (mode: \"create\" | \"edit\") => Object.freeze(form(mode).filter((f) => !f.readOnly).map((f) => f.field.name));\n\n // ── Guards and summary ───────────────────────────────────────────────\n const guards = definition.can ?? {};\n // `can(\"create\", viewer)` and `can(\"update\", row, viewer)`; no viewer means no one (fail closed).\n function can(action: \"create\" | \"update\" | \"delete\", rowOrViewer?: Row | Viewer, maybeViewer?: Viewer): Allowed {\n // Plain JavaScript can pass a row to create: that row would be read as the viewer.\n if (action === \"create\" && maybeViewer !== undefined) throw new TypeError(`[genesis-core] ${contract.name}: can(\"create\", viewer) takes no row`);\n if (action === \"create\") return guards.create?.((rowOrViewer as Viewer | undefined) ?? NO_VIEWER) ?? true;\n const guard = guards[action];\n const row = rowOrViewer as Row | undefined;\n return guard && row ? guard(row, maybeViewer ?? NO_VIEWER) : true;\n }\n const actionGuards = new Map(actionList.map((a) => [a.name, a.can]));\n const resolvedActions: readonly ResolvedViewAction[] = Object.freeze(\n actionList.map((a) =>\n Object.freeze({\n name: a.name,\n label: a.label,\n ...(a.confirm !== undefined ? { confirm: a.confirm } : {}),\n ...(a.description !== undefined ? { description: a.description } : {}),\n ...(a.destructive ? { destructive: true } : {}),\n }),\n ),\n );\n function canAction(name: string, row: Row, viewer: Viewer = NO_VIEWER): Allowed {\n if (!actionGuards.has(name)) throw new ViewDefinitionError(contract.name, [`no action \"${name}\"`]);\n const guard = actionGuards.get(name);\n if (!guard) return true;\n const result: unknown = guard(row, viewer);\n // Only `true` allows; a reason is shown as given; anything else (false, \"\", undefined) refuses.\n if (result === true) return true;\n return typeof result === \"string\" && result.trim() ? result : \"This isn't allowed.\";\n }\n const summary = (row: Row): RowSummary => {\n if (definition.summary) return definition.summary(row);\n const value = labelField ? row[labelField] : undefined;\n return { title: value === null || value === undefined || value === \"\" ? titleCase(noun) : String(value) };\n };\n\n const galleryItem = (row: Row, override?: Partial<ViewGallery>): GalleryItem | undefined => {\n const block = { ...gallery, ...override };\n if (!block.image) return undefined;\n // A row without an image is still a photo: an empty `src`, which the grids draw as a placeholder.\n const image = row[block.image];\n const src = typeof image === \"string\" ? image : \"\";\n const number = (name: string | undefined) => {\n const value = name ? Number(row[name]) : NaN;\n return Number.isFinite(value) && value > 0 ? value : undefined;\n };\n const text = (name: string | undefined) => {\n const value = name ? row[name] : undefined;\n return value === null || value === undefined || value === \"\" ? undefined : String(value);\n };\n const width = number(block.width);\n const height = number(block.height);\n const caption = text(block.caption);\n const alt = text(block.alt) ?? summary(row).title;\n return {\n id: String(encodeRecordKey(contract, row as DataRow)),\n src,\n alt,\n ...(width !== undefined && height !== undefined ? { width, height } : {}),\n ...(caption !== undefined ? { caption } : {}),\n };\n };\n\n return Object.freeze({\n contract,\n definition: Object.freeze({\n ...definition,\n fields: viewFields,\n columns: columnLists,\n presets,\n ...(definition.form ? { form: formItems } : {}),\n ...(definition.scope ? { scope: Object.freeze([...definition.scope]) } : {}),\n ...(definition.actions ? { actions: actionList } : {}),\n ...(calendar ? { calendar } : {}),\n ...(board ? { board } : {}),\n ...(gallery ? { gallery } : {}),\n }) as Readonly<ViewDefinition<C, Row>>,\n resource: contract.name,\n noun,\n nounPlural,\n title,\n labelField,\n presets: presetNames,\n field: (name: string) => byName.get(name),\n column: (name: string) => (byName.has(name) && readable(name) ? fieldColumn(name) : undefined),\n label,\n display,\n valueLabel,\n columns,\n form,\n writable,\n can: can as ResourceView<C, Row>[\"can\"],\n actions: () => resolvedActions,\n canAction,\n summary,\n galleryItem,\n });\n}\n","// rowPicture: what to draw for a row's picture (docs/RESOURCE-VIEW.md, \"summary\"). Pure, so web,\n// native and the extension draw the same image or initials, behind the same URL check.\n\nimport { isSafeUrl } from \"../urls\";\nimport type { RowPicture, RowSummary } from \"./types\";\n\nlet segmenter: Intl.Segmenter | null | undefined;\n\n// The first letter of a word, as a whole character: \"é\" keeps its accent, \"李\" is a letter, and\n// punctuation, digits and emoji never count.\nconst LETTER = /^\\p{L}/u;\nfunction lettersOf(word: string): string[] {\n if (segmenter === undefined) {\n segmenter = typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\" ? new Intl.Segmenter(undefined, { granularity: \"grapheme\" }) : null;\n }\n const parts = segmenter ? Array.from(segmenter.segment(word), (s) => s.segment) : Array.from(word);\n return parts.filter((part) => LETTER.test(part));\n}\nfunction firstLetter(word: string): string {\n return lettersOf(word)[0] ?? \"\";\n}\n\n/**\n * First and last initial of a name, from letters only: \"Ada Lovelace\" → \"AL\", \"Ana-María López\"\n * → \"AL\", \"李 小龙\" → \"李小\", \"Cher\" → \"C\". Empty when the name has no letters (\" \", \"🎉🎉\").\n *\n * `distinct: true` gives a one-word name its first two letters (\"Probe\" → \"Pr\", \"Polish\" → \"Po\"),\n * so people who share an initial still differ in a list. Names of two words or more are unchanged.\n */\nexport function initialsOf(name: string | undefined, options: { distinct?: boolean | undefined } = {}): string {\n const words = (name ?? \"\").trim().split(/\\s+/);\n const letters = words.map(firstLetter).filter(Boolean);\n if (letters.length === 0) return \"\";\n const upper = (l: string) => (l.toUpperCase().length === l.length ? l.toUpperCase() : l);\n if (letters.length === 1 && options.distinct) {\n const word = words.find((w) => firstLetter(w))!;\n const second = lettersOf(word)[1];\n // One character each: \"ß\" stays \"ß\" rather than becoming \"SS\".\n return upper(letters[0]!) + (second ? (second.toLowerCase().length === second.length ? second.toLowerCase() : second) : \"\");\n }\n const pair = letters.length === 1 ? [letters[0]!] : [letters[0]!, letters[letters.length - 1]!];\n // One character each: \"ß\" stays \"ß\" rather than becoming \"SS\".\n return pair.map(upper).join(\"\");\n}\n\n/** An image source: `isSafeUrl`, and only http(s) or a root-relative path (never mailto, tel or `#x`). */\nfunction isImageSrc(src: unknown): src is string {\n if (!isSafeUrl(src)) return false;\n const value = src.trim();\n return value.startsWith(\"/\") || /^https?:/i.test(value);\n}\n\n/**\n * What to draw for a summary's picture:\n *\n * ```ts\n * rowPicture({ title: \"Ada\", image: { src: \"https://…/ada.png\", name: \"Ada Lovelace\" } });\n * // { kind: \"image\", src: \"https://…/ada.png\", alt: \"\", fallback: \"AL\" }\n * rowPicture({ title: \"Ada\", image: { src: \"javascript:x\", name: \"Ada Lovelace\" } });\n * // { kind: \"initials\", text: \"AL\" }\n * ```\n *\n * `null` when the summary has no `image`, or neither a safe `src` nor a `name` with letters.\n */\nexport function rowPicture(summary: RowSummary): RowPicture | null {\n const image = summary.image;\n if (!image) return null;\n const initials = initialsOf(image.name);\n if (isImageSrc(image.src)) return { kind: \"image\", src: image.src.trim(), alt: image.alt ?? \"\", fallback: initials };\n return initials ? { kind: \"initials\", text: initials } : null;\n}\n","// groupRows: a view's rows under headers by its `groupBy` field (or another), with no React, so a\n// custom view on the web, a phone screen and a server export group the same way.\n\nimport type { DataRow, ResourceContract } from \"../schema/types\";\nimport type { ResourceView } from \"./types\";\n\n/**\n * One group of rows: the value they share, its words and the rows, in the order they came.\n *\n * @stability Beta\n */\nexport interface RowGroup<Row extends DataRow = DataRow> {\n /** Stable, for list keys: the value as text, or `\"\"` for rows with no value. */\n readonly key: string;\n /** The value the rows share (`null` for the group with none). */\n readonly value: unknown;\n /** The value in words (`view.valueLabel`), or `emptyLabel` for the group with none. */\n readonly label: string;\n readonly rows: readonly Row[];\n}\n\n/** @stability Beta */\nexport interface GroupRowsOptions {\n /** The field to group by. Default the view's `groupBy`. */\n field?: string;\n /** The words for rows with no value. Default \"No {field label}\". */\n emptyLabel?: string;\n}\n\nconst isEmpty = (value: unknown) => value === null || value === undefined || value === \"\";\n\n/**\n * A view's rows in groups, in the order each group first appears (the server's sort, so loading\n * more never reorders what's on screen). Without a field (no `groupBy` and none given), one group\n * holding every row, with an empty label.\n *\n * ```ts\n * for (const group of groupRows(tasksView, rows)) console.log(group.label, group.rows.length);\n * ```\n *\n * @stability Beta\n */\nexport function groupRows<Row extends DataRow>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract; Row is what matters here\n view: ResourceView<ResourceContract<any>, Row>,\n rows: readonly Row[],\n options: GroupRowsOptions = {},\n): RowGroup<Row>[] {\n const field = options.field ?? (view.definition.groupBy as string | undefined);\n if (!field) return rows.length ? [Object.freeze({ key: \"\", value: null, label: \"\", rows: Object.freeze([...rows]) })] : [];\n const groups = new Map<string, { key: string; value: unknown; label: string; rows: Row[] }>();\n for (const row of rows) {\n const value = row[field];\n const key = isEmpty(value) ? \"\" : String(value);\n let group = groups.get(key);\n if (!group) {\n const label = isEmpty(value) ? (options.emptyLabel ?? `No ${view.label(field).toLowerCase()}`) : view.valueLabel(field, value);\n group = { key, value: isEmpty(value) ? null : value, label, rows: [] };\n groups.set(key, group);\n }\n group.rows.push(row);\n }\n return [...groups.values()].map((g) => Object.freeze({ ...g, rows: Object.freeze(g.rows) }));\n}\n","// Tree mode: nested records drawn from a flat list. Each row names its parent; the tree is built\n// from the data, never from nested input, so caching and writes stay the flat list's. No React:\n// genesis-ui's `useResourceView` holds the state and draws it, and a native list can reuse it.\n// docs/RESOURCE-VIEW.md, \"Tree mode\".\n\n/**\n * A screen's `tree` (`<ResourceView tree={{ getParentId }} />`): rows nest under the row\n * `getParentId` names. Client-side data only: every row is loaded, and children are never\n * fetched on expand.\n */\nexport interface ResourceTree<T> {\n /** The parent row's key (the same text as the row key), or `null` / `undefined` / `\"\"` for a root. */\n getParentId: (row: T) => string | null | undefined;\n /**\n * Which rows start open (uncontrolled): `true` every parent, a number the parents shallower\n * than that depth (`1` opens the roots), `false` none. Default `false`.\n */\n defaultExpanded?: boolean | number;\n /** The open rows by key, controlled. Leave unset and the screen keeps its own. */\n expanded?: ReadonlySet<string>;\n /** Called with the next open set whenever a row opens or closes. */\n onExpandedChange?: (expanded: Set<string>) => void;\n /** Selecting a row selects its descendants too, and clearing it clears them. Default `false`. */\n cascadeSelect?: boolean;\n}\n\n/** How to read the tree out of flat rows. */\nexport interface TreeOptions<T> {\n /** A row's own id. */\n getId: (row: T) => string;\n /** The parent's id; `null`, `undefined` or `\"\"` for a root. A parent that isn't loaded makes a root too. */\n getParentId: (row: T) => string | null | undefined;\n /**\n * Which nodes are open: their ids, or `\"all\"`. A closed node's descendants aren't returned.\n * While `match` is set, every ancestor of a match is open regardless, so each match shows.\n */\n expanded: ReadonlySet<string> | \"all\";\n /**\n * The filter, when one is active: rows that match it, and their ancestors (so a match keeps its\n * context), are kept; everything else is left out. Undefined: no filter, every row is kept.\n */\n match?: (row: T) => boolean;\n /**\n * The sort, applied within each set of siblings (stable: ties keep the rows' order). Without it,\n * siblings keep the rows' order, so a list sorted beforehand is sorted within siblings too.\n */\n compare?: (a: T, b: T) => number;\n}\n\n/** One visible row of the tree, in display order. */\nexport interface TreeNode<T> {\n row: T;\n id: string;\n /** The parent's id as drawn: `null` for a root (a missing parent, or a broken cycle, counts as none). */\n parentId: string | null;\n /** 0 for a root. */\n depth: number;\n /** Whether it has children among the kept rows (so a toggle makes sense). */\n hasChildren: boolean;\n /** Whether it is open. Always false without children. */\n expanded: boolean;\n /** False for an ancestor kept only as a match's context; true otherwise, and always true without a filter. */\n matched: boolean;\n /** 1-based position among its kept siblings, and how many there are (`aria-posinset`, `aria-setsize`). */\n position: number;\n siblings: number;\n}\n\n/** What {@link treeRows} returns. */\nexport interface TreeResult<T> {\n /** The rows to draw, in order: each parent before its children, siblings in input order. */\n visible: TreeNode<T>[];\n /** Every kept row's node by id, collapsed ones included. */\n nodes: ReadonlyMap<string, TreeNode<T>>;\n /** Every descendant of a node among the kept rows, depth-first, collapsed or not. */\n descendants: (id: string) => string[];\n /** The ids of every kept node that has children: \"expand all\". */\n parents: () => string[];\n}\n\nconst rootish = (parent: string | null | undefined): parent is null | undefined | \"\" => parent == null || parent === \"\";\n\n/**\n * Build the tree from flat rows. Siblings are sorted by `compare`, else keep the rows' order, so\n * either way the sort applies within each set of siblings. A row whose parent isn't among `rows` is a root,\n * and so is a row whose parent would close a cycle (each cycle loses one link). Duplicate ids keep\n * the first row.\n */\nexport function treeRows<T>(rows: readonly T[], options: TreeOptions<T>): TreeResult<T> {\n const { getId, getParentId, expanded, match, compare } = options;\n const byId = new Map<string, T>();\n const order: string[] = [];\n for (const row of rows) {\n const id = getId(row);\n if (byId.has(id)) continue;\n byId.set(id, row);\n order.push(id);\n }\n\n // The parent each row hangs from: absent, unloaded or cyclic parents make a root.\n const parentOf = new Map<string, string | null>();\n const resolving = new Set<string>();\n const resolve = (id: string): string | null => {\n if (parentOf.has(id)) return parentOf.get(id)!;\n const raw = getParentId(byId.get(id)!);\n let parent: string | null = rootish(raw) || raw === id || !byId.has(raw) ? null : raw;\n if (parent !== null) {\n resolving.add(id);\n // Walk up: meeting a row still being resolved means a cycle; break it here.\n if (resolving.has(parent)) parent = null;\n else resolve(parent);\n resolving.delete(id);\n }\n parentOf.set(id, parent);\n return parent;\n };\n for (const id of order) resolve(id);\n // A cycle's other members may have resolved through the broken one before it broke: recheck\n // that every chain ends at a root.\n for (const id of order) {\n const seen = new Set<string>([id]);\n let at = parentOf.get(id) ?? null;\n while (at !== null && !seen.has(at)) {\n seen.add(at);\n at = parentOf.get(at) ?? null;\n }\n if (at !== null) parentOf.set(id, null);\n }\n\n // What the filter keeps: matches, and every ancestor of one.\n let kept: Set<string> | null = null;\n const matched = new Set<string>();\n if (match) {\n kept = new Set();\n for (const id of order) {\n if (!match(byId.get(id)!)) continue;\n matched.add(id);\n for (let at: string | null = id; at !== null && !kept.has(at); at = parentOf.get(at) ?? null) kept.add(at);\n }\n }\n\n const children = new Map<string | null, string[]>();\n for (const id of order) {\n if (kept && !kept.has(id)) continue;\n const parent = parentOf.get(id) ?? null;\n const list = children.get(parent);\n if (list) list.push(id);\n else children.set(parent, [id]);\n }\n // Sort within siblings only: a child never leaves its parent. Array sort is stable.\n if (compare) for (const list of children.values()) list.sort((a, b) => compare(byId.get(a)!, byId.get(b)!));\n\n const isOpen = (id: string) => (match ? true : expanded === \"all\" || expanded.has(id));\n const nodes = new Map<string, TreeNode<T>>();\n const visible: TreeNode<T>[] = [];\n const visit = (parent: string | null, depth: number, shown: boolean) => {\n const ids = children.get(parent) ?? [];\n ids.forEach((id, index) => {\n const hasChildren = (children.get(id)?.length ?? 0) > 0;\n const open = hasChildren && isOpen(id);\n const node: TreeNode<T> = {\n row: byId.get(id)!,\n id,\n parentId: parent,\n depth,\n hasChildren,\n expanded: open,\n matched: match ? matched.has(id) : true,\n position: index + 1,\n siblings: ids.length,\n };\n nodes.set(id, node);\n if (shown) visible.push(node);\n visit(id, depth + 1, shown && open);\n });\n };\n visit(null, 0, true);\n\n const descendants = (id: string): string[] => {\n const out: string[] = [];\n const walk = (at: string) => {\n for (const child of children.get(at) ?? []) {\n out.push(child);\n walk(child);\n }\n };\n walk(id);\n return out;\n };\n const parents = () => [...nodes.values()].filter((n) => n.hasChildren).map((n) => n.id);\n return { visible, nodes, descendants, parents };\n}\n\n/**\n * The open ids a tree starts with: `true` opens every parent, a number opens parents shallower\n * than that depth (`1` opens the roots), `false` or nothing opens none.\n */\nexport function initialExpanded<T>(rows: readonly T[], options: Omit<TreeOptions<T>, \"expanded\" | \"match\">, open: boolean | number | undefined): Set<string> {\n if (!open) return new Set();\n const tree = treeRows(rows, { ...options, expanded: \"all\" });\n const depth = open === true ? Infinity : open;\n return new Set(tree.parents().filter((id) => tree.nodes.get(id)!.depth < depth));\n}\n\n/** The open set with `id` opened or closed: a new set, or the same one when nothing changes. */\nexport function setExpanded(expanded: ReadonlySet<string>, id: string, open: boolean): ReadonlySet<string> {\n if (expanded.has(id) === open) return expanded;\n const next = new Set(expanded);\n if (open) next.add(id);\n else next.delete(id);\n return next;\n}\n\n/**\n * The selection after toggling `id` with cascade: the node and every descendant take the node's\n * new state. Without cascade, use a plain toggle; selection never cascades by default.\n */\nexport function cascadeSelection(selected: ReadonlySet<string>, id: string, descendants: readonly string[]): Set<string> {\n const next = new Set(selected);\n const on = !selected.has(id);\n for (const at of [id, ...descendants]) {\n if (on) next.add(at);\n else next.delete(at);\n }\n return next;\n}\n","// defineRecordView: one record's screen from a view (docs/RESOURCE-VIEW.md, \"RecordView\").\n// A header (the row's summary and the view's actions), sections (a child list, a few settings, or\n// a slot the screen fills) and readiness checks. Checked once and frozen like defineView, with no\n// React, so web and native draw the same screen from it.\n\nimport { encodeRecordKey } from \"../schema/keys\";\nimport type { Identifier } from \"../provider/types\";\nimport { readinessOf, type Readiness } from \"../resource\";\nimport type { DataRow, FieldSchema, ResourceContract } from \"../schema/types\";\nimport { ViewDefinitionError } from \"./errors\";\nimport type { Viewer } from \"../viewer\";\nimport type { Allowed, FieldNameOf, ResolvedFormField, ResourceView, RowOf, ViewTone } from \"./types\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a child list can be any resource\ntype AnyView = ResourceView<ResourceContract<any>, any>;\n\n/** Equality filters for a child list, sent to the server: `{ brand_id: brand.id }`. `null` is \"is empty\". */\nexport type RecordViewFilter = Readonly<Record<string, string | number | boolean | null>>;\n\ninterface SectionBase {\n /** Unique in the record view; the screen's route segment or slot key. */\n id: string;\n label: string;\n}\n\n/** A child list: another view, filtered by this record. */\nexport interface RecordViewListSection<Row extends DataRow = DataRow> extends SectionBase {\n list: { view: AnyView; filter: (row: Row) => RecordViewFilter };\n settings?: never;\n}\n\n/** A few of this record's own fields, edited in place. Each must be in `view.writable(\"edit\")`. */\nexport interface RecordViewSettingsSection<Name extends string = string> extends SectionBase {\n settings: readonly Name[];\n list?: never;\n}\n\n/** A section the screen fills itself, through a slot keyed by `id`. */\nexport interface RecordViewSlotSection extends SectionBase {\n list?: never;\n settings?: never;\n}\n\nexport type RecordViewSection<Row extends DataRow = DataRow, Name extends string = string> =\n | RecordViewListSection<Row>\n | RecordViewSettingsSection<Name>\n | RecordViewSlotSection;\n\n/** One readiness check: \"Has a logo\", ok or not, and why not. */\nexport interface RecordViewReadinessItem {\n /** A stable key for the check; default its position and title. */\n id?: string;\n title: string;\n ok: boolean;\n reason?: string;\n /** Genesis chip tones only. Default `success` when ok, `warning` when not. */\n tone?: ViewTone;\n}\n\n/**\n * A record page template (ADR 0021): `standard` (a header with the summary and actions, then the\n * sections) or `document` (a cover, an icon, a large title, the properties, then the body, like\n * a page in a notes app).\n *\n * @stability Beta\n */\nexport type RecordPageTemplate = \"standard\" | \"document\";\n\n/**\n * Where a `document` template finds its parts, by field name. Each is optional; a part whose\n * field is empty on a row isn't drawn.\n *\n * @stability Beta\n */\nexport interface RecordViewDocument<Name extends string = string> {\n /** A text field holding the cover image's URL. */\n cover?: Name;\n /** A text field holding the icon: an emoji or a short text, or an image's URL. */\n icon?: Name;\n /** The fields listed under the title, as label and value, in order. */\n properties?: readonly Name[];\n /** The long text below the properties. */\n body?: Name;\n}\n\n/** What `defineRecordView` accepts. */\nexport interface RecordViewDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> {\n /** The view actions the header offers, by name, in order. Default: every view action. */\n header?: { actions?: readonly string[] };\n /** The sections. A `document` template may have none (the document is the page). */\n sections: readonly RecordViewSection<Row, FieldNameOf<C>>[];\n readiness?: (row: Row) => readonly RecordViewReadinessItem[];\n /** The record page template. Default `standard`, the page as before. */\n template?: RecordPageTemplate;\n /** With `template: \"document\"`: the fields its cover, icon, properties and body show. */\n document?: RecordViewDocument<FieldNameOf<C>>;\n}\n\n/** A section as a renderer draws it. */\nexport type ResolvedRecordViewSection =\n | { readonly id: string; readonly label: string; readonly kind: \"list\"; readonly view: AnyView }\n | { readonly id: string; readonly label: string; readonly kind: \"settings\"; readonly settings: readonly string[] }\n | { readonly id: string; readonly label: string; readonly kind: \"slot\" };\n\n/** A header action with whether this row allows it. */\nexport interface RecordViewHeaderAction {\n readonly name: string;\n readonly label: string;\n readonly confirm?: string;\n readonly description?: string;\n readonly destructive?: boolean;\n /** `true`, or the view guard's reason. Only narrows what the server allows. */\n readonly allowed: Allowed;\n}\n\n/** The header for one row: the view's summary plus the header's actions. */\nexport interface RecordViewHeader {\n readonly title: string;\n readonly subtitle?: string;\n readonly chips: readonly { label: string; tone?: ViewTone }[];\n readonly actions: readonly RecordViewHeaderAction[];\n}\n\n/** What a screen and its provider add to the header: they only narrow the view's guards. */\nexport interface RecordViewHeaderOptions<Row extends DataRow = DataRow> {\n /** The screen's own rule: `false` hides the action, a sentence refuses it with that reason. */\n can?: (action: string, row: Row) => Allowed | boolean;\n /** Whether anything can run actions here (the screen's `onAction`, or the provider's `runAction`). `false` hides them all. */\n runnable?: boolean;\n /** The action names the provider reports serving (`ResourceSchema.actions`), when it reports them. Others are hidden. */\n served?: readonly string[];\n /** Who is looking (`useViewer()`), for the view's action guards. Without it they get no one. */\n viewer?: Viewer;\n}\n\n/** A readiness check with its tone resolved. */\nexport interface ResolvedReadinessItem {\n /** Stable, for list keys: the check's `id`, or its position and title. */\n readonly key: string;\n readonly title: string;\n readonly ok: boolean;\n readonly reason?: string;\n readonly tone: ViewTone;\n}\n\n/**\n * Any record view, whatever its contract: the type a view's `recordView` returns. Name it on that\n * function (`recordView: (): AnyRecordView => brandRecordView`), since the record view is defined\n * from the view and TypeScript can't infer one from the other.\n *\n * @stability Beta\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract and row, by design\nexport type AnyRecordView = RecordView<ResourceContract<any>, any>;\n\n/** What `defineRecordView` returns: frozen, with pure helpers for the renderers. */\nexport interface RecordView<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> {\n readonly view: ResourceView<C, Row>;\n readonly sections: readonly ResolvedRecordViewSection[];\n /** The header's action names, in order. */\n readonly headerActions: readonly string[];\n readonly hasReadiness: boolean;\n /** The record page template: `standard` unless the definition says `document`. */\n readonly template: RecordPageTemplate;\n /** The document template's fields (frozen); empty for `standard`. */\n readonly document: Readonly<RecordViewDocument>;\n section(id: string): ResolvedRecordViewSection | undefined;\n /** The record's address for the provider: its key fields (`keyFields`), composite keys encoded. */\n recordId(row: Row): Identifier;\n /**\n * Why settings can't be saved for this row and viewer: the view's `can(\"update\", row, viewer)`\n * reason, or `null` when they can. Renderers then show the settings read-only with the reason.\n * Without a viewer the guard gets no one, so one that needs the viewer locks them.\n */\n settingsLocked(row: Row, viewer?: Viewer): string | null;\n headerFor(row: Row, options?: RecordViewHeaderOptions<Row>): RecordViewHeader;\n /**\n * Settings fields as the view's form resolves them (`view.form(\"edit\")`), in the order listed:\n * one section's, or every settings section's without an id.\n */\n settingsFields(sectionId?: string): readonly ResolvedFormField[];\n /** Only the section's listed keys that `values` has: what a save sends. */\n settingsPatch(sectionId: string, values: Readonly<Record<string, unknown>>): Record<string, unknown>;\n /**\n * A list section's filter for this row. In development, a filter with no key, or a value that\n * isn't a string, number, boolean or null, throws: it would show every child row.\n */\n listFilter(sectionId: string, row: Row): RecordViewFilter;\n /** The readiness checks for this row, tones resolved; empty without `readiness`. */\n readinessFor(row: Row): readonly ResolvedReadinessItem[];\n /**\n * The checks in one chip's terms (genesis-core/resource's `readinessOf`): an unmet `danger`\n * check is a problem, any other unmet check one to look at. `null` without `readiness`. Draw\n * it with `readinessChip`.\n */\n readinessSummary(row: Row): Readiness | null;\n}\n\nconst WORKSPACE = Symbol.for(\"genesis.resource-workspace\");\n/** The reason shown when a guard refuses without one. */\nconst REFUSED = \"This isn't allowed.\";\nconst TONES: ReadonlySet<string> = new Set<ViewTone>([\"success\", \"warning\", \"danger\", \"info\", \"muted\"]);\nconst SECTION_KEYS: ReadonlySet<string> = new Set([\"id\", \"label\", \"list\", \"settings\"]);\nconst DOCUMENT_KEYS: ReadonlySet<string> = new Set([\"cover\", \"icon\", \"properties\", \"body\"]);\nconst dev = () => process.env.NODE_ENV !== \"production\";\n\n/** Why a field can't be a setting edited in place, or null when it can. */\nfunction unsettable(field: FieldSchema | undefined): string | null {\n if (!field) return null;\n const facts = field as FieldSchema & { sensitive?: boolean };\n if (field.type === \"json\") return \"is JSON\";\n if (field.array) return \"is a list\";\n if (field.references || field.type === \"relation\") return \"is a link\";\n if (facts.sensitive) return \"is sensitive\";\n return null;\n}\n\n/**\n * Whether two values are the same as a settings form holds them: 2 and \"2\", and null, undefined\n * and \"\", are the same. A settings section compares an edit with the row through it, so an edit\n * back to the stored value isn't a change (web and native RecordView).\n */\nexport function sameFormValue(a: unknown, b: unknown): boolean {\n const text = (v: unknown) => (v === null || v === undefined ? \"\" : Array.isArray(v) ? v.join(\",\") : String(v));\n return text(a) === text(b);\n}\n\n/** Whether a value is a record view (`defineRecordView`'s result). */\nexport function isRecordView(value: unknown): value is RecordView {\n return typeof value === \"object\" && value !== null && (value as Record<symbol, unknown>)[WORKSPACE] === true;\n}\n\nfunction isView(value: unknown): value is AnyView {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as AnyView).columns === \"function\" &&\n typeof (value as AnyView).resource === \"string\"\n );\n}\n\n/**\n * One record's screen from its view:\n *\n * ```ts\n * export const brandRecordView = defineRecordView(brandsView, {\n * header: { actions: [\"archive\"] },\n * sections: [\n * { id: \"products\", label: \"Products\", list: { view: productsView, filter: (b) => ({ brand_id: b.id }) } },\n * { id: \"settings\", label: \"Settings\", settings: [\"name\", \"website\"] },\n * { id: \"activity\", label: \"Activity\" }, // the screen fills it\n * ],\n * readiness: (b) => [{ title: \"Has a website\", ok: !!b.website, reason: \"Add the website.\" }],\n * });\n * ```\n *\n * Throws {@link ViewDefinitionError} for a settings field the view can't write, a header action\n * the view doesn't define, a repeated section id, or a section that holds another record view.\n */\nexport function defineRecordView<C extends ResourceContract, Row extends DataRow = RowOf<C>>(\n view: ResourceView<C, Row>,\n definition: RecordViewDefinition<C, Row>,\n): RecordView<C, Row> {\n const where = `${view.resource} record view`;\n const problems: string[] = [];\n const writable = new Set(view.writable(\"edit\"));\n const actionNames = new Set(view.actions().map((a) => a.name));\n\n // ── Sections ─────────────────────────────────────────────────────────\n const input = Array.isArray(definition?.sections) ? definition.sections : [];\n const template: RecordPageTemplate = definition?.template ?? \"standard\";\n if (template !== \"standard\" && template !== \"document\") problems.push(`template is \"standard\" or \"document\", not ${JSON.stringify(template)}`);\n if (!Array.isArray(definition?.sections)) problems.push(\"sections isn't a list\");\n else if (input.length === 0 && template !== \"document\") problems.push(\"sections is empty\");\n const ids = new Set<string>();\n const settingsSeen = new Set<string>();\n const sections: ResolvedRecordViewSection[] = [];\n const filters = new Map<string, (row: Row) => RecordViewFilter>();\n input.forEach((raw, i) => {\n const at = `sections[${i}]`;\n if (!raw || typeof raw !== \"object\") {\n problems.push(`${at} isn't a section`);\n return;\n }\n const s = raw as RecordViewSection<Row> & Record<string, unknown>;\n const name = typeof s.id === \"string\" && s.id.trim() ? s.id : undefined;\n if (!name) problems.push(`${at} has no id`);\n else if (ids.has(name)) problems.push(`sections lists \"${name}\" twice`);\n else ids.add(name);\n const label = `sections.${name ?? i}`;\n if (typeof s.label !== \"string\" || !s.label.trim()) problems.push(`${label} has no label`);\n if (isRecordView(s) || \"sections\" in s || \"workspace\" in s) {\n problems.push(`${label} holds a record view; sections don't nest`);\n return;\n }\n const unknown = Object.keys(s).filter((k) => !SECTION_KEYS.has(k));\n if (unknown.length) problems.push(`${label} has ${unknown.map((k) => `\"${k}\"`).join(\", \")}, which isn't a section key (id, label, list, settings)`);\n const hasList = s.list !== undefined;\n const hasSettings = s.settings !== undefined;\n if (hasList && hasSettings) {\n problems.push(`${label} has both list and settings; a section has one`);\n return;\n }\n if (hasList) {\n const list = s.list as { view?: unknown; filter?: unknown };\n if (isRecordView(list?.view)) problems.push(`${label}.list.view is a record view; sections don't nest`);\n else if (!isView(list?.view)) problems.push(`${label}.list.view isn't a view`);\n if (typeof list?.filter !== \"function\") problems.push(`${label}.list.filter isn't a function`);\n if (name && isView(list?.view) && !isRecordView(list.view) && typeof list.filter === \"function\") {\n filters.set(name, list.filter as (row: Row) => RecordViewFilter);\n sections.push(Object.freeze({ id: name, label: s.label, kind: \"list\", view: list.view }));\n }\n return;\n }\n if (hasSettings) {\n if (!Array.isArray(s.settings)) {\n problems.push(`${label}.settings isn't a list`);\n return;\n }\n if (s.settings.length === 0) problems.push(`${label}.settings lists no fields`);\n for (const field of s.settings as readonly string[]) {\n const why = unsettable(view.field(field));\n if (why) problems.push(`${label}.settings names \"${field}\", which ${why}; it needs an editor of its own`);\n else if (!writable.has(field)) problems.push(`${label}.settings names \"${field}\", which the view can't write on edit`);\n if (settingsSeen.has(field)) problems.push(`settings lists \"${field}\" twice`);\n settingsSeen.add(field);\n }\n if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: \"settings\", settings: Object.freeze((s.settings as readonly string[]).map(String)) }));\n return;\n }\n if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: \"slot\" }));\n });\n\n // ── Header and readiness ─────────────────────────────────────────────\n const requested = definition?.header?.actions;\n if (requested !== undefined && !Array.isArray(requested)) problems.push(\"header.actions isn't a list\");\n const headerActions = Object.freeze(\n Array.isArray(requested) ? [...requested] : view.actions().map((a) => a.name),\n );\n const headerSeen = new Set<string>();\n for (const name of headerActions) {\n if (!actionNames.has(name)) problems.push(`header.actions names \"${name}\", which isn't a view action`);\n if (headerSeen.has(name)) problems.push(`header.actions lists \"${name}\" twice`);\n headerSeen.add(name);\n }\n if (definition?.readiness !== undefined && typeof definition.readiness !== \"function\") {\n problems.push(\"readiness isn't a function\");\n }\n // ── The document template ────────────────────────────────────────────\n const doc = definition?.document;\n if (doc !== undefined) {\n if (!doc || typeof doc !== \"object\" || Array.isArray(doc)) problems.push(\"document isn't an object\");\n else {\n if (template !== \"document\") problems.push(`document is set, but template isn't \"document\"`);\n for (const key of Object.keys(doc)) if (!DOCUMENT_KEYS.has(key)) problems.push(`document.${key} isn't a document setting (cover, icon, properties, body)`);\n for (const key of [\"cover\", \"icon\", \"body\"] as const) {\n const name = doc[key];\n if (name === undefined) continue;\n const field = view.field(String(name));\n if (!field) problems.push(`document.${key} names \"${String(name)}\", which isn't a field`);\n else if (field.type !== \"string\" || field.array) problems.push(`document.${key} \"${String(name)}\" is a ${field.array ? \"list\" : field.type}, not a text field`);\n }\n if (doc.properties !== undefined) {\n if (!Array.isArray(doc.properties)) problems.push(\"document.properties isn't a list\");\n else for (const name of doc.properties) if (!view.field(String(name))) problems.push(`document.properties names \"${String(name)}\", which isn't a field`);\n }\n }\n }\n if (problems.length) throw new ViewDefinitionError(where, problems);\n const document: Readonly<RecordViewDocument> = Object.freeze(\n doc ? { ...doc, ...(doc.properties ? { properties: Object.freeze([...doc.properties].map(String)) } : {}) } : {},\n );\n\n const frozenSections = Object.freeze(sections);\n const byId = new Map(frozenSections.map((s) => [s.id, s]));\n const actionByName = new Map(view.actions().map((a) => [a.name, a]));\n const readiness = definition.readiness;\n\n const settingsOf = (sectionId: string): readonly string[] => {\n const s = byId.get(sectionId);\n if (!s || s.kind !== \"settings\") throw new ViewDefinitionError(where, [`no settings section \"${sectionId}\"`]);\n return s.settings;\n };\n const resolvedSettings = new Map<string, readonly ResolvedFormField[]>();\n const settingsFields = (sectionId?: string): readonly ResolvedFormField[] => {\n const key = sectionId ?? \"\";\n const cached = resolvedSettings.get(key);\n if (cached) return cached;\n const names =\n sectionId === undefined\n ? frozenSections.flatMap((s) => (s.kind === \"settings\" ? s.settings : []))\n : settingsOf(sectionId);\n const form = new Map(view.form(\"edit\").map((f) => [f.field.name, f]));\n const out = Object.freeze(names.map((n) => form.get(n)).filter((f): f is ResolvedFormField => f !== undefined));\n resolvedSettings.set(key, out);\n return out;\n };\n\n const headerFor = (row: Row, options: RecordViewHeaderOptions<Row> = {}): RecordViewHeader => {\n const summary = view.summary(row);\n const served = options.served ? new Set(options.served) : null;\n const actions: RecordViewHeaderAction[] = [];\n if (options.runnable !== false) {\n for (const name of headerActions) {\n if (served && !served.has(name)) continue;\n const own = options.can?.(name, row);\n if (own === false) continue;\n // Guards only narrow: the screen's refusal wins, then the view's.\n const allowed: Allowed = typeof own === \"string\" ? own || REFUSED : view.canAction(name, row, options.viewer);\n actions.push(Object.freeze({ ...actionByName.get(name)!, allowed }));\n }\n }\n return Object.freeze({\n title: summary.title,\n ...(summary.subtitle !== undefined ? { subtitle: summary.subtitle } : {}),\n chips: Object.freeze([...(summary.chips ?? [])]),\n actions: Object.freeze(actions),\n });\n };\n\n const readinessFor = (row: Row): readonly ResolvedReadinessItem[] => {\n if (!readiness) return Object.freeze([]);\n return Object.freeze(\n readiness(row).map((item, i) => {\n let tone = item.tone ?? (item.ok ? \"success\" : \"warning\");\n if (!TONES.has(tone)) {\n if (dev()) console.warn(`[genesis-core] ${where}: readiness \"${item.title}\" has tone \"${String(tone)}\", which isn't a chip tone; showing it muted.`);\n tone = \"muted\";\n }\n return Object.freeze({\n key: item.id ?? `${i}:${item.title}`,\n title: item.title,\n ok: Boolean(item.ok),\n ...(item.reason !== undefined ? { reason: item.reason } : {}),\n tone,\n });\n }),\n );\n };\n\n const readinessSummary = (row: Row): Readiness | null =>\n readiness\n ? readinessOf(\n readinessFor(row)\n .filter((r) => !r.ok)\n .map((r) => ({ level: r.tone === \"danger\" ? (\"error\" as const) : (\"warning\" as const) })),\n )\n : null;\n\n return Object.freeze({\n [WORKSPACE]: true,\n view,\n sections: frozenSections,\n headerActions,\n hasReadiness: Boolean(readiness),\n template,\n document,\n section: (id: string) => byId.get(id),\n recordId: (row: Row) => encodeRecordKey(view.contract, row),\n settingsLocked: (row: Row, viewer?: Viewer) => {\n const allowed = view.can(\"update\", row, viewer);\n return allowed === true ? null : typeof allowed === \"string\" && allowed.trim() ? allowed : REFUSED;\n },\n headerFor,\n settingsFields,\n settingsPatch: (sectionId: string, values: Readonly<Record<string, unknown>>) => {\n const patch: Record<string, unknown> = {};\n for (const name of settingsOf(sectionId)) if (Object.hasOwn(values, name)) patch[name] = values[name];\n return patch;\n },\n listFilter: (sectionId: string, row: Row) => {\n const filter = filters.get(sectionId);\n if (!filter) throw new ViewDefinitionError(where, [`no list section \"${sectionId}\"`]);\n const out = filter(row);\n if (dev()) {\n const entries = out && typeof out === \"object\" ? Object.entries(out) : [];\n const bad = entries.filter(([, v]) => !(v === null || typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\"));\n if (entries.length === 0 || bad.length) {\n throw new ViewDefinitionError(where, [\n entries.length === 0\n ? `sections.${sectionId}.list.filter gave no keys, which would list every row`\n : `sections.${sectionId}.list.filter gives ${bad.map(([k]) => `\"${k}\"`).join(\", \")} no single value`,\n ]);\n }\n }\n return Object.freeze({ ...out });\n },\n readinessFor,\n readinessSummary,\n }) as RecordView<C, Row>;\n}\n\n// The names before record views were called record views (\"workspace\" now means where the viewer\n// is working: docs/adr/0004-workspaces.md). Kept for one minor release.\n\n/** @deprecated Renamed `defineRecordView`. Removed in the next major. @stability Deprecated */\nexport const defineWorkspace = defineRecordView;\n/** @deprecated Renamed `isRecordView`. Removed in the next major. @stability Deprecated */\nexport const isWorkspace = isRecordView;\n/** @deprecated Renamed `RecordView`. Removed in the next major. @stability Deprecated */\nexport type ResourceWorkspace<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> = RecordView<C, Row>;\n/** @deprecated Renamed `RecordViewDefinition`. */\nexport type WorkspaceDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> = RecordViewDefinition<C, Row>;\n/** @deprecated Renamed `RecordViewSection`. */\nexport type WorkspaceSection<Row extends DataRow = DataRow, Name extends string = string> = RecordViewSection<Row, Name>;\n/** @deprecated Renamed `RecordViewHeaderAction`. */\nexport type WorkspaceHeaderAction = RecordViewHeaderAction;\n","// defineWidget: a small tile on a dashboard or a record page's sidebar, fed by a view (ADR 0023).\n//\n// A widget is data, with no React: which view it reads (and so which resource, scope, preset\n// and permissions), what it needs from it (a total, or a few rows), its label and how its value\n// reads. genesis-ui's `<Widget>` draws it; a phone draws the same definition. The pure helpers\n// here (`resolveWidgetRequest`, `resolveStreak`, `resolveChartSeries`, `toWidgetText`) are what\n// both platforms compute, so they can't drift.\n\nimport { addDays, dayIn, deviceTimeZone, isDay, startOfWeek, type Day } from \"../dates\";\nimport type { ResourceScope } from \"../hooks/viewer-scope\";\nimport type { AggregateMetric, AggregateParams, FilterParam, SortParam } from \"../provider/types\";\nimport { toAggregateValues } from \"../provider/aggregate\";\nimport type { DataRow, ResourceContract } from \"../schema/types\";\nimport { ViewDefinitionError } from \"./errors\";\nimport { filterParams } from \"./link\";\nimport { scopeFilter } from \"./scope\";\nimport type { Allowed, ResourceView, Viewer } from \"./types\";\n\n/** The built-in kinds of widget. */\nexport type WidgetKind = \"number\" | \"progress\" | \"streak\" | \"list\" | \"chart\";\n\n/** How a widget's number reads: plain, short (`1.2k`), a percent of 1, a currency, or your own words. */\nexport type WidgetFormat =\n | \"number\"\n | \"compact\"\n | \"percent\"\n | { currency: string; maximumFractionDigits?: number }\n | ((value: number) => string);\n\ntype Scalar = string | number | boolean | null;\n/** Values a widget narrows its view by, as a screen's `filter`: `{ status: \"open\" }`, `{ owner_id: [a, b] }`. */\nexport type WidgetFilter = Readonly<Record<string, Scalar | readonly (string | number)[]>>;\n\n/** What every kind of widget says. */\nexport interface WidgetBase<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> {\n /** Stable, unique on its dashboard: a key, a test id, a saved layout's entry. */\n id: string;\n /** What the tile is called (\"Open deals\"). */\n label: string;\n /** The view it reads: its resource, scope keys, presets, fields and who may read them. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- any contract's view\n view: ResourceView<C, Row & any>;\n /** One of the view's presets: its filter narrows the rows, as a tab would. */\n preset?: string;\n /** More values to narrow by, over the scope and the preset. */\n filter?: WidgetFilter;\n /** A short line under the value (\"this quarter\"). */\n description?: string;\n /** Where the tile goes when pressed: the full view, usually. */\n href?: string;\n /**\n * Whether this viewer sees the tile: `true`, or the reason not. Only narrows; the view's own\n * field permissions (a field the viewer can't read) hide it too, and row security decides\n * which rows any total covers.\n */\n can?: (viewer: Viewer | undefined) => Allowed;\n /** Keep the tile current with changes made elsewhere (`DataProvider.subscribe`). Default true. */\n live?: boolean;\n}\n\n/** A number: a count, or the sum, average, lowest or highest of a field. */\nexport interface NumberWidget<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> extends WidgetBase<C, Row> {\n kind: \"number\";\n /** What to total. Default `{ fn: \"count\" }`. */\n metric?: AggregateMetric;\n format?: WidgetFormat;\n}\n\n/** Progress toward a goal: a total over a fixed number, or over another total (done of all). */\nexport interface ProgressWidget<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> extends WidgetBase<C, Row> {\n kind: \"progress\";\n /** What counts as done. Default `{ fn: \"count\" }` over the widget's rows. */\n metric?: AggregateMetric;\n /**\n * The goal: a number, or a total over the view's scope and `goalFilter` (not the preset or\n * `filter`): `{ fn: \"count\" }` with the preset \"done\" makes \"done of all\".\n */\n goal: number | AggregateMetric;\n /** Narrows the goal's rows when it is a total. */\n goalFilter?: WidgetFilter;\n format?: WidgetFormat;\n}\n\n/** A streak: how many days (or weeks) in a row, up to today, have at least one row. */\nexport interface StreakWidget<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> extends WidgetBase<C, Row> {\n kind: \"streak\";\n /** The date (or timestamp) field a row counts on. */\n dateField: string;\n /** Default `day`. Weeks start on Monday. */\n unit?: \"day\" | \"week\";\n /** The zone days are counted in. Default the device's. */\n timeZone?: string;\n /** The most recent rows read to count it. Default 400. */\n limit?: number;\n}\n\n/** A short list: the first few rows, as the view names them. */\nexport interface ListWidget<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> extends WidgetBase<C, Row> {\n kind: \"list\";\n /** Rows shown. Default 5, at most 50. */\n limit?: number;\n /** Their order. Default the view's `orderBy`. */\n sort?: SortParam;\n}\n\n/** A chart: one bar (or point) per value of a field, with a count or a total each. */\nexport interface ChartWidget<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> extends WidgetBase<C, Row> {\n kind: \"chart\";\n /** The field whose values are the bars. */\n groupBy: string;\n /** Each bar's height. Default `{ fn: \"count\" }`. */\n metric?: AggregateMetric;\n /** Default `bar`. */\n chart?: \"bar\" | \"line\";\n /** The most rows read to draw it. Default 1000. */\n limit?: number;\n format?: WidgetFormat;\n}\n\n/** What `defineWidget` accepts. */\nexport type WidgetDefinition<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> =\n | NumberWidget<C, Row>\n | ProgressWidget<C, Row>\n | StreakWidget<C, Row>\n | ListWidget<C, Row>\n | ChartWidget<C, Row>;\n\n/** A checked, frozen widget. */\nexport type DefinedWidget<C extends ResourceContract = ResourceContract, Row extends DataRow = DataRow> = Readonly<WidgetDefinition<C, Row>> & {\n readonly __widget: true;\n};\n\nconst ID = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;\n\nfunction metricProblems(where: string, metric: AggregateMetric | undefined, view: WidgetBase[\"view\"]): string[] {\n if (!metric || metric.fn === \"count\") return [];\n if (![\"sum\", \"avg\", \"min\", \"max\"].includes(metric.fn)) return [`${where}.fn: one of count, sum, avg, min, max`];\n if (!view.field(metric.field)) return [`${where}.field: \"${metric.field}\" isn't a field of ${view.resource}`];\n return [];\n}\n\n/** Every problem with a widget; empty when it is sound. */\nexport function widgetProblems(input: WidgetDefinition): string[] {\n const w = input as Partial<WidgetDefinition> & Record<string, unknown>;\n if (!w || typeof w !== \"object\") return [\"expected a widget\"];\n const problems: string[] = [];\n if (typeof w.id !== \"string\" || !ID.test(w.id)) problems.push(\"id: a letter, then letters, digits, - or _\");\n if (typeof w.label !== \"string\" || !w.label.trim()) problems.push(\"label: expected a non-empty string\");\n const view = w.view;\n if (!view || typeof view !== \"object\" || typeof view.field !== \"function\") return [...problems, \"view: a view from defineView\"];\n if (w.preset !== undefined && !view.definition.presets?.[w.preset]) problems.push(`preset: ${view.resource} has no preset \"${w.preset}\"`);\n for (const field of Object.keys(w.filter ?? {})) if (!view.field(field)) problems.push(`filter.${field}: not a field of ${view.resource}`);\n const currency = (w as { format?: { currency?: unknown } }).format?.currency;\n if (currency !== undefined) {\n try {\n new Intl.NumberFormat(\"en\", { style: \"currency\", currency: String(currency) });\n } catch {\n problems.push(\"format.currency: an ISO 4217 code (USD, EUR)\");\n }\n }\n switch (w.kind) {\n case \"number\":\n problems.push(...metricProblems(\"metric\", w.metric, view));\n break;\n case \"progress\":\n problems.push(...metricProblems(\"metric\", w.metric, view));\n if (typeof w.goal === \"number\") {\n if (!(w.goal > 0)) problems.push(\"goal: a number above 0, or a total\");\n } else if (!w.goal || typeof w.goal !== \"object\") problems.push(\"goal: a number above 0, or a total\");\n else problems.push(...metricProblems(\"goal\", w.goal, view));\n for (const field of Object.keys(w.goalFilter ?? {})) if (!view.field(field)) problems.push(`goalFilter.${field}: not a field of ${view.resource}`);\n break;\n case \"streak\":\n if (typeof w.dateField !== \"string\" || !view.field(w.dateField)) problems.push(`dateField: not a field of ${view.resource}`);\n if (w.unit !== undefined && w.unit !== \"day\" && w.unit !== \"week\") problems.push(\"unit: day or week\");\n if (w.limit !== undefined && !(Number.isInteger(w.limit) && w.limit > 0 && w.limit <= 1000)) problems.push(\"limit: a whole number from 1 to 1000\");\n break;\n case \"list\":\n if (w.limit !== undefined && !(Number.isInteger(w.limit) && w.limit > 0 && w.limit <= 50)) problems.push(\"limit: a whole number from 1 to 50\");\n if (w.sort && !view.field(w.sort.field)) problems.push(`sort.field: not a field of ${view.resource}`);\n break;\n case \"chart\":\n if (typeof w.groupBy !== \"string\" || !view.field(w.groupBy)) problems.push(`groupBy: not a field of ${view.resource}`);\n problems.push(...metricProblems(\"metric\", w.metric, view));\n if (w.chart !== undefined && w.chart !== \"bar\" && w.chart !== \"line\") problems.push(\"chart: bar or line\");\n if (w.limit !== undefined && !(Number.isInteger(w.limit) && w.limit > 0 && w.limit <= 1000)) problems.push(\"limit: a whole number from 1 to 1000\");\n break;\n default:\n problems.push(\"kind: one of number, progress, streak, list, chart\");\n }\n return problems;\n}\n\n/**\n * Define a widget: a tile fed by a view. Checks it against the view (its fields, presets) and\n * returns it frozen. Throws {@link ViewDefinitionError} with every problem.\n *\n * ```ts\n * const openDeals = defineWidget({ id: \"open-deals\", kind: \"number\", label: \"Open deals\", view: dealsView, preset: \"open\" });\n * const pipeline = defineWidget({\n * id: \"pipeline\", kind: \"number\", label: \"Pipeline\", view: dealsView, preset: \"open\",\n * metric: { fn: \"sum\", field: \"amount\" }, format: { currency: \"USD\" },\n * });\n * ```\n *\n * @stability Beta\n */\nexport function defineWidget<C extends ResourceContract, Row extends DataRow>(input: WidgetDefinition<C, Row>): DefinedWidget<C, Row> {\n const problems = widgetProblems(input as unknown as WidgetDefinition);\n if (problems.length) throw new ViewDefinitionError(`widget ${String((input as { id?: unknown })?.id)}`, problems);\n // Shallow: the view inside is already frozen, and functions (format, can) stay as given.\n return Object.freeze({ ...input, __widget: true as const }) as DefinedWidget<C, Row>;\n}\n\n/** Whether a value is a widget from `defineWidget`. */\nexport function isWidget(value: unknown): value is DefinedWidget {\n return !!value && typeof value === \"object\" && (value as { __widget?: unknown }).__widget === true;\n}\n\n/** The fields a widget reads: hidden from a viewer who can't read any of them. */\nfunction fieldsRead(w: WidgetDefinition): string[] {\n switch (w.kind) {\n case \"number\":\n return w.metric && w.metric.fn !== \"count\" ? [w.metric.field] : [];\n case \"progress\":\n return [\n ...(w.metric && w.metric.fn !== \"count\" ? [w.metric.field] : []),\n ...(typeof w.goal === \"object\" && w.goal.fn !== \"count\" ? [w.goal.field] : []),\n ];\n case \"streak\":\n return [w.dateField];\n case \"chart\":\n return [w.groupBy, ...(w.metric && w.metric.fn !== \"count\" ? [w.metric.field] : [])];\n case \"list\":\n return [];\n }\n}\n\n/**\n * Whether this viewer sees the widget: `true`, or the reason not. A field it totals that the\n * viewer can't read (`permissions.read: false` in the contract) hides it, then the widget's own\n * `can`. Only narrows: row security still decides the rows behind any total.\n *\n * @stability Beta\n */\nexport function resolveWidgetAccess(widget: WidgetDefinition, viewer?: Viewer): Allowed {\n for (const field of fieldsRead(widget)) {\n if (widget.view.field(field)?.permissions?.read === false) return `You can't see ${widget.view.label(field).toLowerCase()}.`;\n }\n return widget.can ? widget.can(viewer) : true;\n}\n\n/** What a widget asks its provider for, from its view, scope, preset and filter. */\nexport interface WidgetRequest {\n resource: string;\n /** The preset's filter, the scope, then the widget's own filter. */\n filters: FilterParam[];\n /** Totals to ask `aggregate` for (number, progress). */\n aggregate?: AggregateParams;\n /** The goal's totals, over the scope and `goalFilter` only (progress with a total goal). */\n goal?: AggregateParams;\n /** Rows to read (streak, list, chart): how many and in what order. */\n rows?: { perPage: number; sort?: SortParam };\n}\n\n/**\n * What a widget needs from its provider, for a viewer working in `scope` (ViewerScope's): the\n * filters its view would list with, and either the totals or the rows. `<Widget>` and a phone\n * build their reads from this.\n *\n * @stability Beta\n */\nexport function resolveWidgetRequest(widget: WidgetDefinition, scope?: ResourceScope | null): WidgetRequest {\n const { view } = widget;\n const preset = widget.preset ? view.definition.presets?.[widget.preset] : undefined;\n if (widget.preset && !preset) throw new ViewDefinitionError(view.resource, [`no preset \"${widget.preset}\"`]);\n const scoped = filterParams(scopeFilter(view, scope) as WidgetFilter);\n const filters = [...filterParams(preset?.filter as WidgetFilter | undefined), ...scoped, ...filterParams(widget.filter)];\n const orderBy = view.definition.orderBy;\n const viewSort: SortParam | undefined = orderBy\n ? { field: orderBy.field as string, order: orderBy.direction ?? \"asc\", ...(orderBy.nulls ? { nulls: orderBy.nulls } : {}) }\n : undefined;\n switch (widget.kind) {\n case \"number\":\n return { resource: view.resource, filters, aggregate: { metrics: { value: widget.metric ?? { fn: \"count\" } }, filters } };\n case \"progress\": {\n const request: WidgetRequest = { resource: view.resource, filters, aggregate: { metrics: { value: widget.metric ?? { fn: \"count\" } }, filters } };\n if (typeof widget.goal === \"object\") {\n const goalFilters = [...scoped, ...filterParams(widget.goalFilter)];\n request.goal = { metrics: { goal: widget.goal }, filters: goalFilters };\n }\n return request;\n }\n case \"streak\":\n return { resource: view.resource, filters, rows: { perPage: widget.limit ?? 400, sort: { field: widget.dateField, order: \"desc\", nulls: \"last\" } } };\n case \"list\": {\n const sort = widget.sort ?? viewSort;\n return { resource: view.resource, filters, rows: { perPage: widget.limit ?? 5, ...(sort ? { sort } : {}) } };\n }\n case \"chart\":\n return { resource: view.resource, filters, rows: { perPage: widget.limit ?? 1000 } };\n }\n}\n\n/** The day a row's date or timestamp falls on, in `zone`. */\nfunction dayOfValue(value: unknown, zone: string): Day | undefined {\n if (typeof value === \"string\" && isDay(value)) return value;\n if (typeof value !== \"string\" && !(value instanceof Date) && typeof value !== \"number\") return undefined;\n const at = value instanceof Date ? value : new Date(value);\n return Number.isNaN(at.getTime()) ? undefined : dayIn(zone, at);\n}\n\n/** A streak's length and whether today (this week) is already in it. */\nexport interface Streak {\n /** Days (or weeks) in a row, ending today or, while today is still open, yesterday. */\n current: number;\n /** Whether today (this week) has a row. */\n today: boolean;\n unit: \"day\" | \"week\";\n}\n\n/**\n * How many days (or weeks) in a row have at least one of `values` (dates or timestamps), ending\n * today, or yesterday while today has none yet, so a streak isn't broken before the day is over.\n *\n * @stability Beta\n */\nexport function resolveStreak(\n values: readonly unknown[],\n options: { unit?: \"day\" | \"week\"; timeZone?: string; today?: Day } = {},\n): Streak {\n const unit = options.unit ?? \"day\";\n const zone = options.timeZone ?? deviceTimeZone();\n const step = unit === \"day\" ? 1 : 7;\n const bucket = (day: Day) => (unit === \"day\" ? day : startOfWeek(day, 1));\n const seen = new Set<Day>();\n for (const value of values) {\n const day = dayOfValue(value, zone);\n if (day) seen.add(bucket(day));\n }\n const now = bucket(options.today ?? dayIn(zone));\n const today = seen.has(now);\n let at = today ? now : addDays(now, -step);\n let current = 0;\n while (seen.has(at)) {\n current++;\n at = addDays(at, -step);\n }\n return { current, today, unit };\n}\n\n/** One bar (or point) of a chart widget. */\nexport interface ChartPoint {\n /** The field's value, as text (`\"(none)\"` for an empty one). */\n key: string;\n /** The value in words (`ResourceView.valueLabel`). */\n label: string;\n value: number;\n}\n\n/**\n * A chart widget's bars from its rows: one per value of `groupBy`, in the field's choice order\n * when it has choices (else by value), each the metric over the rows with that value.\n *\n * @stability Beta\n */\nexport function resolveChartSeries(widget: ChartWidget, rows: readonly Record<string, unknown>[]): ChartPoint[] {\n const groups = new Map<string, Record<string, unknown>[]>();\n for (const row of rows) {\n const raw = row[widget.groupBy];\n const key = raw === null || raw === undefined || raw === \"\" ? \"(none)\" : String(raw);\n const list = groups.get(key) ?? [];\n list.push(row);\n groups.set(key, list);\n }\n const choices = (widget.view.field(widget.groupBy)?.enumValues ?? []) as readonly string[];\n const keys = [\n ...choices.filter((c) => groups.has(c)),\n ...[...groups.keys()].filter((k) => !choices.includes(k)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })),\n ];\n const metric = widget.metric ?? { fn: \"count\" as const };\n return keys.map((key) => {\n const list = groups.get(key)!;\n // The same rule as a number widget's total: rows with no number in the field are skipped, not\n // read as 0; a group where none has one draws as 0.\n const value = toAggregateValues(list, { value: metric })[\"value\"] ?? 0;\n return { key, label: key === \"(none)\" ? \"None\" : widget.view.valueLabel(widget.groupBy, key), value };\n });\n}\n\n/**\n * A widget's number in words: `null` reads \"—\", a percent is of 1 (0.42 is 42%).\n *\n * @stability Beta\n */\nexport function toWidgetText(value: number | null | undefined, format: WidgetFormat = \"number\", locale?: string): string {\n if (value === null || value === undefined || !Number.isFinite(value)) return \"—\";\n if (typeof format === \"function\") return format(value);\n if (typeof format === \"object\") {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: format.currency,\n ...(format.maximumFractionDigits !== undefined ? { maximumFractionDigits: format.maximumFractionDigits } : {}),\n }).format(value);\n }\n switch (format) {\n case \"compact\":\n return new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }).format(value);\n case \"percent\":\n return new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 }).format(value);\n default:\n return new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(value);\n }\n}\n\n/**\n * Progress as a fraction from 0 to 1 (more than 1 when the goal is passed), or null without a\n * goal to measure against.\n *\n * @stability Beta\n */\nexport function resolveProgress(value: number | null | undefined, goal: number | null | undefined): number | null {\n if (value === null || value === undefined || goal === null || goal === undefined || !(goal > 0)) return null;\n return Math.max(0, value / goal);\n}\n"]}