@stonecrop/stonecrop 0.16.6 → 0.18.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 (44) hide show
  1. package/README.md +16 -8
  2. package/dist/src/client-action.d.ts +31 -0
  3. package/dist/src/client-action.d.ts.map +1 -0
  4. package/dist/src/client-action.js +169 -0
  5. package/dist/src/composables/stonecrop.d.ts +9 -6
  6. package/dist/src/composables/stonecrop.d.ts.map +1 -1
  7. package/dist/src/composables/stonecrop.js +19 -90
  8. package/dist/src/doctype.d.ts +15 -12
  9. package/dist/src/doctype.d.ts.map +1 -1
  10. package/dist/src/doctype.js +19 -20
  11. package/dist/src/draft.d.ts +35 -0
  12. package/dist/src/draft.d.ts.map +1 -0
  13. package/dist/src/draft.js +36 -0
  14. package/dist/src/index.d.ts +4 -2
  15. package/dist/src/index.d.ts.map +1 -1
  16. package/dist/src/index.js +10 -4
  17. package/dist/src/registry.d.ts.map +1 -1
  18. package/dist/src/registry.js +6 -8
  19. package/dist/src/stonecrop.d.ts +67 -27
  20. package/dist/src/stonecrop.d.ts.map +1 -1
  21. package/dist/src/stonecrop.js +98 -84
  22. package/dist/src/stores/operation-log.d.ts +1 -1
  23. package/dist/src/types/client-action.d.ts +121 -0
  24. package/dist/src/types/client-action.d.ts.map +1 -0
  25. package/dist/src/types/client-action.js +0 -0
  26. package/dist/src/types/doctype.d.ts +1 -4
  27. package/dist/src/types/doctype.d.ts.map +1 -1
  28. package/dist/src/types/index.d.ts +1 -0
  29. package/dist/src/types/index.d.ts.map +1 -1
  30. package/dist/src/types/index.js +1 -0
  31. package/dist/stonecrop.d.ts +274 -49
  32. package/dist/stonecrop.js +662 -617
  33. package/dist/stonecrop.js.map +1 -1
  34. package/package.json +4 -4
  35. package/src/client-action.ts +207 -0
  36. package/src/composables/stonecrop.ts +28 -102
  37. package/src/doctype.ts +18 -20
  38. package/src/draft.ts +38 -0
  39. package/src/index.ts +8 -2
  40. package/src/registry.ts +6 -8
  41. package/src/stonecrop.ts +107 -93
  42. package/src/types/client-action.ts +121 -0
  43. package/src/types/doctype.ts +1 -4
  44. package/src/types/index.ts +1 -0
package/src/stonecrop.ts CHANGED
@@ -1,12 +1,11 @@
1
- import type { DataClient } from '@stonecrop/schema'
1
+ import type { DataClient, GetRecordOptions, GetRecordsOptions, GetRecordsResult } from '@stonecrop/schema'
2
2
  import { reactive } from 'vue'
3
3
 
4
4
  import Doctype from './doctype'
5
- import { getGlobalTriggerEngine } from './field-triggers'
5
+ import { isDraftRecordId } from './draft'
6
6
  import Registry from './registry'
7
7
  import { createHST, type HSTNode } from './stores/hst'
8
8
  import { useOperationLogStore } from './stores/operation-log'
9
- import type { FieldChangeContext } from './types/field-triggers'
10
9
  import type { OperationLogConfig } from './types/operation-log'
11
10
  import type { RouteContext } from './types/registry'
12
11
  import type { StonecropOptions } from './types/stonecrop'
@@ -30,6 +29,12 @@ export class Stonecrop {
30
29
  private _operationLogConfig?: Partial<OperationLogConfig>
31
30
  private _client?: DataClient
32
31
 
32
+ /**
33
+ * Per-doctype page info from the last list read, keyed by slug. Reactive so views tracking
34
+ * it update on fetch. Deliberately not in HST — see {@link Stonecrop.getRecords}.
35
+ */
36
+ private pageInfo: Record<string, { hasMore: boolean; count?: number }> = reactive({})
37
+
33
38
  /** The registry instance containing all doctype definitions */
34
39
  readonly registry!: Registry
35
40
 
@@ -240,72 +245,6 @@ export class Stonecrop {
240
245
  this.ensureDoctypeExists(doctype.slug)
241
246
  }
242
247
 
243
- /**
244
- * Run action on doctype
245
- * Executes the action and logs it to the operation log for audit tracking
246
- * @param doctype - The doctype
247
- * @param action - The action to run
248
- * @param args - Action arguments (typically record IDs)
249
- */
250
- runAction(doctype: Doctype, action: string, args?: string[]): void {
251
- const registry = this.registry.registry[doctype.slug]
252
- const actions = registry?.actions?.get(action)
253
- const recordIds = Array.isArray(args) ? args.filter((arg): arg is string => typeof arg === 'string') : undefined
254
- const recordId = recordIds?.[0]
255
-
256
- // Check if workflow is ready (all blocked links have data)
257
- const workflowStatus = recordId ? this.isWorkflowReady(doctype, recordId) : { ready: true }
258
- if (!workflowStatus.ready) {
259
- const opLogStore = this.getOperationLogStore()
260
- opLogStore.logAction(
261
- doctype.doctype,
262
- action,
263
- recordIds,
264
- 'failure',
265
- `BLOCKED: missing data for links: ${workflowStatus.blockedLinks?.join(', ')}`
266
- )
267
- throw new Error(`Workflow blocked: missing data for links: ${workflowStatus.blockedLinks?.join(', ')}`)
268
- }
269
-
270
- // Log action execution start
271
- const opLogStore = this.getOperationLogStore()
272
- let actionResult: 'success' | 'failure' | 'pending' = 'success'
273
- let actionError: string | undefined
274
-
275
- try {
276
- // Execute action functions
277
- if (actions && actions.length > 0) {
278
- const engine = getGlobalTriggerEngine()
279
- actions.forEach(actionStr => {
280
- try {
281
- const actionFn = engine.getAction(actionStr)
282
- if (!actionFn) throw new Error(`Action "${actionStr}" is not registered in FieldTriggerEngine`)
283
- const context = {
284
- path: `${doctype.slug}.${recordIds?.[0] ?? ''}`,
285
- fieldname: action,
286
- beforeValue: undefined,
287
- afterValue: args,
288
- operation: 'set',
289
- doctype: doctype.doctype,
290
- recordId: recordId,
291
- timestamp: new Date(),
292
- } as FieldChangeContext
293
- void actionFn(context)
294
- } catch (error) {
295
- actionResult = 'failure'
296
- actionError = error instanceof Error ? error.message : 'Unknown error'
297
- throw error
298
- }
299
- })
300
- }
301
- } catch {
302
- // Error already set in inner catch
303
- } finally {
304
- // Log the action execution to operation log
305
- opLogStore.logAction(doctype.doctype, action, recordIds, actionResult, actionError)
306
- }
307
- }
308
-
309
248
  /**
310
249
  * Get the effective blockWorkflows value for a link.
311
250
  * Returns true if blockWorkflows is explicitly true, or if it's absent and fetch method is 'sync'.
@@ -331,7 +270,7 @@ export class Stonecrop {
331
270
  */
332
271
  isWorkflowReady(doctype: Doctype, recordId: string): { ready: boolean; blockedLinks?: string[] } {
333
272
  // New records don't block workflows - they haven't been saved yet
334
- if (recordId === 'new') {
273
+ if (isDraftRecordId(recordId)) {
335
274
  return { ready: true }
336
275
  }
337
276
 
@@ -354,11 +293,24 @@ export class Stonecrop {
354
293
  }
355
294
 
356
295
  /**
357
- * Get records from server using the configured data client.
296
+ * Fetch a doctype's records from the server and store them in HST.
297
+ *
298
+ * This is the one read path for a list. Every caller shares its keying rule, so a row is
299
+ * always stored under the identity its Edit link will later ask for.
300
+ *
301
+ * Deliberately unguarded, unlike {@link Stonecrop.getRecord}: a list is a view of data that
302
+ * changes, so revisiting one must re-read it rather than serve whatever HST happens to hold.
303
+ *
304
+ * `options` is forwarded to the client untouched — no row limit is invented here, because
305
+ * nothing on this side of the wire knows what is safe for an arbitrary backend. A caller that
306
+ * passes none gets whatever the server considers a reasonable page.
307
+ *
358
308
  * @param doctype - The doctype
309
+ * @param options - Query options (filters, orderBy, limit, offset), forwarded to the client
359
310
  * @throws Error if no data client has been configured
311
+ * @public
360
312
  */
361
- async getRecords(doctype: Doctype): Promise<void> {
313
+ async getRecords(doctype: Doctype, options?: GetRecordsOptions): Promise<GetRecordsResult> {
362
314
  if (!this._client) {
363
315
  throw new Error(
364
316
  'No data client configured. Call setClient() with a DataClient implementation ' +
@@ -366,7 +318,13 @@ export class Stonecrop {
366
318
  )
367
319
  }
368
320
 
369
- const records = await this._client.getRecords(doctype)
321
+ const result = await this._client.getRecords(doctype, options)
322
+ const records = result.data
323
+
324
+ // Page info is kept beside HST, not in it. `getRecordIds` reads the raw keys under a
325
+ // doctype node, so anything filed there becomes a phantom record — the same hazard that
326
+ // ruled out seeding a draft node.
327
+ this.pageInfo[doctype.slug] = { hasMore: result.hasMore, count: result.count }
370
328
 
371
329
  // Key each record by its declared primary key, falling back to `id`. This used to read
372
330
  // `record.id` only, which silently dropped every row of a natural-keyed doctype (no `id`
@@ -378,16 +336,45 @@ export class Stonecrop {
378
336
  this.addRecord(doctype, recordId, record)
379
337
  }
380
338
  })
339
+
340
+ return result
341
+ }
342
+
343
+ /**
344
+ * What the last {@link Stonecrop.getRecords} for this doctype returned about the wider set.
345
+ *
346
+ * Answers the question HST cannot: HST holds what was fetched, so counting its keys reports
347
+ * how much has been seen, never how much exists. Reactive, so a view reading it re-renders
348
+ * when a fetch lands.
349
+ *
350
+ * @param doctype - The doctype slug string or Doctype object
351
+ * @returns Page info, or undefined if this doctype's records have not been fetched
352
+ * @public
353
+ */
354
+ getPageInfo(doctype: string | Doctype): { hasMore: boolean; count?: number } | undefined {
355
+ const slug = typeof doctype === 'string' ? doctype : doctype.slug
356
+ return this.pageInfo[slug]
381
357
  }
382
358
 
383
359
  /**
384
- * Get single record from server using the configured data client.
360
+ * Fetch a single record from the server and store it in HST.
361
+ *
362
+ * This is the one read path for a record, and it owns the whole job: deciding whether a fetch
363
+ * is warranted, performing it, and writing the result back under the doctype's declared
364
+ * identity. Callers ask for a record and get one; they do not re-derive when to ask.
365
+ *
366
+ * Two cases return without touching the network, because in both the answer is already known:
367
+ * a draft does not exist on the server yet, and a record already in HST has been read.
368
+ * Refetching the latter would also discard unsaved edits sitting in the store.
369
+ *
385
370
  * @param doctype - The doctype slug string or Doctype object
386
371
  * @param recordId - The record ID
372
+ * @param options - Query options (includeNested, maxDepth), forwarded to the client
387
373
  * @throws Error if no data client has been configured
388
374
  * @throws Error if a slug string is given and no matching doctype is found in the registry
375
+ * @public
389
376
  */
390
- async getRecord(doctype: string | Doctype, recordId: string): Promise<void> {
377
+ async getRecord(doctype: string | Doctype, recordId: string, options?: GetRecordOptions): Promise<void> {
391
378
  if (!this._client) {
392
379
  throw new Error(
393
380
  'No data client configured. Call setClient() with a DataClient implementation ' +
@@ -400,7 +387,17 @@ export class Stonecrop {
400
387
  throw new Error(`Doctype not found: ${typeof doctype === 'string' ? doctype : doctype.slug}`)
401
388
  }
402
389
 
403
- const result = await this._client.getRecord(resolved, recordId)
390
+ // An unsaved draft has no server record, so a fetch could only ever miss. This guard used
391
+ // to live in every host, which is how the private draft-id scheme leaked into all of them.
392
+ if (isDraftRecordId(recordId)) {
393
+ return
394
+ }
395
+
396
+ if (this.getRecordById(resolved.slug, recordId)) {
397
+ return
398
+ }
399
+
400
+ const result = await this._client.getRecord(resolved, recordId, options)
404
401
 
405
402
  if (result?.record) {
406
403
  this.addRecord(resolved, recordId, result.record)
@@ -408,8 +405,23 @@ export class Stonecrop {
408
405
  }
409
406
 
410
407
  /**
411
- * Dispatch an action to the server via the configured data client.
412
- * All state changes flow through this single mutation endpoint.
408
+ * Dispatch an action to the server via the configured data client, and file the record it
409
+ * returns into HST under the identity the *server* settled on.
410
+ *
411
+ * The write is the point. For a created record the settled identity is never the one that was
412
+ * dispatched, so a caller that stores the result under the id it sent files the record under a
413
+ * key nothing can fetch and leaves the next save creating a second one. Every host that
414
+ * hand-rolled this got it wrong the same way, so it stops being the caller's job — this is the
415
+ * write-side twin of {@link Stonecrop.getRecords}, which keys reads by the same rule.
416
+ *
417
+ * Two things are deliberately NOT done here, because both need the id that was dispatched and
418
+ * that lives inside `args` — an opaque array whose shape is a convention between a host's
419
+ * client and its server handlers, not something this layer may parse. Dropping the stale key
420
+ * and moving the route therefore stay with `useClientAction`, which knows both ids.
421
+ *
422
+ * A result that states no identity of its own — a `{ state: 'APPROVED' }` outcome — is left
423
+ * alone rather than guessed at, for the same reason `settledRecordId` is strict: a partial
424
+ * record must not be able to look like a rename.
413
425
  *
414
426
  * @param doctype - The doctype
415
427
  * @param action - Action name to execute (e.g., 'SUBMIT', 'APPROVE', 'save')
@@ -429,7 +441,23 @@ export class Stonecrop {
429
441
  )
430
442
  }
431
443
 
432
- return this._client.runAction(doctype, action, args)
444
+ const result = await this._client.runAction(doctype, action, args)
445
+
446
+ if (result.success && result.data && typeof result.data === 'object' && !Array.isArray(result.data)) {
447
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the guard above confirms a non-null, non-array object; the action result payload is an opaque JSON scalar
448
+ const record = result.data as Record<string, unknown>
449
+ // Require the declared key to be *present* before trusting `getRecordId`, which falls
450
+ // back to `id`. Without that, a handler returning `{ id, total }` for a natural-keyed
451
+ // doctype would relocate the record to a key the adapter cannot look up.
452
+ if (record[doctype.recordIdField] !== undefined) {
453
+ const settledId = doctype.getRecordId(record)
454
+ if (settledId !== undefined) {
455
+ this.addRecord(doctype, settledId, record)
456
+ }
457
+ }
458
+ }
459
+
460
+ return result
433
461
  }
434
462
 
435
463
  /**
@@ -658,20 +686,6 @@ export class Stonecrop {
658
686
  }
659
687
  }
660
688
 
661
- /**
662
- * Returns the global Stonecrop singleton instance, or `undefined` if no
663
- * instance has been created yet.
664
- *
665
- * Use this when you need the Stonecrop instance outside a Vue component
666
- * context (e.g., in workflow action handlers, plugin setup code, or
667
- * non-component utilities). Inside a component, prefer `useStonecrop()`.
668
- *
669
- * @public
670
- */
671
- export function getStonecrop(): Stonecrop | undefined {
672
- return Stonecrop._root
673
- }
674
-
675
689
  /**
676
690
  * Create an Error with a `code` property for programmatic error handling.
677
691
  * @internal
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Payload emitted with the 'action' event when the user triggers a declared action —
3
+ * an FSM transition or a stateless Command.
4
+ *
5
+ * Defined here rather than in `@stonecrop/desktop` because the shell that *emits* it and the
6
+ * runner that *consumes* it now live in different packages, and desktop already depends on this
7
+ * one. `@stonecrop/desktop` re-exports it, so a host importing it from there is unaffected.
8
+ *
9
+ * @public
10
+ */
11
+ export type ActionEventPayload = {
12
+ /** The declared action name (e.g. 'SAVE', 'SUBMIT', 'APPROVE') */
13
+ name: string
14
+ doctype: string
15
+ recordId: string
16
+ /** Snapshot of the form data at the time the action was triggered */
17
+ data: Record<string, any>
18
+ }
19
+
20
+ /**
21
+ * Result of dispatching an action to its server handler.
22
+ * @public
23
+ */
24
+ export type ActionDispatchResult = { success: boolean; data: unknown; error: string | null }
25
+
26
+ /**
27
+ * An action that did not complete, described well enough for a host to render it.
28
+ *
29
+ * An object rather than a bare message on purpose: a notification says *what* failed, and the
30
+ * action, doctype and record are all known at the point of failure. It is also the shape that can
31
+ * gain a field later without breaking a host that already destructures it.
32
+ *
33
+ * @public
34
+ */
35
+ export interface ActionFailure {
36
+ /** Human-readable reason — the server's own message where there is one. */
37
+ message: string
38
+ /** The action that was clicked, not necessarily the one a `clientHandler` dispatched. */
39
+ action: string
40
+ /** Slug of the doctype the action was raised on. */
41
+ doctype: string
42
+ /** Record the action was raised against; the `new` route segment for an unsaved record. */
43
+ recordId: string
44
+ /** The thrown value, present only when the failure was a throw rather than a refused dispatch. */
45
+ cause?: unknown
46
+ }
47
+
48
+ /**
49
+ * Everything known about a dispatch at the point the argument array is built.
50
+ * @public
51
+ */
52
+ export interface ActionArgsContext {
53
+ /** Slug of the doctype the action was raised on. */
54
+ doctype: string
55
+ /** The action being dispatched. */
56
+ action: string
57
+ /** The route's record segment — {@link DRAFT_RECORD_ID} for an unsaved record. */
58
+ recordId: string
59
+ /** Whether `recordId` is the draft segment rather than a real identity. */
60
+ isDraft: boolean
61
+ /** The form snapshot being sent. */
62
+ data: Record<string, unknown>
63
+ /** Extra fields a `clientHandler` passed to `runAction`. */
64
+ extra?: Record<string, unknown>
65
+ }
66
+
67
+ /**
68
+ * Where a record ended up after the server settled its identity.
69
+ * @public
70
+ */
71
+ export interface FollowRecordContext {
72
+ /** Slug of the doctype the action was raised on. */
73
+ doctype: string
74
+ /** The identity the server settled on — where the record now lives. */
75
+ recordId: string
76
+ /** The identity that was dispatched, which is no longer valid. */
77
+ previousRecordId: string
78
+ }
79
+
80
+ /**
81
+ * Host overrides for `useClientAction`.
82
+ *
83
+ * These are the three things that legitimately differ between applications: how your backend wants
84
+ * an action's arguments shaped, where the user should end up after a create, and how a failure is
85
+ * shown. Everything else is framework behaviour and is deliberately not configurable — in
86
+ * particular, resolving a record's identity and keying it into HST stay sealed, because that is
87
+ * the rule the adapter re-derives server-side, and every host that re-derived it got it wrong.
88
+ *
89
+ * @public
90
+ */
91
+ export interface UseClientActionOptions {
92
+ /**
93
+ * Called instead of the built-in alert when an action fails. Supply this to route failures into
94
+ * the host's own notification system, or pass a no-op to suppress them entirely.
95
+ *
96
+ * It fully replaces the default, console log included — a host that wants one writes it.
97
+ */
98
+ onError?: (failure: ActionFailure) => void
99
+ /**
100
+ * Build the opaque argument array handed to `DataClient.runAction`.
101
+ *
102
+ * The default is `[{ id, data }]`, omitting `id` entirely for a draft — the envelope every
103
+ * in-repo server handler destructures. Supply this when your backend expects another shape;
104
+ * `examples/desktop` uses positional `[recordId, data]`, for instance. Nothing validates the
105
+ * array, so both ends of your own stack have to agree on it.
106
+ *
107
+ * Whatever you return is sent verbatim. It does not affect how the *result* is stored — that
108
+ * is keyed off the returned record's declared identity, not off what was sent.
109
+ */
110
+ buildArgs?: (context: ActionArgsContext) => unknown[]
111
+ /**
112
+ * Move the user to where a record ended up when the server settled on a different identity —
113
+ * the create case, and any action that rewrites a natural key.
114
+ *
115
+ * The default is `router.replace('/{doctype}/{recordId}')`. `replace`, not `push`: the route
116
+ * being left behind was never a record, so going Back to `/{doctype}/new` would show an empty
117
+ * form that creates yet another record. Supply this for a locale prefix, a nested path, or to
118
+ * stay put; the store has already been updated either way.
119
+ */
120
+ followRecord?: (context: FollowRecordContext) => void | Promise<void>
121
+ }
@@ -1,5 +1,5 @@
1
1
  import type { DoctypeField, LinkDeclaration, WorkflowMeta } from '@stonecrop/schema'
2
- import { List, Map } from 'immutable'
2
+ import { List } from 'immutable'
3
3
  import type { AnyStateNodeConfig, UnknownMachineConfig } from 'xstate'
4
4
 
5
5
  /**
@@ -10,7 +10,6 @@ import type { AnyStateNodeConfig, UnknownMachineConfig } from 'xstate'
10
10
  export type ImmutableDoctype = {
11
11
  readonly schema?: List<DoctypeField>
12
12
  readonly workflow?: UnknownMachineConfig | AnyStateNodeConfig | WorkflowMeta
13
- readonly actions?: Map<string, string[]>
14
13
  }
15
14
 
16
15
  /**
@@ -29,8 +28,6 @@ export type DoctypeConfig = {
29
28
  links?: Record<string, LinkDeclaration>
30
29
  /** Workflow configuration (XState format or simple WorkflowMeta) */
31
30
  workflow?: UnknownMachineConfig | WorkflowMeta
32
- /** Actions and their field triggers */
33
- actions?: Record<string, string[]>
34
31
  /** Ancestor doctype for inheritance */
35
32
  inherits?: string
36
33
  }
@@ -1,4 +1,5 @@
1
1
  // Re-export all type files
2
+ export * from './client-action'
2
3
  export * from './composable'
3
4
  export * from './doctype'
4
5
  export * from './field-triggers'