@stonecrop/stonecrop 0.31.0 → 0.32.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 (121) hide show
  1. package/dist/stonecrop.js +3548 -2740
  2. package/dist/stonecrop.js.map +1 -1
  3. package/dist/tsdoc-metadata.json +1 -1
  4. package/package.json +33 -27
  5. package/dist/src/client-action.d.ts +0 -31
  6. package/dist/src/client-action.d.ts.map +0 -1
  7. package/dist/src/client-action.js +0 -169
  8. package/dist/src/client-handler.d.ts +0 -43
  9. package/dist/src/client-handler.d.ts.map +0 -1
  10. package/dist/src/client-handler.js +0 -42
  11. package/dist/src/composables/lazy-link.d.ts +0 -25
  12. package/dist/src/composables/lazy-link.d.ts.map +0 -1
  13. package/dist/src/composables/lazy-link.js +0 -124
  14. package/dist/src/composables/operation-log.d.ts +0 -136
  15. package/dist/src/composables/operation-log.d.ts.map +0 -1
  16. package/dist/src/composables/operation-log.js +0 -224
  17. package/dist/src/composables/stonecrop.d.ts +0 -37
  18. package/dist/src/composables/stonecrop.d.ts.map +0 -1
  19. package/dist/src/composables/stonecrop.js +0 -433
  20. package/dist/src/doctype.d.ts +0 -243
  21. package/dist/src/doctype.d.ts.map +0 -1
  22. package/dist/src/doctype.js +0 -325
  23. package/dist/src/draft.d.ts +0 -35
  24. package/dist/src/draft.d.ts.map +0 -1
  25. package/dist/src/draft.js +0 -36
  26. package/dist/src/exceptions.d.ts +0 -14
  27. package/dist/src/exceptions.d.ts.map +0 -1
  28. package/dist/src/exceptions.js +0 -16
  29. package/dist/src/field-triggers.d.ts +0 -184
  30. package/dist/src/field-triggers.d.ts.map +0 -1
  31. package/dist/src/field-triggers.js +0 -577
  32. package/dist/src/index.d.ts +0 -25
  33. package/dist/src/index.d.ts.map +0 -1
  34. package/dist/src/index.js +0 -39
  35. package/dist/src/plugins/index.d.ts +0 -35
  36. package/dist/src/plugins/index.d.ts.map +0 -1
  37. package/dist/src/plugins/index.js +0 -98
  38. package/dist/src/registry.d.ts +0 -161
  39. package/dist/src/registry.d.ts.map +0 -1
  40. package/dist/src/registry.js +0 -384
  41. package/dist/src/schema-validator.d.ts +0 -78
  42. package/dist/src/schema-validator.d.ts.map +0 -1
  43. package/dist/src/schema-validator.js +0 -398
  44. package/dist/src/stonecrop.d.ts +0 -539
  45. package/dist/src/stonecrop.d.ts.map +0 -1
  46. package/dist/src/stonecrop.js +0 -610
  47. package/dist/src/stores/hst.d.ts +0 -92
  48. package/dist/src/stores/hst.d.ts.map +0 -1
  49. package/dist/src/stores/hst.js +0 -487
  50. package/dist/src/stores/index.d.ts +0 -9
  51. package/dist/src/stores/index.d.ts.map +0 -1
  52. package/dist/src/stores/index.js +0 -13
  53. package/dist/src/stores/operation-log.d.ts +0 -262
  54. package/dist/src/stores/operation-log.d.ts.map +0 -1
  55. package/dist/src/stores/operation-log.js +0 -571
  56. package/dist/src/stores/validation.d.ts +0 -83
  57. package/dist/src/stores/validation.d.ts.map +0 -1
  58. package/dist/src/stores/validation.js +0 -104
  59. package/dist/src/types/client-action.d.ts +0 -121
  60. package/dist/src/types/client-action.d.ts.map +0 -1
  61. package/dist/src/types/client-action.js +0 -0
  62. package/dist/src/types/composable.d.ts +0 -268
  63. package/dist/src/types/composable.d.ts.map +0 -1
  64. package/dist/src/types/composable.js +0 -0
  65. package/dist/src/types/doctype.d.ts +0 -34
  66. package/dist/src/types/doctype.d.ts.map +0 -1
  67. package/dist/src/types/doctype.js +0 -0
  68. package/dist/src/types/field-triggers.d.ts +0 -186
  69. package/dist/src/types/field-triggers.d.ts.map +0 -1
  70. package/dist/src/types/field-triggers.js +0 -4
  71. package/dist/src/types/hst.d.ts +0 -70
  72. package/dist/src/types/hst.d.ts.map +0 -1
  73. package/dist/src/types/hst.js +0 -0
  74. package/dist/src/types/index.d.ts +0 -11
  75. package/dist/src/types/index.d.ts.map +0 -1
  76. package/dist/src/types/index.js +0 -11
  77. package/dist/src/types/operation-log.d.ts +0 -163
  78. package/dist/src/types/operation-log.d.ts.map +0 -1
  79. package/dist/src/types/operation-log.js +0 -0
  80. package/dist/src/types/plugin.d.ts +0 -37
  81. package/dist/src/types/plugin.d.ts.map +0 -1
  82. package/dist/src/types/plugin.js +0 -0
  83. package/dist/src/types/registry.d.ts +0 -11
  84. package/dist/src/types/registry.d.ts.map +0 -1
  85. package/dist/src/types/registry.js +0 -0
  86. package/dist/src/types/schema-validator.d.ts +0 -66
  87. package/dist/src/types/schema-validator.d.ts.map +0 -1
  88. package/dist/src/types/schema-validator.js +0 -13
  89. package/dist/src/types/stonecrop.d.ts +0 -32
  90. package/dist/src/types/stonecrop.d.ts.map +0 -1
  91. package/dist/src/types/stonecrop.js +0 -0
  92. package/dist/stonecrop.tsbuildinfo +0 -1
  93. package/src/client-action.ts +0 -207
  94. package/src/client-handler.ts +0 -55
  95. package/src/composables/lazy-link.ts +0 -145
  96. package/src/composables/operation-log.ts +0 -257
  97. package/src/composables/stonecrop.ts +0 -556
  98. package/src/doctype.ts +0 -360
  99. package/src/draft.ts +0 -38
  100. package/src/exceptions.ts +0 -16
  101. package/src/field-triggers.ts +0 -686
  102. package/src/index.ts +0 -81
  103. package/src/plugins/index.ts +0 -113
  104. package/src/registry.ts +0 -433
  105. package/src/schema-validator.ts +0 -476
  106. package/src/stonecrop.ts +0 -721
  107. package/src/stores/hst.ts +0 -626
  108. package/src/stores/index.ts +0 -21
  109. package/src/stores/operation-log.ts +0 -675
  110. package/src/stores/validation.ts +0 -138
  111. package/src/types/client-action.ts +0 -121
  112. package/src/types/composable.ts +0 -288
  113. package/src/types/doctype.ts +0 -35
  114. package/src/types/field-triggers.ts +0 -201
  115. package/src/types/hst.ts +0 -77
  116. package/src/types/index.ts +0 -11
  117. package/src/types/operation-log.ts +0 -202
  118. package/src/types/plugin.ts +0 -38
  119. package/src/types/registry.ts +0 -10
  120. package/src/types/schema-validator.ts +0 -69
  121. package/src/types/stonecrop.ts +0 -33
@@ -1,610 +0,0 @@
1
- import { reactive } from 'vue';
2
- import { isDraftRecordId } from './draft';
3
- import { createHST } from './stores/hst';
4
- import { useOperationLogStore } from './stores/operation-log';
5
- /**
6
- * Main Stonecrop class with HST integration and built-in Operation Log
7
- * @public
8
- */
9
- export class Stonecrop {
10
- /**
11
- * Singleton instance of Stonecrop. Only one Stonecrop instance can exist
12
- * per application, ensuring consistent HST state and registry access.
13
- * Subsequent constructor calls return this instance instead of creating new ones.
14
- * @internal
15
- */
16
- static _root;
17
- /** The HST store instance for reactive state management */
18
- hstStore;
19
- _operationLogStore;
20
- _operationLogConfig;
21
- _client;
22
- /**
23
- * Per-doctype page info from the last list read, keyed by slug. Reactive so views tracking
24
- * it update on fetch. Deliberately not in HST — see {@link Stonecrop.getRecords}.
25
- */
26
- pageInfo = reactive({});
27
- /** The registry instance containing all doctype definitions */
28
- registry;
29
- /**
30
- * Creates a new Stonecrop instance with HST integration (singleton pattern)
31
- * @param registry - The Registry instance containing doctype definitions
32
- * @param operationLogConfig - Optional configuration for the operation log
33
- * @param options - Options including the data client (can be set later via setClient)
34
- */
35
- constructor(registry, operationLogConfig, options) {
36
- if (Stonecrop._root) {
37
- return Stonecrop._root;
38
- }
39
- Stonecrop._root = this;
40
- this.registry = registry;
41
- // Store config for lazy initialization
42
- this._operationLogConfig = operationLogConfig;
43
- // Store data client (can be set later via setClient)
44
- this._client = options?.client;
45
- // Initialize HST store with auto-sync to Registry
46
- this.initializeHSTStore();
47
- this.setupRegistrySync();
48
- return this;
49
- }
50
- /**
51
- * Set the data client for fetching doctype metadata and records.
52
- * Use this for deferred configuration in Nuxt/Vue plugin setups.
53
- *
54
- * @param client - DataClient implementation (e.g., StonecropClient from \@stonecrop/graphql-client)
55
- *
56
- * @example
57
- * ```ts
58
- * const { setClient } = useStonecropRegistry()
59
- * const client = new StonecropClient({ endpoint: '/graphql' })
60
- * setClient(client)
61
- * ```
62
- */
63
- setClient(client) {
64
- this._client = client;
65
- }
66
- /**
67
- * Get the current data client
68
- * @returns The DataClient instance or undefined if not set
69
- */
70
- getClient() {
71
- return this._client;
72
- }
73
- /**
74
- * Get the operation log store (lazy initialization)
75
- * @internal
76
- */
77
- getOperationLogStore() {
78
- if (!this._operationLogStore) {
79
- this._operationLogStore = useOperationLogStore();
80
- if (this._operationLogConfig) {
81
- this._operationLogStore.configure(this._operationLogConfig);
82
- }
83
- }
84
- return this._operationLogStore;
85
- }
86
- /**
87
- * Initialize the HST store structure
88
- */
89
- initializeHSTStore() {
90
- const initialStoreStructure = {};
91
- // Auto-populate from existing Registry doctypes
92
- Object.keys(this.registry.registry).forEach(doctypeSlug => {
93
- initialStoreStructure[doctypeSlug] = {};
94
- });
95
- // Wrap the store in Vue's reactive() for automatic change detection
96
- // This enables Vue computed properties to track HST store changes
97
- this.hstStore = createHST(reactive(initialStoreStructure), 'StonecropStore');
98
- }
99
- /**
100
- * Setup automatic sync with Registry when doctypes are added
101
- */
102
- setupRegistrySync() {
103
- // Extend Registry.addDoctype to auto-create HST store sections
104
- const originalAddDoctype = this.registry.addDoctype.bind(this.registry);
105
- this.registry.addDoctype = (doctype) => {
106
- // Call original method
107
- originalAddDoctype(doctype);
108
- // Auto-create HST store section for new doctype
109
- if (!this.hstStore.has(doctype.slug)) {
110
- this.hstStore.set(doctype.slug, {});
111
- }
112
- };
113
- }
114
- /**
115
- * Get records hash for a doctype
116
- * @param doctype - The doctype to get records for
117
- * @returns HST node containing records hash
118
- */
119
- records(doctype) {
120
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
121
- this.ensureDoctypeExists(slug);
122
- return this.hstStore.getNode(slug);
123
- }
124
- /**
125
- * Add a record to the store
126
- * @param doctype - The doctype
127
- * @param recordId - The record ID
128
- * @param recordData - The record data
129
- */
130
- addRecord(doctype, recordId, recordData) {
131
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
132
- this.ensureDoctypeExists(slug);
133
- // Store raw record data - let HST handle wrapping with proper hierarchy
134
- this.hstStore.set(`${slug}.${recordId}`, recordData);
135
- }
136
- /**
137
- * Get a specific record
138
- * @param doctype - The doctype
139
- * @param recordId - The record ID
140
- * @returns HST node for the record or undefined
141
- */
142
- getRecordById(doctype, recordId) {
143
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
144
- this.ensureDoctypeExists(slug);
145
- // First check if the record exists
146
- const recordExists = this.hstStore.has(`${slug}.${recordId}`);
147
- if (!recordExists) {
148
- return undefined;
149
- }
150
- // Check if the actual value is undefined (i.e., record was removed)
151
- const recordValue = this.hstStore.get(`${slug}.${recordId}`);
152
- if (recordValue === undefined) {
153
- return undefined;
154
- }
155
- // Use getNode to get the properly wrapped HST node with correct ancestor relationships
156
- return this.hstStore.getNode(`${slug}.${recordId}`);
157
- }
158
- /**
159
- * Remove a record from the store
160
- * @param doctype - The doctype
161
- * @param recordId - The record ID
162
- */
163
- removeRecord(doctype, recordId) {
164
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
165
- this.ensureDoctypeExists(slug);
166
- // Remove the specific record directly by setting to undefined
167
- if (this.hstStore.has(`${slug}.${recordId}`)) {
168
- this.hstStore.set(`${slug}.${recordId}`, undefined);
169
- }
170
- }
171
- /**
172
- * Get all record IDs for a doctype
173
- * @param doctype - The doctype
174
- * @returns Array of record IDs
175
- */
176
- getRecordIds(doctype) {
177
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
178
- this.ensureDoctypeExists(slug);
179
- const doctypeNode = this.hstStore.get(slug);
180
- if (!doctypeNode || typeof doctypeNode !== 'object') {
181
- return [];
182
- }
183
- return Object.keys(doctypeNode).filter(key => doctypeNode[key] !== undefined);
184
- }
185
- /**
186
- * Clear all records for a doctype
187
- * @param doctype - The doctype
188
- */
189
- clearRecords(doctype) {
190
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
191
- this.ensureDoctypeExists(slug);
192
- // Get all record IDs and remove them
193
- const recordIds = this.getRecordIds(slug);
194
- recordIds.forEach(recordId => {
195
- this.hstStore.set(`${slug}.${recordId}`, undefined);
196
- });
197
- }
198
- /**
199
- * Setup method for doctype initialization
200
- * @param doctype - The doctype to setup
201
- */
202
- setup(doctype) {
203
- // Ensure doctype exists in store
204
- this.ensureDoctypeExists(doctype.slug);
205
- }
206
- /**
207
- * Get the effective blockWorkflows value for a link.
208
- * Returns true if blockWorkflows is explicitly true, or if it's absent and fetch method is 'sync'.
209
- * @param link - The link declaration
210
- * @returns Whether workflows should be blocked until this link is loaded
211
- */
212
- getEffectiveBlockWorkflows(link) {
213
- if (link.blockWorkflows !== undefined) {
214
- return link.blockWorkflows;
215
- }
216
- // TODO: For custom fetch handlers, this returns false (not blocking), but the custom handler
217
- // may still be invoked by useLazyLink. Future: custom handlers should be able to declare they
218
- // satisfy blockWorkflows, or validation should reject custom + blockWorkflows: true.
219
- return link.fetch?.method === 'sync';
220
- }
221
- /**
222
- * Check if workflow actions are ready to run (all required link data is loaded).
223
- * A link's data is considered loaded if it exists in HST at `slug.recordId.linkname`.
224
- * @param doctype - The doctype to check
225
- * @param recordId - The record ID
226
- * @returns Object with `ready: true` if all blocked links are loaded, or `ready: false` with `blockedLinks` array
227
- */
228
- isWorkflowReady(doctype, recordId) {
229
- // New records don't block workflows - they haven't been saved yet
230
- if (isDraftRecordId(recordId)) {
231
- return { ready: true };
232
- }
233
- const links = this.registry.getDescendantLinks(doctype.slug);
234
- const blockedLinks = [];
235
- for (const link of links) {
236
- if (this.getEffectiveBlockWorkflows(link)) {
237
- const linkPath = `${doctype.slug}.${recordId}.${link.fieldname}`;
238
- if (!this.hstStore.has(linkPath)) {
239
- blockedLinks.push(link.fieldname);
240
- }
241
- }
242
- }
243
- if (blockedLinks.length > 0) {
244
- return { ready: false, blockedLinks };
245
- }
246
- return { ready: true };
247
- }
248
- /**
249
- * Fetch a doctype's records from the server and store them in HST.
250
- *
251
- * This is the one read path for a list. Every caller shares its keying rule, so a row is
252
- * always stored under the identity its Edit link will later ask for.
253
- *
254
- * Deliberately unguarded, unlike {@link Stonecrop.getRecord}: a list is a view of data that
255
- * changes, so revisiting one must re-read it rather than serve whatever HST happens to hold.
256
- *
257
- * `options` is forwarded to the client untouched — no row limit is invented here, because
258
- * nothing on this side of the wire knows what is safe for an arbitrary backend. A caller that
259
- * passes none gets whatever the server considers a reasonable page.
260
- *
261
- * `options.offset === 0` (or omitted) replaces the doctype's HST records; `offset > 0` appends.
262
- *
263
- * @param doctype - The doctype
264
- * @param options - Query options (filters, orderBy, limit, offset), forwarded to the client
265
- * @throws Error if no data client has been configured
266
- * @public
267
- */
268
- async getRecords(doctype, options) {
269
- if (!this._client) {
270
- throw new Error('No data client configured. Call setClient() with a DataClient implementation ' +
271
- '(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.');
272
- }
273
- const result = await this._client.getRecords(doctype, options);
274
- const records = result.data;
275
- const offset = options?.offset ?? 0;
276
- // Page info is kept beside HST, not in it. `getRecordIds` reads the raw keys under a
277
- // doctype node, so anything filed there becomes a phantom record — the same hazard that
278
- // ruled out seeding a draft node.
279
- const pageEntry = {
280
- hasMore: result.hasMore,
281
- offset,
282
- limit: records.length,
283
- };
284
- if (result.count != null) {
285
- pageEntry.count = result.count;
286
- }
287
- this.pageInfo[doctype.slug] = pageEntry;
288
- // offset === 0 replaces the doctype's HST records; offset > 0 appends. A failed fetch
289
- // must not clear — that happens only after a successful response lands above.
290
- if (offset === 0) {
291
- this.clearRecords(doctype);
292
- }
293
- // Key each record by its declared primary key, falling back to `id`. This used to read
294
- // `record.id` only, which silently dropped every row of a natural-keyed doctype (no `id`
295
- // column at all) — the records never entered HST, so the list rendered empty and no
296
- // downstream id-resolution could recover them.
297
- records.forEach(record => {
298
- const recordId = doctype.getRecordId(record);
299
- if (recordId !== undefined) {
300
- this.addRecord(doctype, recordId, record);
301
- }
302
- });
303
- return result;
304
- }
305
- /**
306
- * What the last {@link Stonecrop.getRecords} for this doctype returned about the wider set.
307
- *
308
- * Answers the question HST cannot: HST holds what was fetched, so counting its keys reports
309
- * how much has been seen, never how much exists. Reactive, so a view reading it re-renders
310
- * when a fetch lands.
311
- *
312
- * @param doctype - The doctype slug string or Doctype object
313
- * @returns Page info, or undefined if this doctype's records have not been fetched
314
- * @public
315
- */
316
- getPageInfo(doctype) {
317
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
318
- return this.pageInfo[slug];
319
- }
320
- /**
321
- * Fetch a single record from the server and store it in HST.
322
- *
323
- * This is the one read path for a record, and it owns the whole job: deciding whether a fetch
324
- * is warranted, performing it, and writing the result back under the doctype's declared
325
- * identity. Callers ask for a record and get one; they do not re-derive when to ask.
326
- *
327
- * Two cases return without touching the network, because in both the answer is already known:
328
- * a draft does not exist on the server yet, and a record already in HST has been read.
329
- * Refetching the latter would also discard unsaved edits sitting in the store.
330
- *
331
- * @param doctype - The doctype slug string or Doctype object
332
- * @param recordId - The record ID
333
- * @param options - Query options (includeNested, maxDepth), forwarded to the client
334
- * @throws Error if no data client has been configured
335
- * @throws Error if a slug string is given and no matching doctype is found in the registry
336
- * @public
337
- */
338
- async getRecord(doctype, recordId, options) {
339
- if (!this._client) {
340
- throw new Error('No data client configured. Call setClient() with a DataClient implementation ' +
341
- '(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.');
342
- }
343
- const resolved = typeof doctype === 'string' ? this.registry.getDoctype(doctype) : doctype;
344
- if (!resolved) {
345
- throw new Error(`Doctype not found: ${typeof doctype === 'string' ? doctype : doctype.slug}`);
346
- }
347
- // An unsaved draft has no server record, so a fetch could only ever miss. This guard used
348
- // to live in every host, which is how the private draft-id scheme leaked into all of them.
349
- if (isDraftRecordId(recordId)) {
350
- return;
351
- }
352
- if (this.getRecordById(resolved.slug, recordId)) {
353
- return;
354
- }
355
- const result = await this._client.getRecord(resolved, recordId, options);
356
- if (result?.record) {
357
- this.addRecord(resolved, recordId, result.record);
358
- }
359
- }
360
- /**
361
- * Dispatch an action to the server via the configured data client, and file the record it
362
- * returns into HST under the identity the *server* settled on.
363
- *
364
- * The write is the point. For a created record the settled identity is never the one that was
365
- * dispatched, so a caller that stores the result under the id it sent files the record under a
366
- * key nothing can fetch and leaves the next save creating a second one. Every host that
367
- * hand-rolled this got it wrong the same way, so it stops being the caller's job — this is the
368
- * write-side twin of {@link Stonecrop.getRecords}, which keys reads by the same rule.
369
- *
370
- * Two things are deliberately NOT done here, because both need the id that was dispatched and
371
- * that lives inside `args` — an opaque array whose shape is a convention between a host's
372
- * client and its server handlers, not something this layer may parse. Dropping the stale key
373
- * and moving the route therefore stay with `useClientAction`, which knows both ids.
374
- *
375
- * A result that states no identity of its own — a `{ state: 'APPROVED' }` outcome — is left
376
- * alone rather than guessed at, for the same reason `settledRecordId` is strict: a partial
377
- * record must not be able to look like a rename.
378
- *
379
- * @param doctype - The doctype
380
- * @param action - Action name to execute (e.g., 'SUBMIT', 'APPROVE', 'save')
381
- * @param args - Action arguments (typically record ID and/or form data)
382
- * @returns Action result with success status, response data, and any error
383
- * @throws Error if no data client has been configured
384
- */
385
- async dispatchAction(doctype, action, args) {
386
- if (!this._client) {
387
- throw new Error('No data client configured. Call setClient() with a DataClient implementation ' +
388
- '(e.g., StonecropClient from @stonecrop/graphql-client) before dispatching actions.');
389
- }
390
- const result = await this._client.runAction(doctype, action, args);
391
- if (result.success && result.data && typeof result.data === 'object' && !Array.isArray(result.data)) {
392
- // 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
393
- const record = result.data;
394
- // Require the declared key to be *present* before trusting `getRecordId`, which falls
395
- // back to `id`. Without that, a handler returning `{ id, total }` for a natural-keyed
396
- // doctype would relocate the record to a key the adapter cannot look up.
397
- if (record[doctype.recordIdField] !== undefined) {
398
- const settledId = doctype.getRecordId(record);
399
- if (settledId !== undefined) {
400
- this.addRecord(doctype, settledId, record);
401
- }
402
- }
403
- }
404
- return result;
405
- }
406
- /**
407
- * Ensure doctype section exists in HST store
408
- * @param slug - The doctype slug
409
- */
410
- ensureDoctypeExists(slug) {
411
- if (!this.hstStore.has(slug)) {
412
- this.hstStore.set(slug, {});
413
- }
414
- }
415
- /**
416
- * Get doctype metadata from the registry
417
- * @param context - The route context
418
- * @returns The doctype metadata
419
- */
420
- async getMeta(context) {
421
- if (!this.registry.getMeta) {
422
- throw new Error('No getMeta function provided to Registry');
423
- }
424
- return await this.registry.getMeta(context);
425
- }
426
- /**
427
- * Get the root HST store node for advanced usage
428
- * @returns Root HST node
429
- */
430
- getStore() {
431
- return this.hstStore;
432
- }
433
- /**
434
- * Determine the current workflow state for a record.
435
- *
436
- * Reads the record's `status` field from the HST store. If the field is absent or
437
- * empty the doctype's declared `workflow.initial` state is used as the fallback,
438
- * giving callers a reliable state name without having to duplicate that logic.
439
- *
440
- * @param doctype - The doctype slug or Doctype instance
441
- * @param recordId - The record identifier
442
- * @returns The current state name, or an empty string if the doctype has no workflow
443
- *
444
- * @public
445
- */
446
- getRecordState(doctype, recordId) {
447
- const slug = typeof doctype === 'string' ? doctype : doctype.slug;
448
- const meta = this.registry.getDoctype(slug);
449
- if (!meta?.workflow)
450
- return '';
451
- const record = this.getRecordById(slug, recordId);
452
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- HSTNode.get returns any; status is always string in workflow records
453
- const status = record?.get('status');
454
- // Handle both XState format and WorkflowMeta format
455
- const workflow = meta.workflow;
456
- let initialState;
457
- if (Array.isArray(workflow.states)) {
458
- // WorkflowMeta format: states is a string array
459
- initialState = workflow.states[0] ?? '';
460
- }
461
- else {
462
- // XState format: states is an object, use initial or first key
463
- // oxlint-disable typescript/no-unsafe-type-assertion -- XState MachineConfig has `initial` but type union doesn't expose it; runtime-guarded by typeof check
464
- initialState =
465
- typeof workflow.initial === 'string'
466
- ? workflow.initial
467
- : (Object.keys(workflow.states ?? {})[0] ?? '');
468
- // oxlint-enable typescript/no-unsafe-type-assertion
469
- }
470
- return status || initialState;
471
- }
472
- /**
473
- * Collect a record payload with all nested doctype fields from HST
474
- * @param doctype - The doctype metadata
475
- * @param recordId - The record ID to collect
476
- * @returns The complete record payload ready for API submission
477
- * @public
478
- */
479
- collectRecordPayload(doctype, recordId) {
480
- const recordPath = `${doctype.slug}.${recordId}`;
481
- const recordData = this.hstStore.get(recordPath) || {};
482
- const payload = { ...recordData };
483
- // Collect nested data from links
484
- if (doctype.links) {
485
- for (const [fieldname, link] of Object.entries(doctype.links)) {
486
- const fieldPath = `${recordPath}.${fieldname}`;
487
- const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
488
- if (isMany) {
489
- const arrayData = this.hstStore.get(fieldPath);
490
- if (Array.isArray(arrayData)) {
491
- payload[fieldname] = arrayData;
492
- }
493
- }
494
- else {
495
- const targetDoctype = this.registry.getDoctype(link.target);
496
- if (targetDoctype?.links) {
497
- payload[fieldname] = this.collectNestedData(fieldPath, targetDoctype);
498
- }
499
- else {
500
- payload[fieldname] = this.hstStore.get(fieldPath) || {};
501
- }
502
- }
503
- }
504
- }
505
- // The store's shape, inline links included. Reducing them to what a column takes is the
506
- // adapter's job at dispatch — storage is behind the API.
507
- return payload;
508
- }
509
- /**
510
- * Scaffold empty descendant records from defaults for all descendant links.
511
- *
512
- * Initializes all scalar and link fields at their HST paths with default values.
513
- * For new records, call this after setting up the doctype to ensure all paths exist.
514
- *
515
- * @param path - HST path (e.g., "customer.new")
516
- * @param doctype - The doctype to initialize
517
- * @public
518
- */
519
- initializeNestedData(path, doctype) {
520
- const slug = doctype.slug;
521
- this.ensureDoctypeExists(slug);
522
- // Resolve schema and initialize with defaults
523
- const resolvedSchema = this.registry.resolveSchema(doctype);
524
- const record = this.registry.initializeRecord(resolvedSchema);
525
- // Ensure the ancestor path exists in HST before setting descendant fields
526
- const existingData = this.hstStore.get(path);
527
- if (!existingData) {
528
- this.hstStore.set(path, {}, 'system');
529
- }
530
- // Store each field at its own HST path
531
- for (const [key, value] of Object.entries(record)) {
532
- this.hstStore.set(`${path}.${key}`, value, 'system');
533
- }
534
- }
535
- /**
536
- * Fetch a record and its nested data from the server.
537
- *
538
- * Calls `_client.getRecord()` with nested sub-selections and stores each scalar field at its own HST path
539
- * (`slug.recordId.fieldname`), descendants at the link-level path (`slug.recordId.linkname`).
540
- *
541
- * @param path - HST path (e.g., "recipe.r1")
542
- * @param doctype - The doctype to fetch
543
- * @param recordId - Record ID to fetch
544
- * @param options - Query options (includeNested to control which links are fetched)
545
- * @throws Error with code `"CLIENT_REQUIRED"` if no data client is configured
546
- * @throws Error with code `"RECORD_NOT_FOUND"` if the server returns null
547
- * @public
548
- */
549
- async fetchNestedData(path, doctype, recordId, options) {
550
- if (!this._client) {
551
- throw createCodedError('No data client configured. Call setClient() with a DataClient implementation ' +
552
- '(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.', 'CLIENT_REQUIRED');
553
- }
554
- const result = await this._client.getRecord({ name: doctype.doctype }, recordId, {
555
- includeNested: options?.includeNested ?? true,
556
- });
557
- if (!result?.record) {
558
- throw createCodedError(`Record not found: ${doctype.doctype} ${recordId}`, 'RECORD_NOT_FOUND');
559
- }
560
- // Store each scalar field at its own HST path, descendants at link-level path
561
- const slug = doctype.slug;
562
- this.ensureDoctypeExists(slug);
563
- // Ensure the ancestor path exists in HST before setting descendant fields
564
- const existingData = this.hstStore.get(`${slug}.${recordId}`);
565
- if (!existingData) {
566
- this.hstStore.set(`${slug}.${recordId}`, {}, 'system');
567
- }
568
- for (const [key, value] of Object.entries(result.record)) {
569
- this.hstStore.set(`${slug}.${recordId}.${key}`, value, 'system');
570
- }
571
- }
572
- /**
573
- * Recursively collect nested data from HST
574
- * @param basePath - The base path in HST (e.g., "customer.123.address")
575
- * @param doctype - The doctype whose links drive the recursive traversal
576
- * @returns The collected data object
577
- */
578
- collectNestedData(basePath, doctype) {
579
- const data = this.hstStore.get(basePath) || {};
580
- const payload = { ...data };
581
- if (!doctype.links)
582
- return payload;
583
- for (const [fieldname, link] of Object.entries(doctype.links)) {
584
- const fieldPath = `${basePath}.${fieldname}`;
585
- const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
586
- if (isMany) {
587
- const arrayData = this.hstStore.get(fieldPath);
588
- if (Array.isArray(arrayData)) {
589
- payload[fieldname] = arrayData;
590
- }
591
- }
592
- else {
593
- const targetDoctype = this.registry.getDoctype(link.target);
594
- if (targetDoctype?.links) {
595
- payload[fieldname] = this.collectNestedData(fieldPath, targetDoctype);
596
- }
597
- else {
598
- payload[fieldname] = this.hstStore.get(fieldPath) || {};
599
- }
600
- }
601
- }
602
- return payload;
603
- }
604
- }
605
- function createCodedError(message, code) {
606
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- extending Error with code property; CodedError cast is the standard pattern for typed error objects
607
- const error = new Error(message);
608
- error.code = code;
609
- return error;
610
- }