@stonecrop/stonecrop 0.31.0 → 0.33.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,98 +0,0 @@
1
- import { nextTick } from 'vue';
2
- import Registry from '../registry';
3
- import { Stonecrop } from '../stonecrop';
4
- import { useOperationLogStore } from '../stores/operation-log';
5
- /**
6
- * Setup auto-initialization for user-defined initialization logic
7
- * This function handles the post-mount initialization automatically
8
- */
9
- async function setupAutoInitialization(registry, stonecrop, onRouterInitialized) {
10
- // Wait for the next tick to ensure the app is mounted
11
- await nextTick();
12
- try {
13
- await onRouterInitialized(registry, stonecrop);
14
- }
15
- catch {
16
- // Silent error handling - application should handle initialization errors
17
- }
18
- }
19
- /**
20
- * Stonecrop Vue plugin
21
- * @param app - The Vue app instance
22
- * @param options - The plugin options
23
- * @example
24
- * ```ts
25
- * import { createApp } from 'vue'
26
- * import Stonecrop from '@stonecrop/stonecrop'
27
- * import { StonecropClient } from '@stonecrop/graphql-client'
28
- * import router from './router'
29
- *
30
- * const client = new StonecropClient({ endpoint: '/graphql' })
31
- *
32
- * const app = createApp(App)
33
- * app.use(Stonecrop, {
34
- * router,
35
- * client,
36
- * getMeta: async (routeContext) => {
37
- * // routeContext contains: { path, segments }
38
- * // use the client to fetch doctype meta
39
- * return client.getMeta({ doctype: routeContext.segments[0] })
40
- * },
41
- * autoInitializeRouter: true,
42
- * onRouterInitialized: async (registry, stonecrop) => {
43
- * // your custom initialization logic here
44
- * }
45
- * })
46
- * app.mount('#app')
47
- * ```
48
- * @public
49
- */
50
- const plugin = {
51
- install: (app, options) => {
52
- // Check for existing router installation
53
- const existingRouter = app.config.globalProperties.$router;
54
- const providedRouter = options?.router;
55
- const router = existingRouter || providedRouter;
56
- if (!existingRouter && providedRouter) {
57
- app.use(providedRouter);
58
- }
59
- // Create registry with available router
60
- const registry = new Registry(router, options?.getMeta);
61
- app.provide('$registry', registry);
62
- app.config.globalProperties.$registry = registry;
63
- // Create and provide a global Stonecrop instance
64
- const stonecrop = new Stonecrop(registry);
65
- if (options?.client) {
66
- stonecrop.setClient(options.client);
67
- }
68
- app.provide('$stonecrop', stonecrop);
69
- app.config.globalProperties.$stonecrop = stonecrop;
70
- // Initialize operation log store if Pinia is available
71
- // This ensures the store is created with the app's Pinia instance
72
- try {
73
- const pinia = app.config.globalProperties.$pinia;
74
- if (pinia) {
75
- // Initialize the operation log store with the app's Pinia instance
76
- const operationLogStore = useOperationLogStore(pinia);
77
- // Provide the store so components can access it
78
- app.provide('$operationLogStore', operationLogStore);
79
- app.config.globalProperties.$operationLogStore = operationLogStore;
80
- }
81
- }
82
- catch (error) {
83
- // Pinia not available - operation log won't work, but app should still function
84
- console.warn('Pinia not available - operation log features will be disabled:', error);
85
- }
86
- // Register custom components
87
- if (options?.components) {
88
- for (const [tag, component] of Object.entries(options.components)) {
89
- app.component(tag, component);
90
- }
91
- }
92
- // Setup auto-initialization if requested
93
- if (options?.autoInitializeRouter && options.onRouterInitialized) {
94
- void setupAutoInitialization(registry, stonecrop, options.onRouterInitialized);
95
- }
96
- },
97
- };
98
- export default plugin;
@@ -1,161 +0,0 @@
1
- import type { ResolvedField } from '@stonecrop/aform';
2
- import type { LinkDeclaration } from '@stonecrop/schema';
3
- import { Router } from 'vue-router';
4
- import Doctype from './doctype';
5
- import { RouteContext } from './types/registry';
6
- /**
7
- * Stonecrop Registry class
8
- * @public
9
- */
10
- export default class Registry {
11
- /**
12
- * The root Registry instance
13
- */
14
- static _root: Registry;
15
- /**
16
- * The name of the Registry instance
17
- *
18
- * @defaultValue 'Registry'
19
- */
20
- readonly name: string;
21
- /**
22
- * The registry property contains a collection of doctypes
23
- *
24
- * @defaultValue `{}`
25
- * @see {@link Doctype}
26
- */
27
- readonly registry: Record<string, Doctype>;
28
- /**
29
- * Reverse index: backlink fieldname → list of \{ doctype slug, link fieldname \}.
30
- * Multiple doctypes can declare a link with the same backlink name, so each key
31
- * maps to an array. Built at schema load time for O(1) ancestor lookups.
32
- *
33
- * @defaultValue `new Map()`
34
- * @internal
35
- */
36
- private _ancestorIndex;
37
- /**
38
- * Whether the ancestor index needs rebuilding
39
- *
40
- * @defaultValue `true`
41
- * @internal
42
- */
43
- private _ancestorIndexDirty;
44
- /**
45
- * The Vue router instance
46
- * @see {@link https://router.vuejs.org/}
47
- */
48
- readonly router?: Router;
49
- /**
50
- * Creates a new Registry instance (singleton pattern)
51
- * @param router - Optional Vue router instance for route management
52
- * @param getMeta - Optional function to fetch doctype metadata from an API
53
- */
54
- constructor(router?: Router, getMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>);
55
- /**
56
- * The getMeta function fetches doctype metadata from an API based on route context
57
- * @see {@link Doctype}
58
- */
59
- getMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>;
60
- /**
61
- * Get doctype metadata
62
- * @param doctype - The doctype to fetch metadata for
63
- * @returns The doctype metadata
64
- * @see {@link Doctype}
65
- */
66
- addDoctype(doctype: Doctype): void;
67
- /**
68
- * Resolve a Doctype's authoring schema into a rendered schema array suitable for AForm.
69
- *
70
- * Transforms `DoctypeField[]` (authoring space) → `ResolvedField[]` (rendering space):
71
- * - `kind: 'field'` (not Link) → `ResolvedScalar`
72
- * - `kind: 'field'` (Link, no declaration) → `ResolvedScalar` with `component: 'AFormLink'`
73
- * - `kind: 'field'` (Link, `noneOrMany`/`atLeastOne`) → `ResolvedTable`
74
- * - `kind: 'field'` (Link, `one`/`atMostOne`) → `ResolvedLink`
75
- * - `kind: 'fieldset'` → `ResolvedFieldset` (children resolved recursively)
76
- * - `kind: 'table'` → `ResolvedTable` (columns as `ColumnSchema[]`)
77
- *
78
- * Circular references are protected against via the `visited` set.
79
- *
80
- * @param doctype - The doctype to resolve
81
- * @param visited - Internal — set of already-visited doctype slugs for cycle detection
82
- * @returns A resolved schema array ready for AForm
83
- *
84
- * @public
85
- */
86
- resolveSchema(doctype: Doctype, visited?: Set<string>): ResolvedField[];
87
- /**
88
- * Recursively resolve a `DoctypeField[]` using the provided link context.
89
- * Called by `resolveSchema` and recursively for fieldset children.
90
- * @internal
91
- */
92
- private resolveFields;
93
- /**
94
- * Build a `ResolvedTable` from a resolved Link field with many cardinality.
95
- * Columns come from {@link @stonecrop/aform#resolvedFieldsToColumns}, the shared definition of
96
- * which resolved fields a cell can render.
97
- * @internal
98
- */
99
- private buildTableConfig;
100
- /**
101
- * Initialize a new record with default values based on a resolved schema.
102
- * Narrows by `kind` discriminator for precise branch selection.
103
- *
104
- * - `kind: 'table'` or `kind: 'link'` → `[]` or `{}`
105
- * - `kind: 'fieldset'` → recursively initializes children as `{}`
106
- * - `kind: 'field'` → derives the default from the component's category; falls back to `null`
107
- *
108
- * @param schema - The resolved schema array to derive defaults from
109
- * @returns A plain object with default values for each field
110
- * @public
111
- */
112
- initializeRecord(schema: ResolvedField[]): Record<string, any>;
113
- /**
114
- * Get a registered doctype by slug
115
- * @param slug - The doctype slug to look up
116
- * @returns The Doctype instance if found, or undefined
117
- * @public
118
- */
119
- getDoctype(slug: string): Doctype | undefined;
120
- /**
121
- * Get all links declared on a doctype.
122
- *
123
- * @param doctypeSlug - The doctype slug to get links for
124
- * @returns Array of link declarations with fieldname, or empty array if none
125
- *
126
- * @example
127
- * ```ts
128
- * const links = registry.getDescendantLinks('recipe')
129
- * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe' }]
130
- * ```
131
- *
132
- * @public
133
- */
134
- getDescendantLinks(doctypeSlug: string): Array<LinkDeclaration & {
135
- fieldname: string;
136
- }>;
137
- /**
138
- * Get links on other doctypes that target the given doctype.
139
- *
140
- * @param doctypeSlug - The doctype slug to find ancestor links for
141
- * @returns Array of link declarations with fieldname and declaring doctype slug, or empty array
142
- *
143
- * @example
144
- * ```ts
145
- * const ancestors = registry.getAncestorLinks('recipe-task')
146
- * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe', doctype: 'recipe' }]
147
- * ```
148
- *
149
- * @public
150
- */
151
- getAncestorLinks(doctypeSlug: string): Array<LinkDeclaration & {
152
- fieldname: string;
153
- doctype: string;
154
- }>;
155
- /**
156
- * Ensure the ancestor index is up to date
157
- * @internal
158
- */
159
- private _ensureAncestorIndex;
160
- }
161
- //# sourceMappingURL=registry.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAiE,MAAM,kBAAkB,CAAA;AAEpH,OAAO,KAAK,EAAgB,eAAe,EAA+B,MAAM,mBAAmB,CAAA;AAEnG,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAEnC,OAAO,OAAO,MAAM,WAAW,CAAA;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAE/C;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,QAAQ;IAC5B;;OAEG;IACH,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAA;IAEtB;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAa;IAElC;;;;;OAKG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAK;IAE/C;;;;;;;OAOG;IACH,OAAO,CAAC,cAAc,CAAqE;IAE3F;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB,CAAgB;IAE3C;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IAExB;;;;OAIG;gBACS,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAUjG;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAEpE;;;;;OAKG;IACH,UAAU,CAAC,OAAO,EAAE,OAAO;IAsB3B;;;;;;;;;;;;;;;;;;OAkBG;IACH,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,aAAa,EAAE;IA4BvE;;;;OAIG;IACH,OAAO,CAAC,aAAa;IA2FrB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IAgBxB;;;;;;;;;;;OAWG;IACH,gBAAgB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IAuC9D;;;;;OAKG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAI7C;;;;;;;;;;;;;OAaG;IACH,kBAAkB,CAAC,WAAW,EAAE,MAAM,GAAG,KAAK,CAAC,eAAe,GAAG;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IAWvF;;;;;;;;;;;;;OAaG;IACH,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,KAAK,CAAC,eAAe,GAAG;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAwBtG;;;OAGG;IACH,OAAO,CAAC,oBAAoB;CAgC5B"}
@@ -1,384 +0,0 @@
1
- import { resolvedFieldsToColumns } from '@stonecrop/aform';
2
- import { componentCategory, componentLinkExpansion, resolveLinkRenderMode } from '@stonecrop/schema';
3
- /**
4
- * Stonecrop Registry class
5
- * @public
6
- */
7
- export default class Registry {
8
- /**
9
- * The root Registry instance
10
- */
11
- static _root;
12
- /**
13
- * The name of the Registry instance
14
- *
15
- * @defaultValue 'Registry'
16
- */
17
- name = 'Registry';
18
- /**
19
- * The registry property contains a collection of doctypes
20
- *
21
- * @defaultValue `{}`
22
- * @see {@link Doctype}
23
- */
24
- registry = {};
25
- /**
26
- * Reverse index: backlink fieldname → list of \{ doctype slug, link fieldname \}.
27
- * Multiple doctypes can declare a link with the same backlink name, so each key
28
- * maps to an array. Built at schema load time for O(1) ancestor lookups.
29
- *
30
- * @defaultValue `new Map()`
31
- * @internal
32
- */
33
- _ancestorIndex = new Map();
34
- /**
35
- * Whether the ancestor index needs rebuilding
36
- *
37
- * @defaultValue `true`
38
- * @internal
39
- */
40
- _ancestorIndexDirty = true;
41
- /**
42
- * The Vue router instance
43
- * @see {@link https://router.vuejs.org/}
44
- */
45
- router;
46
- /**
47
- * Creates a new Registry instance (singleton pattern)
48
- * @param router - Optional Vue router instance for route management
49
- * @param getMeta - Optional function to fetch doctype metadata from an API
50
- */
51
- constructor(router, getMeta) {
52
- if (Registry._root) {
53
- return Registry._root;
54
- }
55
- Registry._root = this;
56
- this.router = router;
57
- this.getMeta = getMeta;
58
- return this;
59
- }
60
- /**
61
- * The getMeta function fetches doctype metadata from an API based on route context
62
- * @see {@link Doctype}
63
- */
64
- getMeta;
65
- /**
66
- * Get doctype metadata
67
- * @param doctype - The doctype to fetch metadata for
68
- * @returns The doctype metadata
69
- * @see {@link Doctype}
70
- */
71
- addDoctype(doctype) {
72
- if (!(doctype.slug in this.registry)) {
73
- this.registry[doctype.slug] = doctype;
74
- this._ancestorIndexDirty = true;
75
- }
76
- // Field triggers are registered imperatively, by the app, via the FieldTriggerEngine's own
77
- // `registerDoctypeActions`. A doctype used to be able to declare them too, but that path
78
- // could not survive the wire — neither the Zod gate nor the SDL carries such a map — so it
79
- // only ever worked for a host bypassing both, and it left two public `runAction` methods
80
- // meaning opposite things. Registering here would also overwrite an app's imperative
81
- // registration, since `registerDoctypeActions` sets the maps even when handed nothing.
82
- if (doctype.component && this.router && !this.router.hasRoute(doctype.doctype)) {
83
- this.router.addRoute({
84
- path: `/${doctype.slug}`,
85
- name: doctype.slug,
86
- component: doctype.component,
87
- });
88
- }
89
- }
90
- /**
91
- * Resolve a Doctype's authoring schema into a rendered schema array suitable for AForm.
92
- *
93
- * Transforms `DoctypeField[]` (authoring space) → `ResolvedField[]` (rendering space):
94
- * - `kind: 'field'` (not Link) → `ResolvedScalar`
95
- * - `kind: 'field'` (Link, no declaration) → `ResolvedScalar` with `component: 'AFormLink'`
96
- * - `kind: 'field'` (Link, `noneOrMany`/`atLeastOne`) → `ResolvedTable`
97
- * - `kind: 'field'` (Link, `one`/`atMostOne`) → `ResolvedLink`
98
- * - `kind: 'fieldset'` → `ResolvedFieldset` (children resolved recursively)
99
- * - `kind: 'table'` → `ResolvedTable` (columns as `ColumnSchema[]`)
100
- *
101
- * Circular references are protected against via the `visited` set.
102
- *
103
- * @param doctype - The doctype to resolve
104
- * @param visited - Internal — set of already-visited doctype slugs for cycle detection
105
- * @returns A resolved schema array ready for AForm
106
- *
107
- * @public
108
- */
109
- resolveSchema(doctype, visited) {
110
- const seen = visited ?? new Set();
111
- const slug = doctype.slug;
112
- // Prevent circular resolution — return all ValueField entries as scalars (link not expanded)
113
- if (seen.has(slug)) {
114
- const fallback = doctype.schema ? doctype.schema.toArray() : [];
115
- return fallback
116
- .filter((f) => f.kind === 'field')
117
- .map(({ cardinality: _c, ...rest }) => rest);
118
- }
119
- seen.add(slug);
120
- const schemaArray = doctype.schema ? doctype.schema.toArray() : [];
121
- // Map link declarations by fieldname (link.fieldname ?? key)
122
- const linksByFieldname = new Map();
123
- if (doctype.links) {
124
- for (const [key, link] of Object.entries(doctype.links)) {
125
- linksByFieldname.set(link.fieldname ?? key, link);
126
- }
127
- }
128
- const result = this.resolveFields(schemaArray, linksByFieldname, seen);
129
- seen.delete(slug);
130
- return result;
131
- }
132
- /**
133
- * Recursively resolve a `DoctypeField[]` using the provided link context.
134
- * Called by `resolveSchema` and recursively for fieldset children.
135
- * @internal
136
- */
137
- resolveFields(fields, links, visited) {
138
- const resolved = [];
139
- for (const field of fields) {
140
- // A field is a link when it carries `doctype` (the marker) or has a LinkDeclaration.
141
- const linkDecl = field.kind === 'field' ? links.get(field.fieldname) : undefined;
142
- if (field.kind === 'field' && (linkDecl || field.doctype)) {
143
- const link = linkDecl;
144
- // The declaration's target wins over the field's own `doctype`.
145
- const linkTarget = link?.target ?? field.doctype;
146
- // An undeclared link, or a declared one whose component renders an inline picker,
147
- // stays a scalar: the target is not expanded, it only needs the slug for async
148
- // display-text resolution and navigation.
149
- if (!link || resolveLinkRenderMode(link, field.component) === 'inline') {
150
- const { cardinality: _c, ...rest } = field;
151
- resolved.push({
152
- ...rest,
153
- component: rest.component || 'AFormLink',
154
- ...(linkTarget !== undefined ? { doctype: linkTarget } : {}),
155
- });
156
- continue;
157
- }
158
- const targetDoctype = this.registry[link.target];
159
- if (!targetDoctype) {
160
- // Target not registered — copy as scalar
161
- const { cardinality: _c, ...rest } = field;
162
- resolved.push({ ...rest });
163
- continue;
164
- }
165
- const childSchema = this.resolveSchema(targetDoctype, new Set(visited));
166
- const { options: _opt, cardinality: _card, kind: _kind, ...fieldRest } = field;
167
- if (resolveLinkRenderMode(link, field.component) === 'table') {
168
- resolved.push(this.buildTableConfig(field, childSchema, link.component));
169
- }
170
- else {
171
- const linkEntry = {
172
- ...fieldRest,
173
- kind: 'link',
174
- label: fieldRest.label || field.fieldname,
175
- component: link.component || fieldRest.component || 'AForm',
176
- schema: childSchema,
177
- };
178
- resolved.push(linkEntry);
179
- }
180
- }
181
- else if (field.kind === 'fieldset') {
182
- const resolvedChildren = this.resolveFields(field.schema, links, visited);
183
- const { schema: _s, ...fieldRest } = field;
184
- const fieldsetEntry = {
185
- ...fieldRest,
186
- schema: resolvedChildren,
187
- };
188
- resolved.push(fieldsetEntry);
189
- }
190
- else if (field.kind === 'table') {
191
- // Inline table — columns become ColumnSchema[], add default config
192
- const { columns, config, ...fieldRest } = field;
193
- const tableEntry = {
194
- ...fieldRest,
195
- kind: 'table',
196
- component: fieldRest.component || 'ATable',
197
- schema: columns,
198
- config: config ?? { view: 'list' },
199
- };
200
- resolved.push(tableEntry);
201
- }
202
- else {
203
- // Scalar field (kind: 'field', not a link) — strip cardinality.
204
- // A link-rendering component with nothing to point at renders an empty picker (or an
205
- // empty embedded form), which is indistinguishable from "the record has no value".
206
- // Link-ness comes from `doctype`/`links`, so this is a field that named a link
207
- // component and forgot the target.
208
- if (field.kind === 'field' && componentLinkExpansion(field.component)) {
209
- console.warn(`[Stonecrop] Field "${field.fieldname}" renders with "${field.component}", which is a link component, ` +
210
- `but the field is not a link: it has no \`doctype\` and no \`links\` declaration. It will render ` +
211
- `as a plain field. Add \`"doctype": "<doctype-slug>"\` to the field definition.`);
212
- }
213
- const { cardinality: _c, ...rest } = field;
214
- resolved.push({ ...rest });
215
- }
216
- }
217
- return resolved;
218
- }
219
- /**
220
- * Build a `ResolvedTable` from a resolved Link field with many cardinality.
221
- * Columns come from {@link @stonecrop/aform#resolvedFieldsToColumns}, the shared definition of
222
- * which resolved fields a cell can render.
223
- * @internal
224
- */
225
- buildTableConfig(field, childSchema, component) {
226
- const columns = resolvedFieldsToColumns(childSchema);
227
- const config = field.config ?? { view: 'list' };
228
- const { options: _opt, cardinality: _card, ...fieldRest } = field;
229
- return {
230
- ...fieldRest,
231
- kind: 'table',
232
- label: fieldRest.label || field.fieldname,
233
- component: component || fieldRest.component || 'ATable',
234
- schema: columns,
235
- config,
236
- };
237
- }
238
- /**
239
- * Initialize a new record with default values based on a resolved schema.
240
- * Narrows by `kind` discriminator for precise branch selection.
241
- *
242
- * - `kind: 'table'` or `kind: 'link'` → `[]` or `{}`
243
- * - `kind: 'fieldset'` → recursively initializes children as `{}`
244
- * - `kind: 'field'` → derives the default from the component's category; falls back to `null`
245
- *
246
- * @param schema - The resolved schema array to derive defaults from
247
- * @returns A plain object with default values for each field
248
- * @public
249
- */
250
- initializeRecord(schema) {
251
- const record = {};
252
- for (const field of schema) {
253
- if (field.kind === 'table') {
254
- record[field.fieldname] = [];
255
- }
256
- else if (field.kind === 'link') {
257
- record[field.fieldname] = this.initializeRecord(field.schema);
258
- }
259
- else if (field.kind === 'fieldset') {
260
- record[field.fieldname] = this.initializeRecord(field.schema);
261
- }
262
- else {
263
- // kind: 'field' — the empty default comes from the component's category.
264
- const fieldDefault = field.default;
265
- if (fieldDefault !== undefined) {
266
- record[field.fieldname] = fieldDefault;
267
- }
268
- else {
269
- const category = componentCategory(field.component);
270
- if (category === 'text') {
271
- record[field.fieldname] = '';
272
- }
273
- else if (category === 'number') {
274
- record[field.fieldname] = 0;
275
- }
276
- else if (category === 'boolean') {
277
- record[field.fieldname] = false;
278
- }
279
- else if (category === 'code' && field.language) {
280
- // A JSON editor starts from an empty object; any other language from empty source.
281
- record[field.fieldname] = field.language === 'json' ? {} : '';
282
- }
283
- else {
284
- // date / datetime / select / link / attach — plus two cases with no better answer
285
- // than "no value": an unknown (custom) component, and a code field whose missing
286
- // `language` doesn't say which kind of empty it wants.
287
- record[field.fieldname] = null;
288
- }
289
- }
290
- }
291
- }
292
- return record;
293
- }
294
- /**
295
- * Get a registered doctype by slug
296
- * @param slug - The doctype slug to look up
297
- * @returns The Doctype instance if found, or undefined
298
- * @public
299
- */
300
- getDoctype(slug) {
301
- return this.registry[slug];
302
- }
303
- /**
304
- * Get all links declared on a doctype.
305
- *
306
- * @param doctypeSlug - The doctype slug to get links for
307
- * @returns Array of link declarations with fieldname, or empty array if none
308
- *
309
- * @example
310
- * ```ts
311
- * const links = registry.getDescendantLinks('recipe')
312
- * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe' }]
313
- * ```
314
- *
315
- * @public
316
- */
317
- getDescendantLinks(doctypeSlug) {
318
- const doctype = this.registry[doctypeSlug];
319
- if (!doctype?.links)
320
- return [];
321
- return Object.entries(doctype.links).map(([fieldname, link]) => Object.assign({}, link, {
322
- fieldname,
323
- }));
324
- }
325
- /**
326
- * Get links on other doctypes that target the given doctype.
327
- *
328
- * @param doctypeSlug - The doctype slug to find ancestor links for
329
- * @returns Array of link declarations with fieldname and declaring doctype slug, or empty array
330
- *
331
- * @example
332
- * ```ts
333
- * const ancestors = registry.getAncestorLinks('recipe-task')
334
- * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe', doctype: 'recipe' }]
335
- * ```
336
- *
337
- * @public
338
- */
339
- getAncestorLinks(doctypeSlug) {
340
- this._ensureAncestorIndex();
341
- const results = [];
342
- for (const [_backlink, entries] of this._ancestorIndex) {
343
- for (const { slug: declaringSlug, fieldname } of entries) {
344
- const declaringDoctype = this.registry[declaringSlug];
345
- if (!declaringDoctype?.links)
346
- continue;
347
- const link = declaringDoctype.links[fieldname];
348
- if (link?.target === doctypeSlug) {
349
- results.push({
350
- ...link,
351
- fieldname,
352
- doctype: declaringSlug,
353
- });
354
- }
355
- }
356
- }
357
- return results;
358
- }
359
- /**
360
- * Ensure the ancestor index is up to date
361
- * @internal
362
- */
363
- _ensureAncestorIndex() {
364
- if (!this._ancestorIndexDirty)
365
- return;
366
- this._ancestorIndexDirty = false;
367
- this._ancestorIndex.clear();
368
- for (const [slug, doctype] of Object.entries(this.registry)) {
369
- if (!doctype.links)
370
- continue;
371
- for (const [fieldname, link] of Object.entries(doctype.links)) {
372
- if (link.backlink) {
373
- const existing = this._ancestorIndex.get(link.backlink);
374
- if (existing) {
375
- existing.push({ slug, fieldname });
376
- }
377
- else {
378
- this._ancestorIndex.set(link.backlink, [{ slug, fieldname }]);
379
- }
380
- }
381
- }
382
- }
383
- }
384
- }