@stonecrop/stonecrop 0.55.1 → 0.56.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.
@@ -55,7 +55,8 @@ export declare type ActionEventPayload = {
55
55
  /** The declared action name (e.g. 'SAVE', 'SUBMIT', 'APPROVE') */
56
56
  name: string;
57
57
  doctype: string;
58
- recordId: string;
58
+ /** Absent for an action raised on a list, which has no record. */
59
+ recordId?: string;
59
60
  /** Snapshot of the form data at the time the action was triggered */
60
61
  data: Record<string, any>;
61
62
  };
@@ -91,8 +92,8 @@ export declare interface ActionFailure {
91
92
  action: string;
92
93
  /** Slug of the doctype the action was raised on. */
93
94
  doctype: string;
94
- /** Record the action was raised against; the `new` route segment for an unsaved record. */
95
- recordId: string;
95
+ /** Record the action was raised against; the `new` route segment for an unsaved record; absent on a list. */
96
+ recordId?: string;
96
97
  /** The thrown value, present only when the failure was a throw rather than a refused dispatch. */
97
98
  cause?: unknown;
98
99
  }
@@ -480,6 +481,18 @@ export declare class Doctype {
480
481
  getAvailableCommands(currentState?: string | null): Array<{
481
482
  name: string;
482
483
  }>;
484
+ /**
485
+ * Returns every action this doctype's workflow declares, in declaration order, whatever its kind
486
+ * or state. A list shows these, since a list has no record whose state could narrow them. An
487
+ * XState workflow declares none.
488
+ *
489
+ * @returns Array of action descriptors with `name`
490
+ *
491
+ * @public
492
+ */
493
+ getActions(): Array<{
494
+ name: string;
495
+ }>;
483
496
  /**
484
497
  * Returns the field-validation **triggers** declared on this doctype's workflow (advisory,
485
498
  * client-side). Keyed by trigger name. Returns undefined when the workflow is absent, is an
@@ -2084,6 +2097,7 @@ export declare class Stonecrop {
2084
2097
  * @param doctype - The doctype
2085
2098
  * @param recordId - The record ID
2086
2099
  * @param recordData - The record data
2100
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2087
2101
  */
2088
2102
  addRecord(doctype: string | Doctype, recordId: string, recordData: any): void;
2089
2103
  /**
@@ -2096,6 +2110,7 @@ export declare class Stonecrop {
2096
2110
  * @param startingValues - A record not saved yet's values before anything is set, such as
2097
2111
  * {@link Registry.composeNewRecord} gives; they run no rules. Only a new record takes them.
2098
2112
  * @returns The record to read and set
2113
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2099
2114
  */
2100
2115
  editRecord(doctype: string | Doctype, recordId: string, startingValues?: Record<string, unknown>): EditableRecord;
2101
2116
  /**
@@ -2103,12 +2118,14 @@ export declare class Stonecrop {
2103
2118
  * @param doctype - The doctype
2104
2119
  * @param recordId - The record ID
2105
2120
  * @returns HST node for the record or undefined
2121
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2106
2122
  */
2107
2123
  getRecordById(doctype: string | Doctype, recordId: string): HSTNode | undefined;
2108
2124
  /**
2109
2125
  * Remove a record from the store
2110
2126
  * @param doctype - The doctype
2111
2127
  * @param recordId - The record ID
2128
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2112
2129
  */
2113
2130
  removeRecord(doctype: string | Doctype, recordId: string): void;
2114
2131
  /**
@@ -2140,6 +2157,7 @@ export declare class Stonecrop {
2140
2157
  * @param doctype - The doctype to check
2141
2158
  * @param recordId - The record ID
2142
2159
  * @returns Object with `ready: true` if all blocked links are loaded, or `ready: false` with `blockedLinks` array
2160
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2143
2161
  */
2144
2162
  isWorkflowReady(doctype: Doctype, recordId: string): {
2145
2163
  ready: boolean;
@@ -2198,6 +2216,7 @@ export declare class Stonecrop {
2198
2216
  * @throws Error if no data client has been configured
2199
2217
  * @throws Error if a slug string is given and no matching doctype is found in the registry
2200
2218
  * @throws Error with code `"RECORD_NOT_FOUND"` if the server returns no record
2219
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2201
2220
  * @public
2202
2221
  */
2203
2222
  getRecord(doctype: string | Doctype, recordId: string, options?: GetRecordOptions): Promise<void>;
@@ -2258,6 +2277,7 @@ export declare class Stonecrop {
2258
2277
  * @param recordId - The record identifier
2259
2278
  * @returns The current state name, `null` for a record not created yet, or an empty string if
2260
2279
  * the doctype has no workflow
2280
+ * @throws Error if the doctype has a workflow and `recordId` is empty, or holds a dot or a bracket
2261
2281
  *
2262
2282
  * @public
2263
2283
  */
@@ -2267,6 +2287,7 @@ export declare class Stonecrop {
2267
2287
  * @param doctype - The doctype metadata
2268
2288
  * @param recordId - The record ID to collect
2269
2289
  * @returns The complete record payload ready for API submission
2290
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2270
2291
  * @public
2271
2292
  */
2272
2293
  collectRecordPayload(doctype: Doctype, recordId: string): Record<string, any>;
@@ -2292,6 +2313,7 @@ export declare class Stonecrop {
2292
2313
  * @param options - Query options (includeNested to control which links are fetched)
2293
2314
  * @throws Error with code `"CLIENT_REQUIRED"` if no data client is configured
2294
2315
  * @throws Error with code `"RECORD_NOT_FOUND"` if the server returns null
2316
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2295
2317
  * @public
2296
2318
  */
2297
2319
  fetchNestedData(path: string, doctype: Doctype, recordId: string, options?: {
@@ -2500,6 +2522,7 @@ export declare interface UseClientActionOptions {
2500
2522
  * @param recordId - The record ID
2501
2523
  * @param linkFieldname - The link fieldname to load
2502
2524
  * @returns LazyLink with loading, loaded, error, reload, and data
2525
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2503
2526
  * @public
2504
2527
  */
2505
2528
  export declare function useLazyLink(doctype: Doctype, recordId: string, linkFieldname: string): LazyLink;
package/dist/stonecrop.js CHANGED
@@ -91,19 +91,33 @@ function parsePath(path) {
91
91
  //#endregion
92
92
  //#region src/record-access.ts
93
93
  /**
94
+ * A record's path in its store, `doctype.recordId`. An ID the store would not keep as one part of a
95
+ * path is refused: an empty one would address every record of the doctype, and one with a dot or a
96
+ * bracket would address part of another record.
97
+ *
98
+ * @param slug - the record's doctype
99
+ * @param recordId - the record's ID
100
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
101
+ */
102
+ function recordPath(slug, recordId) {
103
+ if (recordId === "") throw new Error(`No record ID given for ${slug}`);
104
+ if (parsePath(recordId)[0] !== recordId) throw new Error(`Record ID ${recordId} for ${slug} can't contain a dot`);
105
+ return `${slug}.${recordId}`;
106
+ }
107
+ /**
94
108
  * A saved record's fields, read and set by name through the store that holds it. A set is a store
95
109
  * write, so it runs the rules of the field it sets. A set with no field name throws, rather than
96
110
  * reaching the store as a write to the whole record.
97
111
  *
98
112
  * @param store - the store holding the record
99
- * @param recordPath - the record's path in that store, `doctype.recordId`
113
+ * @param path - the record's path in that store, from {@link recordPath}
100
114
  */
101
- function recordInStore(store, recordPath) {
115
+ function recordInStore(store, path) {
102
116
  return {
103
- get: (fieldname) => store.get(fieldname ? `${recordPath}.${fieldname}` : recordPath),
117
+ get: (fieldname) => store.get(fieldname ? `${path}.${fieldname}` : path),
104
118
  set: (fieldname, value) => {
105
119
  if (parsePath(fieldname).length === 0) throw new Error("Cannot set value on empty path");
106
- store.set(`${recordPath}.${fieldname}`, value);
120
+ store.set(`${path}.${fieldname}`, value);
107
121
  }
108
122
  };
109
123
  }
@@ -1477,11 +1491,13 @@ var Stonecrop = class Stonecrop {
1477
1491
  * @param doctype - The doctype
1478
1492
  * @param recordId - The record ID
1479
1493
  * @param recordData - The record data
1494
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1480
1495
  */
1481
1496
  addRecord(doctype, recordId, recordData) {
1482
1497
  const slug = typeof doctype === "string" ? doctype : doctype.slug;
1498
+ const path = recordPath(slug, recordId);
1483
1499
  this.ensureDoctypeExists(slug);
1484
- this.hstStore.set(`${slug}.${recordId}`, recordData);
1500
+ this.hstStore.set(path, recordData);
1485
1501
  }
1486
1502
  /**
1487
1503
  * The record a form is editing, read and set by field name; setting a field runs its rules. A
@@ -1493,36 +1509,41 @@ var Stonecrop = class Stonecrop {
1493
1509
  * @param startingValues - A record not saved yet's values before anything is set, such as
1494
1510
  * {@link Registry.composeNewRecord} gives; they run no rules. Only a new record takes them.
1495
1511
  * @returns The record to read and set
1512
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1496
1513
  */
1497
1514
  editRecord(doctype, recordId, startingValues) {
1498
1515
  const slug = typeof doctype === "string" ? doctype : doctype.slug;
1499
1516
  if (isDraftRecordId(recordId)) return newRecord(slug, this.hstStore, startingValues);
1500
1517
  if (startingValues) throw new Error(`Starting values are only for a new record, not ${slug} ${recordId}`);
1501
1518
  this.ensureDoctypeExists(slug);
1502
- return recordInStore(this.hstStore, `${slug}.${recordId}`);
1519
+ return recordInStore(this.hstStore, recordPath(slug, recordId));
1503
1520
  }
1504
1521
  /**
1505
1522
  * Get a specific record
1506
1523
  * @param doctype - The doctype
1507
1524
  * @param recordId - The record ID
1508
1525
  * @returns HST node for the record or undefined
1526
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1509
1527
  */
1510
1528
  getRecordById(doctype, recordId) {
1511
1529
  const slug = typeof doctype === "string" ? doctype : doctype.slug;
1530
+ const path = recordPath(slug, recordId);
1512
1531
  this.ensureDoctypeExists(slug);
1513
- if (!this.hstStore.has(`${slug}.${recordId}`)) return;
1514
- if (this.hstStore.get(`${slug}.${recordId}`) === void 0) return;
1515
- return this.hstStore.getNode(`${slug}.${recordId}`);
1532
+ if (!this.hstStore.has(path)) return;
1533
+ if (this.hstStore.get(path) === void 0) return;
1534
+ return this.hstStore.getNode(path);
1516
1535
  }
1517
1536
  /**
1518
1537
  * Remove a record from the store
1519
1538
  * @param doctype - The doctype
1520
1539
  * @param recordId - The record ID
1540
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1521
1541
  */
1522
1542
  removeRecord(doctype, recordId) {
1523
1543
  const slug = typeof doctype === "string" ? doctype : doctype.slug;
1544
+ const path = recordPath(slug, recordId);
1524
1545
  this.ensureDoctypeExists(slug);
1525
- if (this.hstStore.has(`${slug}.${recordId}`)) this.hstStore.set(`${slug}.${recordId}`, void 0);
1546
+ if (this.hstStore.has(path)) this.hstStore.set(path, void 0);
1526
1547
  }
1527
1548
  /**
1528
1549
  * Get all record IDs for a doctype
@@ -1570,13 +1591,15 @@ var Stonecrop = class Stonecrop {
1570
1591
  * @param doctype - The doctype to check
1571
1592
  * @param recordId - The record ID
1572
1593
  * @returns Object with `ready: true` if all blocked links are loaded, or `ready: false` with `blockedLinks` array
1594
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1573
1595
  */
1574
1596
  isWorkflowReady(doctype, recordId) {
1575
1597
  if (isDraftRecordId(recordId)) return { ready: true };
1598
+ const path = recordPath(doctype.slug, recordId);
1576
1599
  const links = this.registry.getDescendantLinks(doctype.slug);
1577
1600
  const blockedLinks = [];
1578
1601
  for (const link of links) if (this.getEffectiveBlockWorkflows(link)) {
1579
- const linkPath = `${doctype.slug}.${recordId}.${link.fieldname}`;
1602
+ const linkPath = `${path}.${link.fieldname}`;
1580
1603
  if (!this.hstStore.has(linkPath)) blockedLinks.push(link.fieldname);
1581
1604
  }
1582
1605
  if (blockedLinks.length > 0) return {
@@ -1659,6 +1682,7 @@ var Stonecrop = class Stonecrop {
1659
1682
  * @throws Error if no data client has been configured
1660
1683
  * @throws Error if a slug string is given and no matching doctype is found in the registry
1661
1684
  * @throws Error with code `"RECORD_NOT_FOUND"` if the server returns no record
1685
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1662
1686
  * @public
1663
1687
  */
1664
1688
  async getRecord(doctype, recordId, options) {
@@ -1746,6 +1770,7 @@ var Stonecrop = class Stonecrop {
1746
1770
  * @param recordId - The record identifier
1747
1771
  * @returns The current state name, `null` for a record not created yet, or an empty string if
1748
1772
  * the doctype has no workflow
1773
+ * @throws Error if the doctype has a workflow and `recordId` is empty, or holds a dot or a bracket
1749
1774
  *
1750
1775
  * @public
1751
1776
  */
@@ -1766,13 +1791,14 @@ var Stonecrop = class Stonecrop {
1766
1791
  * @param doctype - The doctype metadata
1767
1792
  * @param recordId - The record ID to collect
1768
1793
  * @returns The complete record payload ready for API submission
1794
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1769
1795
  * @public
1770
1796
  */
1771
1797
  collectRecordPayload(doctype, recordId) {
1772
- const recordPath = `${doctype.slug}.${recordId}`;
1773
- const payload = { ...this.hstStore.get(recordPath) || {} };
1798
+ const path = recordPath(doctype.slug, recordId);
1799
+ const payload = { ...this.hstStore.get(path) || {} };
1774
1800
  if (doctype.links) for (const [fieldname, link] of Object.entries(doctype.links)) {
1775
- const fieldPath = `${recordPath}.${fieldname}`;
1801
+ const fieldPath = `${path}.${fieldname}`;
1776
1802
  if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") {
1777
1803
  const arrayData = this.hstStore.get(fieldPath);
1778
1804
  if (Array.isArray(arrayData)) payload[fieldname] = arrayData;
@@ -1812,16 +1838,17 @@ var Stonecrop = class Stonecrop {
1812
1838
  * @param options - Query options (includeNested to control which links are fetched)
1813
1839
  * @throws Error with code `"CLIENT_REQUIRED"` if no data client is configured
1814
1840
  * @throws Error with code `"RECORD_NOT_FOUND"` if the server returns null
1841
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
1815
1842
  * @public
1816
1843
  */
1817
1844
  async fetchNestedData(path, doctype, recordId, options) {
1818
1845
  if (!this._client) throw createCodedError("No data client configured. Call setClient() with a DataClient implementation (e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.", "CLIENT_REQUIRED");
1846
+ const storePath = recordPath(doctype.slug, recordId);
1819
1847
  const result = await this._client.getRecord({ name: doctype.doctype }, recordId, { includeNested: options?.includeNested ?? true });
1820
1848
  if (!result?.record) throw recordNotFound(doctype, recordId);
1821
- const slug = doctype.slug;
1822
- this.ensureDoctypeExists(slug);
1823
- if (!this.hstStore.get(`${slug}.${recordId}`)) this.hstStore.set(`${slug}.${recordId}`, {}, "system");
1824
- for (const [key, value] of Object.entries(result.record)) this.hstStore.set(`${slug}.${recordId}.${key}`, value, "system");
1849
+ this.ensureDoctypeExists(doctype.slug);
1850
+ if (!this.hstStore.get(storePath)) this.hstStore.set(storePath, {}, "system");
1851
+ for (const [key, value] of Object.entries(result.record)) this.hstStore.set(`${storePath}.${key}`, value, "system");
1825
1852
  }
1826
1853
  /**
1827
1854
  * Recursively collect nested data from HST
@@ -2288,7 +2315,8 @@ function useClientAction(options = {}) {
2288
2315
  }
2289
2316
  /**
2290
2317
  * Handle a Desktop `@action` event: run the action's `clientHandler` if present,
2291
- * else dispatch to the server handler.
2318
+ * else dispatch to the server handler. An action raised with no record, as a list's is,
2319
+ * runs only through its `clientHandler`.
2292
2320
  */
2293
2321
  async function run(payload) {
2294
2322
  const sc = stonecrop.value;
@@ -2296,6 +2324,28 @@ function useClientAction(options = {}) {
2296
2324
  const { name, doctype: doctypeSlug, recordId, data } = payload;
2297
2325
  const clientHandler = (sc.registry.getDoctype(doctypeSlug)?.workflow)?.actions?.[name]?.clientHandler;
2298
2326
  try {
2327
+ const graphql = { query(query, variables) {
2328
+ const client = sc.getClient();
2329
+ if (!client?.query) return Promise.reject(/* @__PURE__ */ new Error("The configured data client does not support graphql.query"));
2330
+ return client.query(query, variables);
2331
+ } };
2332
+ const prefillDraft = (target, values) => sc.registry.prefillDraft(target, values);
2333
+ if (recordId === void 0) {
2334
+ if (!clientHandler) {
2335
+ onError({
2336
+ message: `Action "${name}" has no script, so it cannot run on a list.`,
2337
+ action: name,
2338
+ doctype: doctypeSlug
2339
+ });
2340
+ return;
2341
+ }
2342
+ await executeClientHandler(clientHandler, {
2343
+ router: resolveRouter(),
2344
+ graphql,
2345
+ prefillDraft
2346
+ });
2347
+ return;
2348
+ }
2299
2349
  if (!clientHandler) {
2300
2350
  const result = await dispatchAndWriteback(doctypeSlug, recordId, data, name);
2301
2351
  if (!result.success) onError({
@@ -2308,12 +2358,6 @@ function useClientAction(options = {}) {
2308
2358
  }
2309
2359
  const record = sc.getRecordById(doctypeSlug, recordId)?.get("") ?? data;
2310
2360
  const runAction = (action, extra) => dispatchAndWriteback(doctypeSlug, recordId, data, action, extra);
2311
- const graphql = { query(query, variables) {
2312
- const client = sc.getClient();
2313
- if (!client?.query) return Promise.reject(/* @__PURE__ */ new Error("The configured data client does not support graphql.query"));
2314
- return client.query(query, variables);
2315
- } };
2316
- const prefillDraft = (target, values) => sc.registry.prefillDraft(target, values);
2317
2361
  await executeClientHandler(clientHandler, {
2318
2362
  router: resolveRouter(),
2319
2363
  record,
@@ -2362,11 +2406,13 @@ function useClientAction(options = {}) {
2362
2406
  * @param recordId - The record ID
2363
2407
  * @param linkFieldname - The link fieldname to load
2364
2408
  * @returns LazyLink with loading, loaded, error, reload, and data
2409
+ * @throws Error if `recordId` is empty, or holds a dot or a bracket
2365
2410
  * @public
2366
2411
  */
2367
2412
  function useLazyLink(doctype, recordId, linkFieldname) {
2368
2413
  const stonecropInstance = inject("$stonecrop") || Stonecrop._root;
2369
2414
  if (!stonecropInstance) throw new Error("Stonecrop instance not available. Ensure useStonecrop() has been called first.");
2415
+ const storePath = recordPath(doctype.slug || doctype.doctype, recordId);
2370
2416
  const loading = ref(false);
2371
2417
  const loaded = ref(false);
2372
2418
  const error = ref(null);
@@ -2374,9 +2420,7 @@ function useLazyLink(doctype, recordId, linkFieldname) {
2374
2420
  /**
2375
2421
  * Build the HST path for a lazy link field
2376
2422
  */
2377
- const getLinkPath = () => {
2378
- return `${doctype.slug || doctype.doctype}.${recordId}.${linkFieldname}`;
2379
- };
2423
+ const getLinkPath = () => `${storePath}.${linkFieldname}`;
2380
2424
  /**
2381
2425
  * Get the link declaration from the doctype schema
2382
2426
  */
@@ -2401,12 +2445,11 @@ function useLazyLink(doctype, recordId, linkFieldname) {
2401
2445
  */
2402
2446
  const fetchLinkData = async () => {
2403
2447
  const linkFetch = getLinkDeclaration();
2404
- const ancestorPath = `${doctype.slug || doctype.doctype}.${recordId}`;
2405
2448
  if (linkFetch?.method === "custom") {
2406
- if (!hstStore.has(ancestorPath)) hstStore.set(ancestorPath, {}, "system");
2449
+ if (!hstStore.has(storePath)) hstStore.set(storePath, {}, "system");
2407
2450
  const result = await invokeCustomHandler(linkFetch.handler);
2408
2451
  hstStore.set(getLinkPath(), result, "system");
2409
- } else await stonecropInstance.fetchNestedData(ancestorPath, doctype, recordId, { includeNested: [linkFieldname] });
2452
+ } else await stonecropInstance.fetchNestedData(storePath, doctype, recordId, { includeNested: [linkFieldname] });
2410
2453
  };
2411
2454
  /**
2412
2455
  * Explicitly reload the lazy link data
@@ -2878,6 +2921,19 @@ var Doctype = class Doctype {
2878
2921
  return Object.entries(actions).filter(([, actionDef]) => actionDef.stateless === true && (currentState === null ? isActionAllowedOnNewRecord(actionDef) : isActionAllowedInState(actionDef, currentState ?? ""))).map(([name]) => ({ name }));
2879
2922
  }
2880
2923
  /**
2924
+ * Returns every action this doctype's workflow declares, in declaration order, whatever its kind
2925
+ * or state. A list shows these, since a list has no record whose state could narrow them. An
2926
+ * XState workflow declares none.
2927
+ *
2928
+ * @returns Array of action descriptors with `name`
2929
+ *
2930
+ * @public
2931
+ */
2932
+ getActions() {
2933
+ const actions = this.workflow?.actions;
2934
+ return Object.keys(actions ?? {}).map((name) => ({ name }));
2935
+ }
2936
+ /**
2881
2937
  * Returns the field-validation **triggers** declared on this doctype's workflow (advisory,
2882
2938
  * client-side). Keyed by trigger name. Returns undefined when the workflow is absent, is an
2883
2939
  * XState machine (no triggers), or simply declares none.