@marktiderman/genesis-core 1.13.0 → 1.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +45 -0
  2. package/dist/{chunk-REYTMXAA.js → chunk-3LZAZ5KB.js} +3 -3
  3. package/dist/{chunk-REYTMXAA.js.map → chunk-3LZAZ5KB.js.map} +1 -1
  4. package/dist/chunk-4VRVVN2S.js +109 -0
  5. package/dist/chunk-4VRVVN2S.js.map +1 -0
  6. package/dist/{chunk-JKZ2FVWK.js → chunk-7YHGNPPO.js} +4 -4
  7. package/dist/{chunk-JKZ2FVWK.js.map → chunk-7YHGNPPO.js.map} +1 -1
  8. package/dist/{chunk-TCL27Q5W.js → chunk-K7K6NY3C.js} +4 -113
  9. package/dist/chunk-K7K6NY3C.js.map +1 -0
  10. package/dist/chunk-OZYF55E3.js +6 -0
  11. package/dist/chunk-OZYF55E3.js.map +1 -0
  12. package/dist/chunk-PA6WJE5E.js +115 -0
  13. package/dist/chunk-PA6WJE5E.js.map +1 -0
  14. package/dist/chunk-PP3XFFQM.js +85 -0
  15. package/dist/chunk-PP3XFFQM.js.map +1 -0
  16. package/dist/{chunk-GEF5W2LO.js → chunk-YFTGLQDQ.js} +4 -4
  17. package/dist/{chunk-GEF5W2LO.js.map → chunk-YFTGLQDQ.js.map} +1 -1
  18. package/dist/chunk-ZIMQUFXD.js +154 -0
  19. package/dist/chunk-ZIMQUFXD.js.map +1 -0
  20. package/dist/errors.d.ts +69 -0
  21. package/dist/errors.js +7 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/hooks/index.d.ts +1 -1
  24. package/dist/hooks/index.js +15 -11
  25. package/dist/hooks/mutation-mode.js +2 -2
  26. package/dist/hooks/use-resource-form.js +6 -6
  27. package/dist/hooks/use-resource.js +4 -4
  28. package/dist/index.d.ts +2 -1
  29. package/dist/index.js +18 -15
  30. package/dist/provider/index.js +4 -3
  31. package/dist/resource/index.d.ts +2 -49
  32. package/dist/resource/index.js +1 -83
  33. package/dist/resource/index.js.map +1 -1
  34. package/dist/resource-view/index.d.ts +216 -17
  35. package/dist/resource-view/index.js +263 -13
  36. package/dist/resource-view/index.js.map +1 -1
  37. package/dist/status-BXRokZD9.d.ts +50 -0
  38. package/dist/{viewer-scope-0dR-_o0f.d.ts → viewer-scope-77MqxvmZ.d.ts} +51 -2
  39. package/package.json +5 -1
  40. package/dist/chunk-FARKPY6R.js +0 -66
  41. package/dist/chunk-FARKPY6R.js.map +0 -1
  42. package/dist/chunk-TCL27Q5W.js.map +0 -1
@@ -1,6 +1,9 @@
1
- import { keyFields } from '../chunk-KV2HW4G4.js';
2
- import { isSafeUrl } from '../chunk-YDDPFSQ6.js';
1
+ import { readinessOf } from '../chunk-PP3XFFQM.js';
2
+ import { keyFields, encodeRecordKey } from '../chunk-KV2HW4G4.js';
3
+ import { NO_VIEWER } from '../chunk-OZYF55E3.js';
4
+ export { NO_VIEWER } from '../chunk-OZYF55E3.js';
3
5
  import { titleCase } from '../chunk-RYEXWQFD.js';
6
+ import { isSafeUrl } from '../chunk-YDDPFSQ6.js';
4
7
 
5
8
  // src/resource-view/define-view.ts
6
9
  var ViewDefinitionError = class extends Error {
@@ -62,6 +65,10 @@ function singular(word) {
62
65
  }
63
66
  var RESERVED_ACTIONS = /* @__PURE__ */ new Set(["create", "update", "delete"]);
64
67
  var own = (record, key) => record && Object.hasOwn(record, key) ? record[key] : void 0;
68
+ function valueText(labels, value) {
69
+ const key = String(value);
70
+ return own(labels, key) ?? titleCase(key);
71
+ }
65
72
  function defineView(contract, definition = {}) {
66
73
  const facts = contract;
67
74
  const fields = contract.fields;
@@ -69,7 +76,15 @@ function defineView(contract, definition = {}) {
69
76
  const keys = new Set(keyFields(contract));
70
77
  const scope = new Set(definition.scope ?? []);
71
78
  const viewFields = Object.freeze(
72
- Object.fromEntries(Object.entries(definition.fields ?? {}).map(([k, v]) => [k, Object.freeze({ ...v })]))
79
+ Object.fromEntries(
80
+ Object.entries(definition.fields ?? {}).map(([k, v]) => {
81
+ const f = { ...v };
82
+ const map = (m) => Boolean(m) && typeof m === "object" && !Array.isArray(m);
83
+ if (map(f.tones)) f.tones = Object.freeze({ ...f.tones });
84
+ if (map(f.labels)) f.labels = Object.freeze({ ...f.labels });
85
+ return [k, Object.freeze(f)];
86
+ })
87
+ )
73
88
  );
74
89
  const columnLists = Object.freeze(
75
90
  Object.fromEntries(
@@ -88,13 +103,28 @@ function defineView(contract, definition = {}) {
88
103
  )
89
104
  );
90
105
  const actionList = Object.freeze(
91
- (Array.isArray(definition.actions) ? definition.actions : []).map((a) => a && typeof a === "object" ? Object.freeze({ ...a }) : a)
106
+ // Names are trimmed, so " archive" and "archive" are one name.
107
+ (Array.isArray(definition.actions) ? definition.actions : []).map(
108
+ (a) => a && typeof a === "object" ? Object.freeze({ ...a, ...typeof a.name === "string" ? { name: a.name.trim() } : {} }) : a
109
+ )
92
110
  );
93
111
  const problems = [];
94
112
  const known = (name, where) => {
95
113
  if (!byName.has(name)) problems.push(`${where} names "${name}", which isn't a field`);
96
114
  };
97
115
  for (const name of Object.keys(viewFields)) known(name, "fields");
116
+ for (const [name, v] of Object.entries(viewFields)) {
117
+ if (v?.labels === void 0) continue;
118
+ if (!v.labels || typeof v.labels !== "object" || Array.isArray(v.labels)) {
119
+ problems.push(`fields.${name}.labels isn't a map of values to words`);
120
+ continue;
121
+ }
122
+ const values = byName.get(name)?.enumValues;
123
+ for (const [value, words] of Object.entries(v.labels)) {
124
+ if (typeof words !== "string" || !words.trim()) problems.push(`fields.${name}.labels.${value} isn't text`);
125
+ if (values?.length && !values.includes(value)) problems.push(`fields.${name}.labels names "${value}", which isn't one of its values`);
126
+ }
127
+ }
98
128
  for (const [preset, list] of Object.entries(columnLists)) {
99
129
  const seen = /* @__PURE__ */ new Set();
100
130
  for (const column of list ?? []) {
@@ -141,6 +171,7 @@ function defineView(contract, definition = {}) {
141
171
  problems.push(`${where}.description isn't text`);
142
172
  }
143
173
  if (action.can !== void 0 && typeof action.can !== "function") problems.push(`${where}.can isn't a function`);
174
+ if (action.destructive !== void 0 && typeof action.destructive !== "boolean") problems.push(`${where}.destructive isn't true or false`);
144
175
  });
145
176
  if (problems.length) throw new ViewDefinitionError(contract.name, problems);
146
177
  const copy = definition.copy ?? {};
@@ -154,6 +185,7 @@ function defineView(contract, definition = {}) {
154
185
  const field = byName.get(name);
155
186
  return own(viewFields, name)?.display ?? (field ? deriveDisplay(field) : "text");
156
187
  };
188
+ const valueLabel = (name, value) => valueText(own(viewFields, name)?.labels, value);
157
189
  const readable = (name) => byName.get(name)?.permissions?.read !== false;
158
190
  const readOnly = (field) => Boolean(
159
191
  field.generated || field.readOnly || field.references || field.permissions?.update === false || own(viewFields, field.name)?.readOnly
@@ -180,7 +212,8 @@ function defineView(contract, definition = {}) {
180
212
  field: byName.get(column),
181
213
  value: (row) => row[column],
182
214
  ...v?.tones ? { tones: v.tones } : {},
183
- ...v?.when ? { when: v.when } : {},
215
+ ...v?.labels ? { labels: v.labels } : {},
216
+ ...v?.when ? { when: (row, viewer = NO_VIEWER) => v.when(row, viewer) } : {},
184
217
  ...v?.timeZone ? { timeZone: v.timeZone } : {}
185
218
  });
186
219
  })
@@ -209,6 +242,7 @@ function defineView(contract, definition = {}) {
209
242
  section,
210
243
  sectionTitle,
211
244
  ...v?.max !== void 0 ? { max: v.max } : {},
245
+ ...field.enumValues?.length ? { options: Object.freeze(field.enumValues.map((value) => Object.freeze({ value, label: valueLabel(name, value) }))) } : {},
212
246
  ...v?.visible ? { visible: v.visible } : {}
213
247
  });
214
248
  }));
@@ -217,10 +251,12 @@ function defineView(contract, definition = {}) {
217
251
  };
218
252
  const writable = (mode) => Object.freeze(form(mode).filter((f) => !f.readOnly).map((f) => f.field.name));
219
253
  const guards = definition.can ?? {};
220
- function can(action, row) {
221
- if (action === "create") return guards.create?.() ?? true;
254
+ function can(action, rowOrViewer, maybeViewer) {
255
+ if (action === "create" && maybeViewer !== void 0) throw new TypeError(`[genesis-core] ${contract.name}: can("create", viewer) takes no row`);
256
+ if (action === "create") return guards.create?.(rowOrViewer ?? NO_VIEWER) ?? true;
222
257
  const guard = guards[action];
223
- return guard && row ? guard(row) : true;
258
+ const row = rowOrViewer;
259
+ return guard && row ? guard(row, maybeViewer ?? NO_VIEWER) : true;
224
260
  }
225
261
  const actionGuards = new Map(actionList.map((a) => [a.name, a.can]));
226
262
  const resolvedActions = Object.freeze(
@@ -229,13 +265,18 @@ function defineView(contract, definition = {}) {
229
265
  name: a.name,
230
266
  label: a.label,
231
267
  ...a.confirm !== void 0 ? { confirm: a.confirm } : {},
232
- ...a.description !== void 0 ? { description: a.description } : {}
268
+ ...a.description !== void 0 ? { description: a.description } : {},
269
+ ...a.destructive ? { destructive: true } : {}
233
270
  })
234
271
  )
235
272
  );
236
- function canAction(name, row) {
273
+ function canAction(name, row, viewer = NO_VIEWER) {
237
274
  if (!actionGuards.has(name)) throw new ViewDefinitionError(contract.name, [`no action "${name}"`]);
238
- return actionGuards.get(name)?.(row) ?? true;
275
+ const guard = actionGuards.get(name);
276
+ if (!guard) return true;
277
+ const result = guard(row, viewer);
278
+ if (result === true) return true;
279
+ return typeof result === "string" && result.trim() ? result : "This isn't allowed.";
239
280
  }
240
281
  const summary = (row) => {
241
282
  if (definition.summary) return definition.summary(row);
@@ -262,6 +303,7 @@ function defineView(contract, definition = {}) {
262
303
  field: (name) => byName.get(name),
263
304
  label,
264
305
  display,
306
+ valueLabel,
265
307
  columns,
266
308
  form,
267
309
  writable,
@@ -288,11 +330,16 @@ function initialsOf(name) {
288
330
  const pair = letters.length === 1 ? [letters[0]] : [letters[0], letters[letters.length - 1]];
289
331
  return pair.map((l) => l.toUpperCase().length === l.length ? l.toUpperCase() : l).join("");
290
332
  }
333
+ function isImageSrc(src) {
334
+ if (!isSafeUrl(src)) return false;
335
+ const value = src.trim();
336
+ return value.startsWith("/") || /^https?:/i.test(value);
337
+ }
291
338
  function rowPicture(summary) {
292
339
  const image = summary.image;
293
340
  if (!image) return null;
294
341
  const initials = initialsOf(image.name);
295
- if (isSafeUrl(image.src)) return { kind: "image", src: image.src.trim(), alt: image.alt ?? "", fallback: initials };
342
+ if (isImageSrc(image.src)) return { kind: "image", src: image.src.trim(), alt: image.alt ?? "", fallback: initials };
296
343
  return initials ? { kind: "initials", text: initials } : null;
297
344
  }
298
345
 
@@ -315,6 +362,209 @@ function scopeValues(view, scope) {
315
362
  return Object.freeze(out);
316
363
  }
317
364
 
318
- export { ViewDefinitionError, defineView, deriveDisplay, initialsOf, rowPicture, scopeValues };
365
+ // src/resource-view/workspace.ts
366
+ var WORKSPACE = /* @__PURE__ */ Symbol.for("genesis.resource-workspace");
367
+ var REFUSED = "This isn't allowed.";
368
+ var TONES = /* @__PURE__ */ new Set(["success", "warning", "danger", "info", "muted"]);
369
+ var SECTION_KEYS = /* @__PURE__ */ new Set(["id", "label", "list", "settings"]);
370
+ var dev = () => process.env.NODE_ENV !== "production";
371
+ function unsettable(field) {
372
+ if (!field) return null;
373
+ const facts = field;
374
+ if (field.type === "json") return "is JSON";
375
+ if (field.array) return "is a list";
376
+ if (field.references || field.type === "relation") return "is a link";
377
+ if (facts.sensitive) return "is sensitive";
378
+ return null;
379
+ }
380
+ function isWorkspace(value) {
381
+ return typeof value === "object" && value !== null && value[WORKSPACE] === true;
382
+ }
383
+ function isView(value) {
384
+ return typeof value === "object" && value !== null && typeof value.columns === "function" && typeof value.resource === "string";
385
+ }
386
+ function defineWorkspace(view, definition) {
387
+ const where = `${view.resource} workspace`;
388
+ const problems = [];
389
+ const writable = new Set(view.writable("edit"));
390
+ const actionNames = new Set(view.actions().map((a) => a.name));
391
+ const input = Array.isArray(definition?.sections) ? definition.sections : [];
392
+ if (!Array.isArray(definition?.sections)) problems.push("sections isn't a list");
393
+ else if (input.length === 0) problems.push("sections is empty");
394
+ const ids = /* @__PURE__ */ new Set();
395
+ const settingsSeen = /* @__PURE__ */ new Set();
396
+ const sections = [];
397
+ const filters = /* @__PURE__ */ new Map();
398
+ input.forEach((raw, i) => {
399
+ const at = `sections[${i}]`;
400
+ if (!raw || typeof raw !== "object") {
401
+ problems.push(`${at} isn't a section`);
402
+ return;
403
+ }
404
+ const s = raw;
405
+ const name = typeof s.id === "string" && s.id.trim() ? s.id : void 0;
406
+ if (!name) problems.push(`${at} has no id`);
407
+ else if (ids.has(name)) problems.push(`sections lists "${name}" twice`);
408
+ else ids.add(name);
409
+ const label = `sections.${name ?? i}`;
410
+ if (typeof s.label !== "string" || !s.label.trim()) problems.push(`${label} has no label`);
411
+ if (isWorkspace(s) || "sections" in s || "workspace" in s) {
412
+ problems.push(`${label} holds a workspace; sections don't nest`);
413
+ return;
414
+ }
415
+ const unknown = Object.keys(s).filter((k) => !SECTION_KEYS.has(k));
416
+ if (unknown.length) problems.push(`${label} has ${unknown.map((k) => `"${k}"`).join(", ")}, which isn't a section key (id, label, list, settings)`);
417
+ const hasList = s.list !== void 0;
418
+ const hasSettings = s.settings !== void 0;
419
+ if (hasList && hasSettings) {
420
+ problems.push(`${label} has both list and settings; a section has one`);
421
+ return;
422
+ }
423
+ if (hasList) {
424
+ const list = s.list;
425
+ if (isWorkspace(list?.view)) problems.push(`${label}.list.view is a workspace; sections don't nest`);
426
+ else if (!isView(list?.view)) problems.push(`${label}.list.view isn't a view`);
427
+ if (typeof list?.filter !== "function") problems.push(`${label}.list.filter isn't a function`);
428
+ if (name && isView(list?.view) && !isWorkspace(list.view) && typeof list.filter === "function") {
429
+ filters.set(name, list.filter);
430
+ sections.push(Object.freeze({ id: name, label: s.label, kind: "list", view: list.view }));
431
+ }
432
+ return;
433
+ }
434
+ if (hasSettings) {
435
+ if (!Array.isArray(s.settings)) {
436
+ problems.push(`${label}.settings isn't a list`);
437
+ return;
438
+ }
439
+ if (s.settings.length === 0) problems.push(`${label}.settings lists no fields`);
440
+ for (const field of s.settings) {
441
+ const why = unsettable(view.field(field));
442
+ if (why) problems.push(`${label}.settings names "${field}", which ${why}; it needs an editor of its own`);
443
+ else if (!writable.has(field)) problems.push(`${label}.settings names "${field}", which the view can't write on edit`);
444
+ if (settingsSeen.has(field)) problems.push(`settings lists "${field}" twice`);
445
+ settingsSeen.add(field);
446
+ }
447
+ if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: "settings", settings: Object.freeze(s.settings.map(String)) }));
448
+ return;
449
+ }
450
+ if (name) sections.push(Object.freeze({ id: name, label: s.label, kind: "slot" }));
451
+ });
452
+ const requested = definition?.header?.actions;
453
+ if (requested !== void 0 && !Array.isArray(requested)) problems.push("header.actions isn't a list");
454
+ const headerActions = Object.freeze(
455
+ Array.isArray(requested) ? [...requested] : view.actions().map((a) => a.name)
456
+ );
457
+ const headerSeen = /* @__PURE__ */ new Set();
458
+ for (const name of headerActions) {
459
+ if (!actionNames.has(name)) problems.push(`header.actions names "${name}", which isn't a view action`);
460
+ if (headerSeen.has(name)) problems.push(`header.actions lists "${name}" twice`);
461
+ headerSeen.add(name);
462
+ }
463
+ if (definition?.readiness !== void 0 && typeof definition.readiness !== "function") {
464
+ problems.push("readiness isn't a function");
465
+ }
466
+ if (problems.length) throw new ViewDefinitionError(where, problems);
467
+ const frozenSections = Object.freeze(sections);
468
+ const byId = new Map(frozenSections.map((s) => [s.id, s]));
469
+ const actionByName = new Map(view.actions().map((a) => [a.name, a]));
470
+ const readiness = definition.readiness;
471
+ const settingsOf = (sectionId) => {
472
+ const s = byId.get(sectionId);
473
+ if (!s || s.kind !== "settings") throw new ViewDefinitionError(where, [`no settings section "${sectionId}"`]);
474
+ return s.settings;
475
+ };
476
+ const resolvedSettings = /* @__PURE__ */ new Map();
477
+ const settingsFields = (sectionId) => {
478
+ const key = sectionId ?? "";
479
+ const cached = resolvedSettings.get(key);
480
+ if (cached) return cached;
481
+ const names = sectionId === void 0 ? frozenSections.flatMap((s) => s.kind === "settings" ? s.settings : []) : settingsOf(sectionId);
482
+ const form = new Map(view.form("edit").map((f) => [f.field.name, f]));
483
+ const out = Object.freeze(names.map((n) => form.get(n)).filter((f) => f !== void 0));
484
+ resolvedSettings.set(key, out);
485
+ return out;
486
+ };
487
+ const headerFor = (row, options = {}) => {
488
+ const summary = view.summary(row);
489
+ const served = options.served ? new Set(options.served) : null;
490
+ const actions = [];
491
+ if (options.runnable !== false) {
492
+ for (const name of headerActions) {
493
+ if (served && !served.has(name)) continue;
494
+ const own2 = options.can?.(name, row);
495
+ if (own2 === false) continue;
496
+ const allowed = typeof own2 === "string" ? own2 || REFUSED : view.canAction(name, row, options.viewer);
497
+ actions.push(Object.freeze({ ...actionByName.get(name), allowed }));
498
+ }
499
+ }
500
+ return Object.freeze({
501
+ title: summary.title,
502
+ ...summary.subtitle !== void 0 ? { subtitle: summary.subtitle } : {},
503
+ chips: Object.freeze([...summary.chips ?? []]),
504
+ actions: Object.freeze(actions)
505
+ });
506
+ };
507
+ const readinessFor = (row) => {
508
+ if (!readiness) return Object.freeze([]);
509
+ return Object.freeze(
510
+ readiness(row).map((item, i) => {
511
+ let tone = item.tone ?? (item.ok ? "success" : "warning");
512
+ if (!TONES.has(tone)) {
513
+ if (dev()) console.warn(`[genesis-core] ${where}: readiness "${item.title}" has tone "${String(tone)}", which isn't a chip tone; showing it muted.`);
514
+ tone = "muted";
515
+ }
516
+ return Object.freeze({
517
+ key: item.id ?? `${i}:${item.title}`,
518
+ title: item.title,
519
+ ok: Boolean(item.ok),
520
+ ...item.reason !== void 0 ? { reason: item.reason } : {},
521
+ tone
522
+ });
523
+ })
524
+ );
525
+ };
526
+ const readinessSummary = (row) => readiness ? readinessOf(
527
+ readinessFor(row).filter((r) => !r.ok).map((r) => ({ level: r.tone === "danger" ? "error" : "warning" }))
528
+ ) : null;
529
+ return Object.freeze({
530
+ [WORKSPACE]: true,
531
+ view,
532
+ sections: frozenSections,
533
+ headerActions,
534
+ hasReadiness: Boolean(readiness),
535
+ section: (id) => byId.get(id),
536
+ recordId: (row) => encodeRecordKey(view.contract, row),
537
+ settingsLocked: (row, viewer) => {
538
+ const allowed = view.can("update", row, viewer);
539
+ return allowed === true ? null : typeof allowed === "string" && allowed.trim() ? allowed : REFUSED;
540
+ },
541
+ headerFor,
542
+ settingsFields,
543
+ settingsPatch: (sectionId, values) => {
544
+ const patch = {};
545
+ for (const name of settingsOf(sectionId)) if (Object.hasOwn(values, name)) patch[name] = values[name];
546
+ return patch;
547
+ },
548
+ listFilter: (sectionId, row) => {
549
+ const filter = filters.get(sectionId);
550
+ if (!filter) throw new ViewDefinitionError(where, [`no list section "${sectionId}"`]);
551
+ const out = filter(row);
552
+ if (dev()) {
553
+ const entries = out && typeof out === "object" ? Object.entries(out) : [];
554
+ const bad = entries.filter(([, v]) => !(v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean"));
555
+ if (entries.length === 0 || bad.length) {
556
+ throw new ViewDefinitionError(where, [
557
+ entries.length === 0 ? `sections.${sectionId}.list.filter gave no keys, which would list every row` : `sections.${sectionId}.list.filter gives ${bad.map(([k]) => `"${k}"`).join(", ")} no single value`
558
+ ]);
559
+ }
560
+ }
561
+ return Object.freeze({ ...out });
562
+ },
563
+ readinessFor,
564
+ readinessSummary
565
+ });
566
+ }
567
+
568
+ export { ViewDefinitionError, defineView, defineWorkspace, deriveDisplay, initialsOf, isWorkspace, rowPicture, scopeValues, valueText };
319
569
  //# sourceMappingURL=index.js.map
320
570
  //# sourceMappingURL=index.js.map