@nixxie-cms/core 1.0.3 → 2.0.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 (203) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/CHANGES-1.1.md +134 -0
  3. package/context/dist/nixxie-cms-core-context.cjs.js +4 -3
  4. package/context/dist/nixxie-cms-core-context.esm.js +3 -2
  5. package/dist/declarations/src/access.d.ts +2 -2
  6. package/dist/declarations/src/access.d.ts.map +1 -1
  7. package/dist/declarations/src/admin-ui/components/Navigation.d.ts +2 -2
  8. package/dist/declarations/src/admin-ui/components/Navigation.d.ts.map +1 -1
  9. package/dist/declarations/src/admin-ui/context.d.ts +6 -6
  10. package/dist/declarations/src/admin-ui/context.d.ts.map +1 -1
  11. package/dist/declarations/src/admin-ui/utils/Fields.d.ts +3 -3
  12. package/dist/declarations/src/admin-ui/utils/Fields.d.ts.map +1 -1
  13. package/dist/declarations/src/admin-ui/utils/filters.d.ts +5 -5
  14. package/dist/declarations/src/admin-ui/utils/filters.d.ts.map +1 -1
  15. package/dist/declarations/src/admin-ui/utils/useCreateItem.d.ts +3 -3
  16. package/dist/declarations/src/admin-ui/utils/useCreateItem.d.ts.map +1 -1
  17. package/dist/declarations/src/admin-ui/utils/utils.d.ts +2 -2
  18. package/dist/declarations/src/admin-ui/utils/utils.d.ts.map +1 -1
  19. package/dist/declarations/src/context.d.ts +1 -1
  20. package/dist/declarations/src/context.d.ts.map +1 -1
  21. package/dist/declarations/src/fields/types/bigInt/index.d.ts +3 -3
  22. package/dist/declarations/src/fields/types/bigInt/index.d.ts.map +1 -1
  23. package/dist/declarations/src/fields/types/bytes/index.d.ts +3 -3
  24. package/dist/declarations/src/fields/types/bytes/index.d.ts.map +1 -1
  25. package/dist/declarations/src/fields/types/calendarDay/index.d.ts +3 -3
  26. package/dist/declarations/src/fields/types/calendarDay/index.d.ts.map +1 -1
  27. package/dist/declarations/src/fields/types/checkbox/index.d.ts +3 -3
  28. package/dist/declarations/src/fields/types/checkbox/index.d.ts.map +1 -1
  29. package/dist/declarations/src/fields/types/decimal/index.d.ts +3 -3
  30. package/dist/declarations/src/fields/types/decimal/index.d.ts.map +1 -1
  31. package/dist/declarations/src/fields/types/file/index.d.ts +4 -4
  32. package/dist/declarations/src/fields/types/file/index.d.ts.map +1 -1
  33. package/dist/declarations/src/fields/types/float/index.d.ts +3 -3
  34. package/dist/declarations/src/fields/types/float/index.d.ts.map +1 -1
  35. package/dist/declarations/src/fields/types/image/index.d.ts +4 -4
  36. package/dist/declarations/src/fields/types/image/index.d.ts.map +1 -1
  37. package/dist/declarations/src/fields/types/integer/index.d.ts +3 -3
  38. package/dist/declarations/src/fields/types/integer/index.d.ts.map +1 -1
  39. package/dist/declarations/src/fields/types/json/index.d.ts +3 -3
  40. package/dist/declarations/src/fields/types/json/index.d.ts.map +1 -1
  41. package/dist/declarations/src/fields/types/multiselect/index.d.ts +3 -3
  42. package/dist/declarations/src/fields/types/multiselect/index.d.ts.map +1 -1
  43. package/dist/declarations/src/fields/types/multiselect/views/index.d.ts.map +1 -1
  44. package/dist/declarations/src/fields/types/password/index.d.ts +3 -3
  45. package/dist/declarations/src/fields/types/password/index.d.ts.map +1 -1
  46. package/dist/declarations/src/fields/types/relationship/index.d.ts +8 -8
  47. package/dist/declarations/src/fields/types/relationship/index.d.ts.map +1 -1
  48. package/dist/declarations/src/fields/types/relationship/views/ComboboxMany.d.ts +3 -3
  49. package/dist/declarations/src/fields/types/relationship/views/ComboboxMany.d.ts.map +1 -1
  50. package/dist/declarations/src/fields/types/relationship/views/ComboboxSingle.d.ts +3 -3
  51. package/dist/declarations/src/fields/types/relationship/views/ComboboxSingle.d.ts.map +1 -1
  52. package/dist/declarations/src/fields/types/relationship/views/index.d.ts +3 -3
  53. package/dist/declarations/src/fields/types/relationship/views/index.d.ts.map +1 -1
  54. package/dist/declarations/src/fields/types/relationship/views/types.d.ts +3 -3
  55. package/dist/declarations/src/fields/types/relationship/views/types.d.ts.map +1 -1
  56. package/dist/declarations/src/fields/types/select/index.d.ts +3 -3
  57. package/dist/declarations/src/fields/types/select/index.d.ts.map +1 -1
  58. package/dist/declarations/src/fields/types/text/index.d.ts +3 -3
  59. package/dist/declarations/src/fields/types/text/index.d.ts.map +1 -1
  60. package/dist/declarations/src/fields/types/timestamp/index.d.ts +3 -3
  61. package/dist/declarations/src/fields/types/timestamp/index.d.ts.map +1 -1
  62. package/dist/declarations/src/fields/types/virtual/index.d.ts +7 -7
  63. package/dist/declarations/src/fields/types/virtual/index.d.ts.map +1 -1
  64. package/dist/declarations/src/helpers.d.ts +249 -13
  65. package/dist/declarations/src/helpers.d.ts.map +1 -1
  66. package/dist/declarations/src/index.d.ts +9 -4
  67. package/dist/declarations/src/index.d.ts.map +1 -1
  68. package/dist/declarations/src/internal-unstable/admin-ui/pages/ListPage/index.d.ts.map +1 -1
  69. package/dist/declarations/src/lib/admin-meta.d.ts +11 -11
  70. package/dist/declarations/src/lib/admin-meta.d.ts.map +1 -1
  71. package/dist/declarations/src/lib/core/access-control.d.ts +18 -18
  72. package/dist/declarations/src/lib/core/access-control.d.ts.map +1 -1
  73. package/dist/declarations/src/lib/core/cascade.d.ts +47 -0
  74. package/dist/declarations/src/lib/core/cascade.d.ts.map +1 -0
  75. package/dist/declarations/src/lib/core/initialise-lists.d.ts +27 -24
  76. package/dist/declarations/src/lib/core/initialise-lists.d.ts.map +1 -1
  77. package/dist/declarations/src/lib/env.d.ts +9 -0
  78. package/dist/declarations/src/lib/env.d.ts.map +1 -0
  79. package/dist/declarations/src/lib/system.d.ts +1 -1
  80. package/dist/declarations/src/lib/system.d.ts.map +1 -1
  81. package/dist/declarations/src/list-features.d.ts +162 -0
  82. package/dist/declarations/src/list-features.d.ts.map +1 -0
  83. package/dist/declarations/src/schema.d.ts +24 -23
  84. package/dist/declarations/src/schema.d.ts.map +1 -1
  85. package/dist/declarations/src/session.d.ts +75 -0
  86. package/dist/declarations/src/session.d.ts.map +1 -1
  87. package/dist/declarations/src/types/admin-meta.d.ts +11 -11
  88. package/dist/declarations/src/types/admin-meta.d.ts.map +1 -1
  89. package/dist/declarations/src/types/config/access-control.d.ts +42 -42
  90. package/dist/declarations/src/types/config/access-control.d.ts.map +1 -1
  91. package/dist/declarations/src/types/config/fields.d.ts +19 -19
  92. package/dist/declarations/src/types/config/fields.d.ts.map +1 -1
  93. package/dist/declarations/src/types/config/hooks.d.ts +131 -131
  94. package/dist/declarations/src/types/config/hooks.d.ts.map +1 -1
  95. package/dist/declarations/src/types/config/index.d.ts +190 -8
  96. package/dist/declarations/src/types/config/index.d.ts.map +1 -1
  97. package/dist/declarations/src/types/config/lists.d.ts +146 -108
  98. package/dist/declarations/src/types/config/lists.d.ts.map +1 -1
  99. package/dist/declarations/src/types/context.d.ts +507 -47
  100. package/dist/declarations/src/types/context.d.ts.map +1 -1
  101. package/dist/declarations/src/types/next-fields.d.ts +28 -28
  102. package/dist/declarations/src/types/next-fields.d.ts.map +1 -1
  103. package/dist/declarations/src/types/type-info.d.ts +3 -3
  104. package/dist/declarations/src/types/type-info.d.ts.map +1 -1
  105. package/dist/{express-455ae20c.cjs.js → express-84d534c2.cjs.js} +6 -6
  106. package/dist/{express-7559ca2d.esm.js → express-d0a4ce99.esm.js} +6 -6
  107. package/dist/{index-15c8f81e.esm.js → index-5d8b0b4e.esm.js} +363 -183
  108. package/dist/index-6055753b.cjs.js +393 -0
  109. package/dist/{index-42045902.cjs.js → index-ac29f382.cjs.js} +363 -185
  110. package/dist/index-f1703b7b.esm.js +386 -0
  111. package/dist/nixxie-cms-core.cjs.js +1388 -30
  112. package/dist/nixxie-cms-core.esm.js +1362 -24
  113. package/dist/{non-null-graphql-add6bb3d.cjs.js → non-null-graphql-4a44c122.cjs.js} +1 -1
  114. package/dist/{non-null-graphql-a84ed64d.esm.js → non-null-graphql-8c5feaae.esm.js} +1 -1
  115. package/dist/{resolve-hooks-165a9ce2.cjs.js → resolve-hooks-10a5f84c.cjs.js} +240 -6
  116. package/dist/{resolve-hooks-6813a045.esm.js → resolve-hooks-9e676794.esm.js} +238 -7
  117. package/dist/{system-a321642d.cjs.js → system-6b37a5f8.cjs.js} +33 -7
  118. package/dist/{system-03e49e4f.esm.js → system-e591d821.esm.js} +33 -7
  119. package/fields/dist/nixxie-cms-core-fields.cjs.js +29 -576
  120. package/fields/dist/nixxie-cms-core-fields.esm.js +18 -565
  121. package/fields/types/bytes/dist/nixxie-cms-core-fields-types-bytes.cjs.js +4 -2
  122. package/fields/types/bytes/dist/nixxie-cms-core-fields-types-bytes.esm.js +4 -2
  123. package/fields/types/multiselect/views/dist/nixxie-cms-core-fields-types-multiselect-views.cjs.js +1 -6
  124. package/fields/types/multiselect/views/dist/nixxie-cms-core-fields-types-multiselect-views.esm.js +1 -6
  125. package/fields/types/password/dist/nixxie-cms-core-fields-types-password.cjs.js +4 -2
  126. package/fields/types/password/dist/nixxie-cms-core-fields-types-password.esm.js +4 -2
  127. package/internal-unstable/artifacts/dist/nixxie-cms-core-internal-unstable-artifacts.cjs.js +4 -3
  128. package/internal-unstable/artifacts/dist/nixxie-cms-core-internal-unstable-artifacts.esm.js +4 -3
  129. package/package.json +4 -4
  130. package/scripts/cli/dist/nixxie-cms-core-scripts-cli.cjs.js +4 -3
  131. package/scripts/cli/dist/nixxie-cms-core-scripts-cli.esm.js +4 -3
  132. package/scripts/dist/nixxie-cms-core-scripts.cjs.js +4 -3
  133. package/scripts/dist/nixxie-cms-core-scripts.esm.js +4 -3
  134. package/session/dist/nixxie-cms-core-session.cjs.js +286 -0
  135. package/session/dist/nixxie-cms-core-session.esm.js +279 -1
  136. package/src/access.ts +25 -25
  137. package/src/admin-ui/admin-meta-graphql.ts +5 -5
  138. package/src/admin-ui/components/CreateButtonLink.tsx +46 -46
  139. package/src/admin-ui/components/Navigation.tsx +3 -3
  140. package/src/admin-ui/context.tsx +6 -6
  141. package/src/admin-ui/utils/Fields.tsx +241 -241
  142. package/src/admin-ui/utils/actionData.ts +36 -36
  143. package/src/admin-ui/utils/filters.ts +148 -148
  144. package/src/admin-ui/utils/useCreateItem.ts +171 -171
  145. package/src/admin-ui/utils/utils.tsx +127 -127
  146. package/src/context.ts +1 -1
  147. package/src/fields/non-null-graphql.ts +115 -115
  148. package/src/fields/types/bigInt/index.ts +6 -6
  149. package/src/fields/types/bytes/index.ts +6 -6
  150. package/src/fields/types/calendarDay/index.ts +18 -19
  151. package/src/fields/types/checkbox/index.ts +6 -6
  152. package/src/fields/types/decimal/index.ts +6 -6
  153. package/src/fields/types/file/index.ts +8 -8
  154. package/src/fields/types/float/index.ts +6 -6
  155. package/src/fields/types/image/index.ts +8 -8
  156. package/src/fields/types/integer/index.ts +6 -6
  157. package/src/fields/types/json/index.ts +5 -5
  158. package/src/fields/types/multiselect/index.ts +7 -7
  159. package/src/fields/types/multiselect/views/index.tsx +149 -151
  160. package/src/fields/types/password/index.ts +6 -6
  161. package/src/fields/types/relationship/index.ts +13 -13
  162. package/src/fields/types/relationship/views/ComboboxMany.tsx +110 -110
  163. package/src/fields/types/relationship/views/ComboboxSingle.tsx +115 -115
  164. package/src/fields/types/relationship/views/ContextualActions.tsx +139 -139
  165. package/src/fields/types/relationship/views/index.tsx +492 -492
  166. package/src/fields/types/relationship/views/types.ts +46 -46
  167. package/src/fields/types/relationship/views/useApolloQuery.ts +185 -185
  168. package/src/fields/types/relationship/views/useFilter.tsx +109 -109
  169. package/src/fields/types/select/index.ts +6 -6
  170. package/src/fields/types/text/index.ts +6 -6
  171. package/src/fields/types/timestamp/index.ts +23 -21
  172. package/src/fields/types/virtual/index.ts +11 -11
  173. package/src/helpers.ts +773 -42
  174. package/src/index.ts +66 -24
  175. package/src/internal-unstable/admin-ui/pages/ItemPage/common.tsx +4 -4
  176. package/src/internal-unstable/admin-ui/pages/ItemPage/index.tsx +5 -5
  177. package/src/internal-unstable/admin-ui/pages/ListPage/index.tsx +8 -8
  178. package/src/lib/admin-meta.ts +369 -369
  179. package/src/lib/context/createContext.ts +6 -0
  180. package/src/lib/core/access-control.ts +434 -434
  181. package/src/lib/core/cascade.ts +236 -0
  182. package/src/lib/core/initialise-lists.ts +49 -33
  183. package/src/lib/core/mutations/index.ts +7 -0
  184. package/src/lib/core/mutations/nested-mutation-many-input-resolvers.ts +145 -145
  185. package/src/lib/core/mutations/nested-mutation-one-input-resolvers.ts +71 -71
  186. package/src/lib/core/queries/output-field.ts +178 -178
  187. package/src/lib/env.ts +50 -0
  188. package/src/lib/id-field.ts +2 -2
  189. package/src/lib/system.ts +221 -207
  190. package/src/lib/typescript-schema-printer.ts +227 -227
  191. package/src/list-features.ts +476 -0
  192. package/src/schema.ts +92 -22
  193. package/src/session.ts +225 -0
  194. package/src/types/admin-meta.ts +218 -218
  195. package/src/types/config/access-control.ts +186 -186
  196. package/src/types/config/fields.ts +96 -96
  197. package/src/types/config/hooks.ts +529 -529
  198. package/src/types/config/index.ts +206 -7
  199. package/src/types/config/lists.ts +606 -565
  200. package/src/types/context.ts +592 -55
  201. package/src/types/next-fields.ts +31 -31
  202. package/src/types/type-info.ts +38 -38
  203. package/src/types/type-tests.ts +21 -21
@@ -2,22 +2,114 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var resolveHooks = require('./resolve-hooks-165a9ce2.cjs.js');
6
- var index = require('./index-42045902.cjs.js');
5
+ var resolveHooks = require('./resolve-hooks-10a5f84c.cjs.js');
6
+ var node_crypto = require('node:crypto');
7
+ var index = require('./index-6055753b.cjs.js');
8
+ var index$1 = require('./index-ac29f382.cjs.js');
7
9
  var nextFields = require('./next-fields-49c025ef.cjs.js');
8
10
  require('pluralize');
9
11
  require('@graphql-ts/schema');
10
12
  require('@graphql-ts/extend');
11
13
  require('graphql');
12
- require('./non-null-graphql-add6bb3d.cjs.js');
14
+ require('node:async_hooks');
15
+ require('./non-null-graphql-4a44c122.cjs.js');
13
16
  require('node:path');
14
17
  require('./admin-meta-18d0c276.cjs.js');
18
+ require('./utils-1b632a8f.cjs.js');
15
19
  require('decimal.js');
16
20
  require('graphql-upload/GraphQLUpload.js');
17
21
 
22
+ function normalise(spec) {
23
+ if (Array.isArray(spec)) {
24
+ return Object.fromEntries(spec.map(name => [name, {}]));
25
+ }
26
+ return spec;
27
+ }
28
+
29
+ /**
30
+ * Validate `env` (default `process.env`) against a spec. Applies `default`s to the env
31
+ * object for unset variables, then throws one aggregated error listing every missing or
32
+ * malformed variable. Called automatically when the config declares `env`, and exported
33
+ * for standalone use.
34
+ */
35
+ function validateEnv(spec, env = process.env) {
36
+ const problems = [];
37
+ for (const [name, requirement] of Object.entries(normalise(spec))) {
38
+ let value = env[name];
39
+ if ((value === undefined || value === '') && requirement.default !== undefined) {
40
+ env[name] = requirement.default;
41
+ value = requirement.default;
42
+ }
43
+ const describe = requirement.description ? ` — ${requirement.description}` : '';
44
+ if (value === undefined || value === '') {
45
+ if (requirement.required !== false) {
46
+ problems.push(` • ${name} is not set${describe}`);
47
+ }
48
+ continue;
49
+ }
50
+ if (requirement.pattern && !requirement.pattern.test(value)) {
51
+ problems.push(` • ${name} does not match ${requirement.pattern}${describe}`);
52
+ }
53
+ }
54
+ if (problems.length) {
55
+ throw new Error(`Environment validation failed (${problems.length} problem${problems.length === 1 ? '' : 's'}):\n` + problems.join('\n'));
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Fold `config.plugins` into the config: merge plugin collections (key conflicts throw),
61
+ * run each plugin's `extendConfig`, and chain plugin `onConnect`s before `db.onConnect`.
62
+ */
63
+ function applyPlugins(config) {
64
+ var _config$plugins;
65
+ const plugins = (_config$plugins = config.plugins) !== null && _config$plugins !== void 0 ? _config$plugins : [];
66
+ if (!plugins.length) return config;
67
+ const seen = new Set();
68
+ for (const plugin of plugins) {
69
+ if (!plugin.name) throw new Error('Every plugin must have a `name`');
70
+ if (seen.has(plugin.name)) throw new Error(`Duplicate plugin name "${plugin.name}"`);
71
+ seen.add(plugin.name);
72
+ }
73
+ let next = {
74
+ ...config,
75
+ collections: {
76
+ ...config.collections
77
+ }
78
+ };
79
+ for (const plugin of plugins) {
80
+ for (const [key, collection] of Object.entries((_plugin$collections = plugin.collections) !== null && _plugin$collections !== void 0 ? _plugin$collections : {})) {
81
+ var _plugin$collections;
82
+ if (key in next.collections) {
83
+ throw new Error(`Plugin "${plugin.name}" adds the collection "${key}", but a collection with that key already exists`);
84
+ }
85
+ next.collections[key] = collection;
86
+ }
87
+ if (plugin.extendConfig) {
88
+ next = plugin.extendConfig(next);
89
+ if (!next) {
90
+ throw new Error(`Plugin "${plugin.name}".extendConfig must return the config`);
91
+ }
92
+ }
93
+ }
94
+ const onConnects = plugins.flatMap(plugin => plugin.onConnect ? [plugin.onConnect] : []);
95
+ if (onConnects.length) {
96
+ const userOnConnect = next.db.onConnect;
97
+ next = {
98
+ ...next,
99
+ db: {
100
+ ...next.db,
101
+ onConnect: async context => {
102
+ for (const fn of onConnects) await fn(context);
103
+ await (userOnConnect === null || userOnConnect === void 0 ? void 0 : userOnConnect(context));
104
+ }
105
+ }
106
+ };
107
+ }
108
+ return next;
109
+ }
18
110
  function listsWithDefaults(config, defaultIdField) {
19
111
  // some error checking
20
- for (const [listKey, list] of Object.entries(config.lists)) {
112
+ for (const [listKey, list] of Object.entries(config.collections)) {
21
113
  var _list$db;
22
114
  if (list.fields.id) {
23
115
  throw new Error(`"fields.id" is reserved by Nixxie, use "db.idField" for the "${listKey}" list`);
@@ -27,7 +119,7 @@ function listsWithDefaults(config, defaultIdField) {
27
119
  }
28
120
  }
29
121
  return Object.fromEntries([...function* () {
30
- for (const [listKey, list] of Object.entries(config.lists)) {
122
+ for (const [listKey, list] of Object.entries(config.collections)) {
31
123
  var _list$db$idField, _list$db2;
32
124
  yield [listKey, {
33
125
  listKey,
@@ -36,6 +128,7 @@ function listsWithDefaults(config, defaultIdField) {
36
128
  defaultIsOrderable: true,
37
129
  // TODO: move to access control?
38
130
  isSingleton: false,
131
+ cascade: [],
39
132
  ...list,
40
133
  db: {
41
134
  ...list.db
@@ -79,8 +172,10 @@ async function noop() {}
79
172
  function identity(x) {
80
173
  return x;
81
174
  }
82
- function config(config) {
83
- var _config$db, _config$db$url, _config$db$idField, _config$server, _config$server2, _config$server$cors, _config$server3, _config$types$path, _config$types, _config$db$shadowData, _config$db2, _config$db$extendPris, _config$db3, _config$db$extendPris2, _config$db4, _config$db$onConnect, _config$db$prismaClie, _config$db5, _config$db$prismaSche, _config$db6, _config$db$idField2, _config$db7, _config$db$enableLogg, _config$graphql$path, _config$graphql, _config$graphql$playg, _config$graphql2, _config$graphql$schem, _config$graphql3, _config$graphql$exten, _config$graphql4, _config$server$maxFil, _config$server4, _config$server$extend, _config$server5, _config$server$extend2, _config$server6, _config$telemetry, _config$ui$basePath, _config$ui, _config$ui$isAccessAl, _config$ui2, _config$ui$isDisabled, _config$ui3, _config$ui$getAdditio, _config$ui4, _config$ui$pageMiddle, _config$ui5, _config$ui$publicPage, _config$ui6;
175
+ function buildConfig(config) {
176
+ var _config$db, _config$db$url, _config$db$idField, _config$server, _config$server2, _config$server$cors, _config$server3, _config, _config2, _config$types$path, _config$types, _config$db$shadowData, _config$db2, _config$db$extendPris, _config$db3, _config$db$extendPris2, _config$db4, _config$db$onConnect, _config$db$prismaClie, _config$db5, _config$db$prismaSche, _config$db6, _config$db$idField2, _config$db7, _config$db$enableLogg, _config$graphql$path, _config$graphql, _config$graphql$playg, _config$graphql2, _config$graphql$schem, _config$graphql3, _config$graphql$exten, _config$graphql4, _config$server$maxFil, _config$server4, _config$server$extend, _config$server5, _config$server$extend2, _config$server6, _config$telemetry, _config$ui$basePath, _config$ui, _config$ui$isAccessAl, _config$ui2, _config$ui$isDisabled, _config$ui3, _config$ui$getAdditio, _config$ui4, _config$ui$pageMiddle, _config$ui5, _config$ui$publicPage, _config$ui6;
177
+ if (config.env) validateEnv(config.env);
178
+ config = applyPlugins(config);
84
179
  if (!['postgresql', 'sqlite', 'mysql'].includes(config.db.provider)) {
85
180
  throw new TypeError(`"db.provider" only supports "sqlite", "postgresql" or "mysql"`);
86
181
  }
@@ -97,10 +192,10 @@ function config(config) {
97
192
  const httpOptions = {
98
193
  port: 3000
99
194
  };
100
- if (config !== null && config !== void 0 && config.server && 'port' in config.server) {
195
+ if ((_config = config) !== null && _config !== void 0 && _config.server && 'port' in config.server) {
101
196
  httpOptions.port = config.server.port;
102
197
  }
103
- if (config !== null && config !== void 0 && config.server && 'options' in config.server && config.server.options) {
198
+ if ((_config2 = config) !== null && _config2 !== void 0 && _config2.server && 'options' in config.server && config.server.options) {
104
199
  Object.assign(httpOptions, config.server.options);
105
200
  }
106
201
  return {
@@ -148,6 +243,12 @@ function config(config) {
148
243
  search: config.search,
149
244
  notifications: config.notifications,
150
245
  ai: config.ai,
246
+ aiRag: config.aiRag,
247
+ versioning: config.versioning,
248
+ workflow: config.workflow,
249
+ apiKeys: config.apiKeys,
250
+ logger: config.logger,
251
+ backup: config.backup,
151
252
  telemetry: (_config$telemetry = config.telemetry) !== null && _config$telemetry !== void 0 ? _config$telemetry : true,
152
253
  ui: {
153
254
  ...config.ui,
@@ -161,7 +262,7 @@ function config(config) {
161
262
  };
162
263
  }
163
264
  let i = 0;
164
- function group(config) {
265
+ function fieldGroup(config) {
165
266
  var _config$description;
166
267
  const keys = Object.keys(config.fields);
167
268
  if (keys.some(key => key.startsWith('__group'))) {
@@ -177,18 +278,408 @@ function group(config) {
177
278
  ...config.fields
178
279
  }; // TODO: FIXME, see initialise-lists.ts:getListsWithInitialisedFields
179
280
  }
180
- function list(listConfig) {
281
+ function collection(listConfig) {
181
282
  return {
182
283
  ...listConfig
183
284
  };
184
285
  }
185
- function action(action) {
286
+ function createAction(action) {
186
287
  return {
187
288
  ...action,
188
289
  ___defineActionsWithActionFunction: true
189
290
  };
190
291
  }
191
292
 
293
+ /**
294
+ * Declarative collection features compiled into hooks + access-control filters by
295
+ * `defineCollection()`: computed fields, constraints, default filters, state machines,
296
+ * policies, events, search indexing and version snapshots.
297
+ *
298
+ * Everything here builds on the public hook/access surface — no resolver internals —
299
+ * so the features compose with mixins and user hooks via the same merge pipeline.
300
+ */
301
+
302
+ // ── Option types ──
303
+
304
+ /**
305
+ * Persisted derived fields, recalculated on every create/update after all other
306
+ * `resolveInput` hooks have run. The target keys must be real fields on the collection
307
+ * (unlike `virtual()` fields, computed values are stored — so they can be filtered and
308
+ * sorted). `merged` is the item's prospective state (existing values + this write).
309
+ *
310
+ * @example
311
+ * computed: { total: ({ merged }) => merged.price * merged.quantity }
312
+ */
313
+
314
+ /**
315
+ * Data-integrity rules checked before every create/update.
316
+ *
317
+ * - `uniqueTogether`: compound uniqueness over scalar fields (e.g. `[['tenant', 'slug']]`).
318
+ * Checked with a query, so add a DB index for hot paths.
319
+ * - `checks`: named cross-field rules; return an error message to reject the write.
320
+ *
321
+ * @example
322
+ * constraints: {
323
+ * uniqueTogether: [['translationKey', 'locale']],
324
+ * checks: { dates: ({ merged }) => merged.endDate <= merged.startDate ? 'endDate must be after startDate' : undefined },
325
+ * }
326
+ */
327
+
328
+ /**
329
+ * A where-filter automatically ANDed into every query/update/delete — including the
330
+ * Admin UI, which respects access filters. This is what makes `withSoftDelete()` real:
331
+ *
332
+ * @example
333
+ * defaultFilter: { deletedAt: null }
334
+ * @example
335
+ * defaultFilter: ({ session }) => session?.data?.isAdmin ? true : { status: { equals: 'published' } }
336
+ */
337
+
338
+ /**
339
+ * Enforce legal status transitions on a select field at the mutation layer.
340
+ *
341
+ * @example
342
+ * stateMachine: {
343
+ * field: 'status',
344
+ * transitions: { draft: ['review'], review: ['published', 'draft'], published: ['archived'] },
345
+ * guards: { 'review->published': ({ session }) => session?.data?.role === 'editor' || 'Only editors can publish' },
346
+ * }
347
+ */
348
+
349
+ /** One row-level access rule: the first rule whose `when` matches decides the filter. */
350
+
351
+ /**
352
+ * Declarative row-level access: per operation, rules are evaluated in order and the
353
+ * first matching `when` supplies the filter; no match means no access. ANDed with any
354
+ * explicit `access.filter` you also configure. Pairs naturally with @nixxie-cms/rbac.
355
+ *
356
+ * @example
357
+ * policies: {
358
+ * query: [
359
+ * { when: s => s?.data?.role === 'admin', filter: true },
360
+ * { when: s => !!s, filter: s => ({ author: { id: { equals: s.itemId } } }) },
361
+ * ],
362
+ * }
363
+ */
364
+
365
+ /**
366
+ * Emit lifecycle events through `context.services.webhooks` after every write:
367
+ * `<prefix>.created` / `.updated` / `.deleted` (prefix defaults to the list key).
368
+ * No-op when the webhooks service is not configured.
369
+ */
370
+
371
+ /**
372
+ * Keep a search index in sync through `context.services.search`: documents are indexed
373
+ * after create/update and removed after delete. No-op when search is not configured.
374
+ */
375
+
376
+ /**
377
+ * Snapshot every create/update into `context.services.versioning` (resource = list key).
378
+ * No-op when versioning is not configured.
379
+ */
380
+
381
+ // ── Compilation to hooks ──
382
+
383
+ const mergedView = args => {
384
+ var _args$item, _args$resolvedData;
385
+ return {
386
+ ...((_args$item = args.item) !== null && _args$item !== void 0 ? _args$item : {}),
387
+ ...((_args$resolvedData = args.resolvedData) !== null && _args$resolvedData !== void 0 ? _args$resolvedData : {})
388
+ };
389
+ };
390
+ function computedHooks(computed) {
391
+ return {
392
+ resolveInput: async args => {
393
+ const out = {
394
+ ...args.resolvedData
395
+ };
396
+ for (const [field, fn] of Object.entries(computed)) {
397
+ var _args$item2;
398
+ out[field] = await fn({
399
+ operation: args.operation,
400
+ resolvedData: out,
401
+ merged: {
402
+ ...((_args$item2 = args.item) !== null && _args$item2 !== void 0 ? _args$item2 : {}),
403
+ ...out
404
+ },
405
+ item: args.item,
406
+ context: args.context
407
+ });
408
+ }
409
+ return out;
410
+ }
411
+ };
412
+ }
413
+ function constraintsHooks(constraints) {
414
+ return {
415
+ validate: async args => {
416
+ const {
417
+ operation,
418
+ addValidationError
419
+ } = args;
420
+ if (operation === 'delete') return;
421
+ const merged = mergedView(args);
422
+ for (const tuple of (_constraints$uniqueTo = constraints.uniqueTogether) !== null && _constraints$uniqueTo !== void 0 ? _constraints$uniqueTo : []) {
423
+ var _constraints$uniqueTo;
424
+ const values = tuple.map(field => merged[field]);
425
+ // Incomplete tuples (a NULL member) are not checked — same semantics as SQL unique indexes.
426
+ if (values.some(value => value === undefined || value === null)) continue;
427
+ const where = {};
428
+ tuple.forEach((field, i) => where[field] = {
429
+ equals: values[i]
430
+ });
431
+ try {
432
+ const clashes = await args.context.sudo().db[args.listKey].findMany({
433
+ where,
434
+ take: 2
435
+ });
436
+ const other = clashes.find(clash => !args.item || String(clash.id) !== String(args.item.id));
437
+ if (other) {
438
+ addValidationError(`Another item already exists with the same ${tuple.join(' + ')}`);
439
+ }
440
+ } catch (err) {
441
+ // A malformed tuple (unknown/non-scalar field) should fail loudly, not silently pass.
442
+ addValidationError(`uniqueTogether check for (${tuple.join(', ')}) failed: ${err instanceof Error ? err.message : err}`);
443
+ }
444
+ }
445
+ for (const check of Object.values((_constraints$checks = constraints.checks) !== null && _constraints$checks !== void 0 ? _constraints$checks : {})) {
446
+ var _constraints$checks;
447
+ const message = await check({
448
+ operation: args.operation,
449
+ resolvedData: args.resolvedData,
450
+ merged,
451
+ item: args.item,
452
+ context: args.context
453
+ });
454
+ if (typeof message === 'string' && message.length > 0) addValidationError(message);
455
+ }
456
+ }
457
+ };
458
+ }
459
+ function stateMachineHooks(machine) {
460
+ const {
461
+ field,
462
+ transitions,
463
+ guards = {}
464
+ } = machine;
465
+ const initial = machine.initial === undefined ? undefined : Array.isArray(machine.initial) ? machine.initial : [machine.initial];
466
+ return {
467
+ validate: async args => {
468
+ var _transitions$previous;
469
+ const {
470
+ operation,
471
+ resolvedData,
472
+ item,
473
+ addValidationError
474
+ } = args;
475
+ if (operation === 'delete') return;
476
+ const next = resolvedData === null || resolvedData === void 0 ? void 0 : resolvedData[field];
477
+ if (next === undefined) return;
478
+ if (operation === 'create') {
479
+ if (initial && next != null && !initial.includes(next)) {
480
+ addValidationError(`"${field}" cannot start as "${next}" (allowed: ${initial.join(', ')})`);
481
+ }
482
+ return;
483
+ }
484
+ const previous = item === null || item === void 0 ? void 0 : item[field];
485
+ if (next === previous) return;
486
+ const allowed = (_transitions$previous = transitions[previous]) !== null && _transitions$previous !== void 0 ? _transitions$previous : [];
487
+ if (!allowed.includes(next)) {
488
+ addValidationError(`"${field}" cannot change from "${previous}" to "${next}"` + (allowed.length ? ` (allowed: ${allowed.join(', ')})` : ' (no transitions from this state)'));
489
+ return;
490
+ }
491
+ const guard = guards[`${previous}->${next}`];
492
+ if (guard) {
493
+ var _args$context;
494
+ const verdict = await guard({
495
+ item,
496
+ resolvedData,
497
+ context: args.context,
498
+ session: (_args$context = args.context) === null || _args$context === void 0 ? void 0 : _args$context.session
499
+ });
500
+ if (verdict !== true) {
501
+ addValidationError(typeof verdict === 'string' ? verdict : `"${field}" transition "${previous}" → "${next}" was blocked`);
502
+ }
503
+ }
504
+ }
505
+ };
506
+ }
507
+ const pastTense = {
508
+ create: 'created',
509
+ update: 'updated',
510
+ delete: 'deleted'
511
+ };
512
+ function eventsHooks(events) {
513
+ var _options$operations;
514
+ const options = events === true ? {} : events;
515
+ const operations = (_options$operations = options.operations) !== null && _options$operations !== void 0 ? _options$operations : ['create', 'update', 'delete'];
516
+ return {
517
+ afterOperation: async args => {
518
+ var _args$context2;
519
+ if (!operations.includes(args.operation)) return;
520
+ const webhooks = (_args$context2 = args.context) === null || _args$context2 === void 0 || (_args$context2 = _args$context2.services) === null || _args$context2 === void 0 ? void 0 : _args$context2.webhooks;
521
+ if (!webhooks) return;
522
+ try {
523
+ var _args$item3, _options$prefix;
524
+ const subject = (_args$item3 = args.item) !== null && _args$item3 !== void 0 ? _args$item3 : args.originalItem;
525
+ const event = `${(_options$prefix = options.prefix) !== null && _options$prefix !== void 0 ? _options$prefix : args.listKey}.${pastTense[args.operation]}`;
526
+ const payload = options.payload ? await options.payload(args) : {
527
+ listKey: args.listKey,
528
+ id: (subject === null || subject === void 0 ? void 0 : subject.id) != null ? String(subject.id) : undefined,
529
+ item: subject
530
+ };
531
+ await webhooks.trigger(event, payload);
532
+ } catch (err) {
533
+ console.error(`[nixxie] events: failed to emit for ${args.listKey}:`, err);
534
+ }
535
+ }
536
+ };
537
+ }
538
+
539
+ /** Copy the indexable scalar values off an item (used when `fields` is not specified). */
540
+ function scalarDocument(item) {
541
+ const doc = {};
542
+ for (const [key, value] of Object.entries(item)) {
543
+ if (key.startsWith('__')) continue;
544
+ if (value === null) doc[key] = null;else if (value instanceof Date) doc[key] = value.toISOString();else if (['string', 'number', 'boolean'].includes(typeof value)) doc[key] = value;
545
+ }
546
+ return doc;
547
+ }
548
+ function searchableHooks(searchable) {
549
+ const options = searchable === true ? {} : searchable;
550
+ return {
551
+ afterOperation: async args => {
552
+ var _args$context3, _options$index;
553
+ const search = (_args$context3 = args.context) === null || _args$context3 === void 0 || (_args$context3 = _args$context3.services) === null || _args$context3 === void 0 ? void 0 : _args$context3.search;
554
+ if (!search) return;
555
+ const indexName = (_options$index = options.index) !== null && _options$index !== void 0 ? _options$index : String(args.listKey).toLowerCase();
556
+ try {
557
+ if (args.operation === 'delete') {
558
+ await search.remove(indexName, String(args.originalItem.id));
559
+ return;
560
+ }
561
+ const item = args.item;
562
+ const picked = options.fields ? Object.fromEntries(options.fields.map(field => [field, item[field] instanceof Date ? item[field].toISOString() : item[field]])) : scalarDocument(item);
563
+ await search.index(indexName, {
564
+ ...picked,
565
+ id: String(item.id)
566
+ });
567
+ } catch (err) {
568
+ console.error(`[nixxie] searchable: failed to sync index "${indexName}":`, err);
569
+ }
570
+ }
571
+ };
572
+ }
573
+ function versionedHooks(versioned) {
574
+ const options = versioned === true ? {} : versioned;
575
+ return {
576
+ afterOperation: async args => {
577
+ var _args$context4;
578
+ if (args.operation === 'delete') return;
579
+ const versioning = (_args$context4 = args.context) === null || _args$context4 === void 0 || (_args$context4 = _args$context4.services) === null || _args$context4 === void 0 ? void 0 : _args$context4.versioning;
580
+ if (!versioning) return;
581
+ try {
582
+ var _args$context5, _options$label;
583
+ const session = (_args$context5 = args.context) === null || _args$context5 === void 0 ? void 0 : _args$context5.session;
584
+ await versioning.snapshot({
585
+ resource: args.listKey,
586
+ resourceId: String(args.item.id),
587
+ data: scalarSafe(args.item),
588
+ label: (_options$label = options.label) === null || _options$label === void 0 ? void 0 : _options$label.call(options, args),
589
+ actor: (session === null || session === void 0 ? void 0 : session.itemId) != null ? {
590
+ id: String(session.itemId)
591
+ } : undefined
592
+ });
593
+ } catch (err) {
594
+ console.error(`[nixxie] versioned: failed to snapshot ${args.listKey}:`, err);
595
+ }
596
+ }
597
+ };
598
+ }
599
+
600
+ /** Snapshot-safe clone: keeps JSON-representable values, ISO-stringifies dates. */
601
+ function scalarSafe(item) {
602
+ const out = {};
603
+ for (const [key, value] of Object.entries(item)) {
604
+ if (value instanceof Date) out[key] = value.toISOString();else if (typeof value === 'bigint') out[key] = value.toString();else if (typeof value !== 'function' && typeof value !== 'symbol') out[key] = value;
605
+ }
606
+ return out;
607
+ }
608
+
609
+ /** Compile the declarative features into hook fragments, in a deliberate order. */
610
+ function compileFeatureHooks(features) {
611
+ const hooks = [];
612
+ if (features.computed) hooks.push(computedHooks(features.computed));
613
+ if (features.constraints) hooks.push(constraintsHooks(features.constraints));
614
+ if (features.stateMachine) hooks.push(stateMachineHooks(features.stateMachine));
615
+ if (features.events) hooks.push(eventsHooks(features.events));
616
+ if (features.searchable) hooks.push(searchableHooks(features.searchable));
617
+ if (features.versioned) hooks.push(versionedHooks(features.versioned));
618
+ return hooks;
619
+ }
620
+
621
+ // ── Compilation to access filters ──
622
+
623
+ /** AND two access filters; `true`/missing means unrestricted, `false` wins outright. */
624
+ function andFilters(a, b) {
625
+ if (a === undefined) return b;
626
+ return async args => {
627
+ const ra = typeof a === 'function' ? await a(args) : a;
628
+ const rb = typeof b === 'function' ? await b(args) : b;
629
+ if (ra === false || rb === false) return false;
630
+ if (ra === true) return rb;
631
+ if (rb === true) return ra;
632
+ return {
633
+ AND: [ra, rb]
634
+ };
635
+ };
636
+ }
637
+ function policyFilter(rules) {
638
+ return ({
639
+ session
640
+ }) => {
641
+ for (const rule of rules) {
642
+ if (!rule.when(session)) continue;
643
+ return typeof rule.filter === 'function' ? rule.filter(session) : rule.filter;
644
+ }
645
+ return false;
646
+ };
647
+ }
648
+
649
+ /**
650
+ * Merge `defaultFilter` and `policies` into an access-control object. Existing filters
651
+ * are preserved and ANDed with the feature filters.
652
+ */
653
+ function applyAccessFeatures(access, features) {
654
+ var _access$filter;
655
+ const {
656
+ defaultFilter,
657
+ policies
658
+ } = features;
659
+ if (!defaultFilter && !policies) return access;
660
+ const filter = {
661
+ ...((_access$filter = access === null || access === void 0 ? void 0 : access.filter) !== null && _access$filter !== void 0 ? _access$filter : {})
662
+ };
663
+ for (const operation of ['query', 'update', 'delete']) {
664
+ let merged = filter[operation];
665
+ if (defaultFilter) {
666
+ merged = andFilters(merged, typeof defaultFilter === 'function' ? args => defaultFilter({
667
+ session: args.session,
668
+ context: args.context
669
+ }) : defaultFilter);
670
+ }
671
+ const rules = policies === null || policies === void 0 ? void 0 : policies[operation];
672
+ if (rules !== null && rules !== void 0 && rules.length) {
673
+ merged = andFilters(merged, policyFilter(rules));
674
+ }
675
+ if (merged !== undefined) filter[operation] = merged;
676
+ }
677
+ return {
678
+ ...(access !== null && access !== void 0 ? access : {}),
679
+ filter
680
+ };
681
+ }
682
+
192
683
  // ================================================================
193
684
  // Validators — use inside field `validation` config
194
685
  // ================================================================
@@ -240,6 +731,72 @@ const validators = {
240
731
  }
241
732
  };
242
733
 
734
+ // ================================================================
735
+ // Access presets — readable shorthands for common access patterns
736
+ // ================================================================
737
+ //
738
+ // Spelling out an access-control object on every list gets repetitive. In
739
+ // practice 90% of lists fall into a handful of patterns, so we name them.
740
+ // Anything more bespoke can still drop down to a raw access object.
741
+
742
+ const isSignedIn = ({
743
+ session
744
+ }) => !!session;
745
+ const accessPresets = {
746
+ public: () => true,
747
+ authenticated: {
748
+ operation: {
749
+ query: isSignedIn,
750
+ create: isSignedIn,
751
+ update: isSignedIn,
752
+ delete: isSignedIn
753
+ }
754
+ },
755
+ publicReadAuthenticatedWrite: {
756
+ operation: {
757
+ query: () => true,
758
+ create: isSignedIn,
759
+ update: isSignedIn,
760
+ delete: isSignedIn
761
+ }
762
+ },
763
+ readOnly: {
764
+ operation: {
765
+ query: () => true,
766
+ create: () => false,
767
+ update: () => false,
768
+ delete: () => false
769
+ }
770
+ },
771
+ owner(field = 'user') {
772
+ const scopeToOwner = ({
773
+ session
774
+ }) => {
775
+ if (!(session !== null && session !== void 0 && session.itemId)) return false;
776
+ return {
777
+ [field]: {
778
+ id: {
779
+ equals: session.itemId
780
+ }
781
+ }
782
+ };
783
+ };
784
+ return {
785
+ operation: {
786
+ query: isSignedIn,
787
+ create: isSignedIn,
788
+ update: isSignedIn,
789
+ delete: isSignedIn
790
+ },
791
+ filter: {
792
+ query: scopeToOwner,
793
+ update: scopeToOwner,
794
+ delete: scopeToOwner
795
+ }
796
+ };
797
+ }
798
+ };
799
+
243
800
  // ================================================================
244
801
  // Mixin system
245
802
  // ================================================================
@@ -330,7 +887,7 @@ function withSoftDelete() {
330
887
  function withAudit(userListKey = 'User') {
331
888
  return {
332
889
  fields: {
333
- createdBy: index.relationship({
890
+ createdBy: index$1.relationship({
334
891
  ref: userListKey,
335
892
  ui: {
336
893
  createView: {
@@ -341,7 +898,7 @@ function withAudit(userListKey = 'User') {
341
898
  }
342
899
  }
343
900
  }),
344
- updatedBy: index.relationship({
901
+ updatedBy: index$1.relationship({
345
902
  ref: userListKey,
346
903
  ui: {
347
904
  createView: {
@@ -395,6 +952,760 @@ function withAudit(userListKey = 'User') {
395
952
  };
396
953
  }
397
954
 
955
+ /**
956
+ * Turn an arbitrary string into a URL-safe slug. Pure, dependency-free.
957
+ */
958
+ function slugify(input) {
959
+ return input.toString().normalize('NFKD').replace(/[̀-ͯ]/g, '') // strip accents
960
+ .toLowerCase().trim().replace(/[^a-z0-9]+/g, '-') // non-alphanumerics → dashes
961
+ .replace(/^-+|-+$/g, ''); // trim leading/trailing dashes
962
+ }
963
+
964
+ /**
965
+ * Adds a URL-friendly `slug` field that is auto-generated from another field
966
+ * (e.g. `title`) when left blank, and normalised when provided.
967
+ *
968
+ * Solves a perennial papercut: there's no built-in slug field, so everyone
969
+ * re-implements the same `resolveInput` hook by hand.
970
+ *
971
+ * @example
972
+ * defineCollection({ mixins: [withSlug({ from: 'title' })], fields: { title: text() } })
973
+ */
974
+ function withSlug(opts = {
975
+ from: 'title'
976
+ }) {
977
+ var _opts$field, _opts$isIndexed;
978
+ const fieldKey = (_opts$field = opts.field) !== null && _opts$field !== void 0 ? _opts$field : 'slug';
979
+ const from = opts.from;
980
+ return {
981
+ fields: {
982
+ [fieldKey]: index.text({
983
+ isIndexed: (_opts$isIndexed = opts.isIndexed) !== null && _opts$isIndexed !== void 0 ? _opts$isIndexed : 'unique',
984
+ ui: {
985
+ description: `URL slug — auto-generated from "${from}" when left blank.`
986
+ }
987
+ })
988
+ },
989
+ hooks: {
990
+ resolveInput: ({
991
+ resolvedData,
992
+ inputData
993
+ }) => {
994
+ var _from;
995
+ const provided = resolvedData[fieldKey];
996
+ if (typeof provided === 'string' && provided.length > 0) {
997
+ return {
998
+ ...resolvedData,
999
+ [fieldKey]: slugify(provided)
1000
+ };
1001
+ }
1002
+ const source = (_from = inputData === null || inputData === void 0 ? void 0 : inputData[from]) !== null && _from !== void 0 ? _from : resolvedData === null || resolvedData === void 0 ? void 0 : resolvedData[from];
1003
+ if (typeof source === 'string' && source.length > 0) {
1004
+ return {
1005
+ ...resolvedData,
1006
+ [fieldKey]: slugify(source)
1007
+ };
1008
+ }
1009
+ return resolvedData;
1010
+ }
1011
+ }
1012
+ };
1013
+ }
1014
+
1015
+ /**
1016
+ * Adds a draft → published → archived workflow: a `status` select plus a
1017
+ * `publishedAt` timestamp that is stamped automatically the first time an item
1018
+ * transitions to `published`.
1019
+ *
1020
+ * Publishing is otherwise left entirely to the developer; this bakes in the
1021
+ * common content lifecycle so a blog/news/docs list works out of the box.
1022
+ */
1023
+ function withPublishing(opts = {}) {
1024
+ var _opts$defaultStatus;
1025
+ const defaultStatus = (_opts$defaultStatus = opts.defaultStatus) !== null && _opts$defaultStatus !== void 0 ? _opts$defaultStatus : 'draft';
1026
+ return {
1027
+ fields: {
1028
+ status: index$1.select({
1029
+ type: 'enum',
1030
+ options: [{
1031
+ label: 'Draft',
1032
+ value: 'draft'
1033
+ }, {
1034
+ label: 'Published',
1035
+ value: 'published'
1036
+ }, {
1037
+ label: 'Archived',
1038
+ value: 'archived'
1039
+ }],
1040
+ defaultValue: defaultStatus,
1041
+ ui: {
1042
+ displayMode: 'segmented-control'
1043
+ }
1044
+ }),
1045
+ publishedAt: index.timestamp({
1046
+ ui: {
1047
+ createView: {
1048
+ fieldMode: 'hidden'
1049
+ },
1050
+ itemView: {
1051
+ fieldMode: 'read'
1052
+ },
1053
+ listView: {
1054
+ fieldMode: 'read'
1055
+ }
1056
+ }
1057
+ })
1058
+ },
1059
+ hooks: {
1060
+ resolveInput: ({
1061
+ resolvedData,
1062
+ item
1063
+ }) => {
1064
+ var _status;
1065
+ const nextStatus = (_status = resolvedData.status) !== null && _status !== void 0 ? _status : item === null || item === void 0 ? void 0 : item.status;
1066
+ const alreadyPublished = item === null || item === void 0 ? void 0 : item.publishedAt;
1067
+ const incomingPublishedAt = resolvedData.publishedAt;
1068
+ if (nextStatus === 'published' && !alreadyPublished && incomingPublishedAt == null) {
1069
+ return {
1070
+ ...resolvedData,
1071
+ publishedAt: new Date().toISOString()
1072
+ };
1073
+ }
1074
+ return resolvedData;
1075
+ }
1076
+ }
1077
+ };
1078
+ }
1079
+
1080
+ /**
1081
+ * Adds standard SEO metadata fields, grouped together in the Admin UI.
1082
+ * Drop-in for any content list that needs search/social previews.
1083
+ */
1084
+ function withSEO() {
1085
+ return {
1086
+ fields: {
1087
+ metaTitle: index.text({
1088
+ ui: {
1089
+ description: 'Title used by search engines and social previews.'
1090
+ }
1091
+ }),
1092
+ metaDescription: index.text({
1093
+ ui: {
1094
+ displayMode: 'textarea',
1095
+ description: 'Short summary (~155 characters).'
1096
+ }
1097
+ }),
1098
+ ogImage: index.text({
1099
+ ui: {
1100
+ description: 'Absolute URL to the social sharing image.'
1101
+ }
1102
+ })
1103
+ }
1104
+ };
1105
+ }
1106
+
1107
+ /**
1108
+ * Adds an integer `order` field for manual sorting/drag-ordering of items.
1109
+ */
1110
+ function withSortable(opts = {}) {
1111
+ var _opts$field2;
1112
+ const fieldKey = (_opts$field2 = opts.field) !== null && _opts$field2 !== void 0 ? _opts$field2 : 'order';
1113
+ return {
1114
+ fields: {
1115
+ [fieldKey]: index$1.integer({
1116
+ defaultValue: 0,
1117
+ ui: {
1118
+ description: 'Manual sort position (lower comes first).'
1119
+ }
1120
+ })
1121
+ }
1122
+ };
1123
+ }
1124
+
1125
+ /**
1126
+ * Adds self-referential `parent` / `children` relationships for tree-shaped content
1127
+ * (categories, menus, pages), with cycle prevention: an item can never be moved under
1128
+ * one of its own descendants.
1129
+ *
1130
+ * @param listKey - The key of the collection this mixin is applied to (needed for the
1131
+ * self-referencing relationship and ancestor checks).
1132
+ *
1133
+ * @example
1134
+ * defineCollection({ mixins: [withTreeStructure('Category')], fields: { name: text() } })
1135
+ */
1136
+ function withTreeStructure(listKey, opts = {}) {
1137
+ var _opts$parentField, _opts$childrenField;
1138
+ const parentField = (_opts$parentField = opts.parentField) !== null && _opts$parentField !== void 0 ? _opts$parentField : 'parent';
1139
+ const childrenField = (_opts$childrenField = opts.childrenField) !== null && _opts$childrenField !== void 0 ? _opts$childrenField : 'children';
1140
+ return {
1141
+ fields: {
1142
+ [parentField]: index$1.relationship({
1143
+ ref: `${listKey}.${childrenField}`,
1144
+ ui: {
1145
+ description: 'Parent item in the tree (leave empty for a root item).'
1146
+ }
1147
+ }),
1148
+ [childrenField]: index$1.relationship({
1149
+ ref: `${listKey}.${parentField}`,
1150
+ many: true,
1151
+ ui: {
1152
+ displayMode: 'count',
1153
+ itemView: {
1154
+ fieldMode: 'read'
1155
+ }
1156
+ }
1157
+ })
1158
+ },
1159
+ hooks: {
1160
+ validate: async args => {
1161
+ var _parentOp$connect;
1162
+ const {
1163
+ operation,
1164
+ resolvedData,
1165
+ item,
1166
+ context,
1167
+ addValidationError
1168
+ } = args;
1169
+ if (operation !== 'update') return;
1170
+ const parentOp = resolvedData === null || resolvedData === void 0 ? void 0 : resolvedData[parentField];
1171
+ const newParentId = parentOp === null || parentOp === void 0 || (_parentOp$connect = parentOp.connect) === null || _parentOp$connect === void 0 ? void 0 : _parentOp$connect.id;
1172
+ if (newParentId == null) return;
1173
+ if (String(newParentId) === String(item.id)) {
1174
+ addValidationError(`"${parentField}" cannot point at the item itself`);
1175
+ return;
1176
+ }
1177
+ // Walk up from the new parent — finding the item means we'd create a cycle.
1178
+ const sudo = context.sudo();
1179
+ let cursor = newParentId;
1180
+ for (let depth = 0; depth < 100 && cursor != null; depth++) {
1181
+ var _ancestor$parentField, _ancestor$parentField2;
1182
+ const ancestor = await sudo.query[listKey].findOne({
1183
+ where: {
1184
+ id: String(cursor)
1185
+ },
1186
+ query: `id ${parentField} { id }`
1187
+ });
1188
+ if (!ancestor) return;
1189
+ cursor = (_ancestor$parentField = (_ancestor$parentField2 = ancestor[parentField]) === null || _ancestor$parentField2 === void 0 ? void 0 : _ancestor$parentField2.id) !== null && _ancestor$parentField !== void 0 ? _ancestor$parentField : null;
1190
+ if (cursor != null && String(cursor) === String(item.id)) {
1191
+ addValidationError(`"${parentField}" would create a cycle — the new parent is a descendant of this item`);
1192
+ return;
1193
+ }
1194
+ }
1195
+ }
1196
+ }
1197
+ };
1198
+ }
1199
+
1200
+ /**
1201
+ * Multi-tenancy: adds a required `tenant` relationship that is auto-assigned from the
1202
+ * session on create. Combine with `tenantAccessFilter()` in the collection's
1203
+ * `access.filter` rules to scope every query/update/delete to the session's tenant.
1204
+ *
1205
+ * @example
1206
+ * defineCollection({
1207
+ * mixins: [withTenant({ ref: 'Tenant' })],
1208
+ * access: {
1209
+ * filter: {
1210
+ * query: tenantAccessFilter(),
1211
+ * update: tenantAccessFilter(),
1212
+ * delete: tenantAccessFilter(),
1213
+ * },
1214
+ * },
1215
+ * fields: { ... },
1216
+ * })
1217
+ */
1218
+ function withTenant(opts = {}) {
1219
+ var _opts$ref, _opts$field3, _opts$getTenantId;
1220
+ const ref = (_opts$ref = opts.ref) !== null && _opts$ref !== void 0 ? _opts$ref : 'Tenant';
1221
+ const field = (_opts$field3 = opts.field) !== null && _opts$field3 !== void 0 ? _opts$field3 : 'tenant';
1222
+ const getTenantId = (_opts$getTenantId = opts.getTenantId) !== null && _opts$getTenantId !== void 0 ? _opts$getTenantId : defaultGetTenantId;
1223
+ return {
1224
+ fields: {
1225
+ [field]: index$1.relationship({
1226
+ ref,
1227
+ ui: {
1228
+ createView: {
1229
+ fieldMode: 'hidden'
1230
+ },
1231
+ itemView: {
1232
+ fieldMode: 'read'
1233
+ }
1234
+ }
1235
+ })
1236
+ },
1237
+ hooks: {
1238
+ resolveInput: ({
1239
+ operation,
1240
+ resolvedData,
1241
+ context
1242
+ }) => {
1243
+ if (operation !== 'create') return resolvedData;
1244
+ if (resolvedData[field]) return resolvedData;
1245
+ const tenantId = getTenantId(context.session);
1246
+ if (!tenantId) return resolvedData;
1247
+ return {
1248
+ ...resolvedData,
1249
+ [field]: {
1250
+ connect: {
1251
+ id: tenantId
1252
+ }
1253
+ }
1254
+ };
1255
+ },
1256
+ validate: async args => {
1257
+ const {
1258
+ operation,
1259
+ resolvedData,
1260
+ addValidationError
1261
+ } = args;
1262
+ if (opts.optional || operation !== 'create') return;
1263
+ if (!(resolvedData !== null && resolvedData !== void 0 && resolvedData[field])) {
1264
+ addValidationError(`"${field}" is required — no tenant found on the session`);
1265
+ }
1266
+ }
1267
+ }
1268
+ };
1269
+ }
1270
+ function defaultGetTenantId(session) {
1271
+ var _session$data$tenant$, _session$data;
1272
+ return (_session$data$tenant$ = session === null || session === void 0 || (_session$data = session.data) === null || _session$data === void 0 || (_session$data = _session$data.tenant) === null || _session$data === void 0 ? void 0 : _session$data.id) !== null && _session$data$tenant$ !== void 0 ? _session$data$tenant$ : session === null || session === void 0 ? void 0 : session.tenantId;
1273
+ }
1274
+
1275
+ /**
1276
+ * Access-control filter companion to `withTenant()`: limits matched items to the
1277
+ * session's tenant. Returns `false` (no access) when the session has no tenant.
1278
+ */
1279
+ function tenantAccessFilter(opts = {}) {
1280
+ var _opts$field4, _opts$getTenantId2;
1281
+ const field = (_opts$field4 = opts.field) !== null && _opts$field4 !== void 0 ? _opts$field4 : 'tenant';
1282
+ const getTenantId = (_opts$getTenantId2 = opts.getTenantId) !== null && _opts$getTenantId2 !== void 0 ? _opts$getTenantId2 : defaultGetTenantId;
1283
+ return ({
1284
+ session
1285
+ }) => {
1286
+ const tenantId = getTenantId(session);
1287
+ if (!tenantId) return false;
1288
+ return {
1289
+ [field]: {
1290
+ id: {
1291
+ equals: tenantId
1292
+ }
1293
+ }
1294
+ };
1295
+ };
1296
+ }
1297
+
1298
+ /**
1299
+ * Adds `publishAt` / `unpublishAt` timestamps for scheduled publishing. Composes with
1300
+ * `withPublishing()` (which provides the `status` field). The schedule is enacted by
1301
+ * `applyScheduledPublishing()` — run it from a cron job:
1302
+ *
1303
+ * @example
1304
+ * jobs: createJobs({ jobs: [{
1305
+ * name: 'scheduled-publishing',
1306
+ * schedule: '* * * * *',
1307
+ * handler: async () => { await applyScheduledPublishing(getContext(), 'Post') },
1308
+ * }]})
1309
+ */
1310
+ function withScheduledPublishing() {
1311
+ return {
1312
+ fields: {
1313
+ publishAt: index.timestamp({
1314
+ ui: {
1315
+ description: 'Automatically publish at this time (requires the scheduled-publishing job).'
1316
+ }
1317
+ }),
1318
+ unpublishAt: index.timestamp({
1319
+ ui: {
1320
+ description: 'Automatically archive at this time (requires the scheduled-publishing job).'
1321
+ }
1322
+ })
1323
+ }
1324
+ };
1325
+ }
1326
+
1327
+ /**
1328
+ * Enact `withScheduledPublishing()` schedules for one collection: publishes drafts whose
1329
+ * `publishAt` has passed and archives published items whose `unpublishAt` has passed.
1330
+ * Designed to be called from a cron job (see `withScheduledPublishing`).
1331
+ */
1332
+ async function applyScheduledPublishing(context, listKey, opts = {}) {
1333
+ var _opts$statusField, _opts$draftValue, _opts$publishedValue, _opts$archivedValue;
1334
+ const statusField = (_opts$statusField = opts.statusField) !== null && _opts$statusField !== void 0 ? _opts$statusField : 'status';
1335
+ const draftValue = (_opts$draftValue = opts.draftValue) !== null && _opts$draftValue !== void 0 ? _opts$draftValue : 'draft';
1336
+ const publishedValue = (_opts$publishedValue = opts.publishedValue) !== null && _opts$publishedValue !== void 0 ? _opts$publishedValue : 'published';
1337
+ const archivedValue = (_opts$archivedValue = opts.archivedValue) !== null && _opts$archivedValue !== void 0 ? _opts$archivedValue : 'archived';
1338
+ const sudo = context.sudo();
1339
+ const now = new Date();
1340
+ const toPublish = await sudo.db[listKey].findMany({
1341
+ where: {
1342
+ [statusField]: {
1343
+ equals: draftValue
1344
+ },
1345
+ publishAt: {
1346
+ lte: now
1347
+ }
1348
+ }
1349
+ });
1350
+ for (const item of toPublish) {
1351
+ await sudo.db[listKey].updateOne({
1352
+ where: {
1353
+ id: String(item.id)
1354
+ },
1355
+ data: {
1356
+ [statusField]: publishedValue
1357
+ }
1358
+ });
1359
+ }
1360
+ const toArchive = await sudo.db[listKey].findMany({
1361
+ where: {
1362
+ [statusField]: {
1363
+ equals: publishedValue
1364
+ },
1365
+ unpublishAt: {
1366
+ lte: now
1367
+ }
1368
+ }
1369
+ });
1370
+ for (const item of toArchive) {
1371
+ await sudo.db[listKey].updateOne({
1372
+ where: {
1373
+ id: String(item.id)
1374
+ },
1375
+ data: {
1376
+ [statusField]: archivedValue
1377
+ }
1378
+ });
1379
+ }
1380
+ return {
1381
+ published: toPublish.length,
1382
+ archived: toArchive.length
1383
+ };
1384
+ }
1385
+
1386
+ /**
1387
+ * i18n: adds a `locale` select plus a shared `translationKey` that groups an item with
1388
+ * its translations (auto-generated on create when blank). Query an item's variants with
1389
+ * `{ translationKey: { equals }, locale: { not: ... } }` — and once compound uniqueness
1390
+ * is configured, pair (`translationKey`, `locale`) should be unique.
1391
+ *
1392
+ * @example
1393
+ * defineCollection({ mixins: [withLocale({ locales: ['en', 'ur', 'ar'] })], fields: { ... } })
1394
+ */
1395
+ function withLocale(opts) {
1396
+ var _opts$locales, _opts$groupField, _opts$defaultLocale;
1397
+ if (!((_opts$locales = opts.locales) !== null && _opts$locales !== void 0 && _opts$locales.length)) throw new Error('withLocale requires at least one locale');
1398
+ const groupField = (_opts$groupField = opts.groupField) !== null && _opts$groupField !== void 0 ? _opts$groupField : 'translationKey';
1399
+ const defaultLocale = (_opts$defaultLocale = opts.defaultLocale) !== null && _opts$defaultLocale !== void 0 ? _opts$defaultLocale : opts.locales[0];
1400
+ return {
1401
+ fields: {
1402
+ locale: index$1.select({
1403
+ type: 'enum',
1404
+ options: opts.locales.map(locale => ({
1405
+ label: locale,
1406
+ value: locale
1407
+ })),
1408
+ defaultValue: defaultLocale,
1409
+ validation: {
1410
+ isRequired: true
1411
+ }
1412
+ }),
1413
+ [groupField]: index.text({
1414
+ isIndexed: true,
1415
+ ui: {
1416
+ description: 'Shared id linking this item with its translations.',
1417
+ createView: {
1418
+ fieldMode: 'hidden'
1419
+ },
1420
+ itemView: {
1421
+ fieldMode: 'read'
1422
+ }
1423
+ }
1424
+ })
1425
+ },
1426
+ hooks: {
1427
+ resolveInput: ({
1428
+ operation,
1429
+ resolvedData
1430
+ }) => {
1431
+ if (operation !== 'create') return resolvedData;
1432
+ if (resolvedData[groupField]) return resolvedData;
1433
+ return {
1434
+ ...resolvedData,
1435
+ [groupField]: node_crypto.randomBytes(8).toString('hex')
1436
+ };
1437
+ }
1438
+ }
1439
+ };
1440
+ }
1441
+
1442
+ /**
1443
+ * Editorial approval: adds an approval status + a `pendingChanges` buffer where proposed
1444
+ * edits wait for review instead of going live. Drive it with `submitForApproval()`,
1445
+ * `approveChanges()` and `rejectChanges()` from custom mutations or the Admin UI.
1446
+ */
1447
+ function withApproval() {
1448
+ return {
1449
+ fields: {
1450
+ approvalStatus: index$1.select({
1451
+ type: 'enum',
1452
+ options: [{
1453
+ label: 'None',
1454
+ value: 'none'
1455
+ }, {
1456
+ label: 'Pending',
1457
+ value: 'pending'
1458
+ }, {
1459
+ label: 'Approved',
1460
+ value: 'approved'
1461
+ }, {
1462
+ label: 'Rejected',
1463
+ value: 'rejected'
1464
+ }],
1465
+ defaultValue: 'none',
1466
+ ui: {
1467
+ createView: {
1468
+ fieldMode: 'hidden'
1469
+ },
1470
+ itemView: {
1471
+ fieldMode: 'read'
1472
+ }
1473
+ }
1474
+ }),
1475
+ pendingChanges: index.json({
1476
+ ui: {
1477
+ createView: {
1478
+ fieldMode: 'hidden'
1479
+ },
1480
+ itemView: {
1481
+ fieldMode: 'hidden'
1482
+ },
1483
+ listView: {
1484
+ fieldMode: 'hidden'
1485
+ }
1486
+ }
1487
+ }),
1488
+ approvalSubmittedAt: index.timestamp({
1489
+ ui: {
1490
+ createView: {
1491
+ fieldMode: 'hidden'
1492
+ },
1493
+ itemView: {
1494
+ fieldMode: 'read'
1495
+ }
1496
+ }
1497
+ }),
1498
+ approvalReviewedAt: index.timestamp({
1499
+ ui: {
1500
+ createView: {
1501
+ fieldMode: 'hidden'
1502
+ },
1503
+ itemView: {
1504
+ fieldMode: 'read'
1505
+ }
1506
+ }
1507
+ })
1508
+ }
1509
+ };
1510
+ }
1511
+
1512
+ /** Park proposed changes on an item for review (see `withApproval`). */
1513
+ async function submitForApproval(context, args) {
1514
+ await context.sudo().db[args.listKey].updateOne({
1515
+ where: {
1516
+ id: args.itemId
1517
+ },
1518
+ data: {
1519
+ pendingChanges: args.changes,
1520
+ approvalStatus: 'pending',
1521
+ approvalSubmittedAt: new Date().toISOString()
1522
+ }
1523
+ });
1524
+ }
1525
+
1526
+ /**
1527
+ * Apply an item's `pendingChanges` (running normal hooks/validation) and mark it
1528
+ * approved. The buffered changes must be a valid update input for the collection.
1529
+ */
1530
+ async function approveChanges(context, args) {
1531
+ const sudo = context.sudo();
1532
+ const item = await sudo.query[args.listKey].findOne({
1533
+ where: {
1534
+ id: args.itemId
1535
+ },
1536
+ query: 'id pendingChanges approvalStatus'
1537
+ });
1538
+ if (!(item !== null && item !== void 0 && item.pendingChanges)) throw new Error('approveChanges: the item has no pending changes');
1539
+ await sudo.db[args.listKey].updateOne({
1540
+ where: {
1541
+ id: args.itemId
1542
+ },
1543
+ data: {
1544
+ ...item.pendingChanges,
1545
+ pendingChanges: null,
1546
+ approvalStatus: 'approved',
1547
+ approvalReviewedAt: new Date().toISOString()
1548
+ }
1549
+ });
1550
+ }
1551
+
1552
+ /** Discard an item's `pendingChanges` and mark it rejected. */
1553
+ async function rejectChanges(context, args) {
1554
+ await context.sudo().db[args.listKey].updateOne({
1555
+ where: {
1556
+ id: args.itemId
1557
+ },
1558
+ data: {
1559
+ pendingChanges: null,
1560
+ approvalStatus: 'rejected',
1561
+ approvalReviewedAt: new Date().toISOString()
1562
+ }
1563
+ });
1564
+ }
1565
+
1566
+ /**
1567
+ * Adds an `expiresAt` timestamp for content with a shelf life. Pair with
1568
+ * `purgeExpired()` in a cron job to physically remove (or just count) expired items.
1569
+ */
1570
+ function withExpiry(opts = {}) {
1571
+ var _opts$field5;
1572
+ const field = (_opts$field5 = opts.field) !== null && _opts$field5 !== void 0 ? _opts$field5 : 'expiresAt';
1573
+ return {
1574
+ fields: {
1575
+ [field]: index.timestamp({
1576
+ ui: {
1577
+ description: 'After this time the item is considered expired.'
1578
+ }
1579
+ })
1580
+ }
1581
+ };
1582
+ }
1583
+
1584
+ /**
1585
+ * Delete every item whose expiry has passed (runs normal delete hooks). Returns the
1586
+ * number deleted. Designed for a cron job; see `withExpiry`.
1587
+ */
1588
+ async function purgeExpired(context, listKey, opts = {}) {
1589
+ var _opts$field6;
1590
+ const field = (_opts$field6 = opts.field) !== null && _opts$field6 !== void 0 ? _opts$field6 : 'expiresAt';
1591
+ const sudo = context.sudo();
1592
+ const expired = await sudo.db[listKey].findMany({
1593
+ where: {
1594
+ [field]: {
1595
+ lte: new Date()
1596
+ }
1597
+ }
1598
+ });
1599
+ for (const item of expired) {
1600
+ await sudo.db[listKey].deleteOne({
1601
+ where: {
1602
+ id: String(item.id)
1603
+ }
1604
+ });
1605
+ }
1606
+ return expired.length;
1607
+ }
1608
+
1609
+ /**
1610
+ * Adds a read-only `viewCount` integer. Increment it with `recordView()` — a direct,
1611
+ * race-safe Prisma increment that bypasses hooks (a view is not an editorial change).
1612
+ */
1613
+ function withViewCount(opts = {}) {
1614
+ var _opts$field7;
1615
+ const field = (_opts$field7 = opts.field) !== null && _opts$field7 !== void 0 ? _opts$field7 : 'viewCount';
1616
+ return {
1617
+ fields: {
1618
+ [field]: index$1.integer({
1619
+ defaultValue: 0,
1620
+ ui: {
1621
+ createView: {
1622
+ fieldMode: 'hidden'
1623
+ },
1624
+ itemView: {
1625
+ fieldMode: 'read'
1626
+ }
1627
+ }
1628
+ })
1629
+ }
1630
+ };
1631
+ }
1632
+
1633
+ /** Increment an item's view counter (see `withViewCount`). */
1634
+ async function recordView(context, listKey, itemId, opts = {}) {
1635
+ var _opts$field8, _context$prisma;
1636
+ const field = (_opts$field8 = opts.field) !== null && _opts$field8 !== void 0 ? _opts$field8 : 'viewCount';
1637
+ const model = (_context$prisma = context.prisma) === null || _context$prisma === void 0 ? void 0 : _context$prisma[listKey[0].toLowerCase() + listKey.slice(1)];
1638
+ if (!model) throw new Error(`recordView: collection "${listKey}" was not found in the Prisma client`);
1639
+ await model.update({
1640
+ where: {
1641
+ id: itemId
1642
+ },
1643
+ data: {
1644
+ [field]: {
1645
+ increment: 1
1646
+ }
1647
+ }
1648
+ });
1649
+ }
1650
+
1651
+ /**
1652
+ * Companion to cascade rules: sweep records whose to-one relationship points at
1653
+ * nothing (e.g. rows that pre-date a cascade rule, or were orphaned by `setNull`).
1654
+ * Runs normal delete hooks (so cascade rules fire too). Designed for a cron job.
1655
+ *
1656
+ * @example
1657
+ * jobs: createJobs({ jobs: [{
1658
+ * name: 'orphan-cleanup',
1659
+ * schedule: '0 4 * * *',
1660
+ * handler: async () => { await cleanupOrphans(getContext(), { collection: 'Comment', field: 'post' }) },
1661
+ * }]})
1662
+ */
1663
+ async function cleanupOrphans(context, options) {
1664
+ var _options$softDeleteFi;
1665
+ const {
1666
+ collection,
1667
+ field,
1668
+ action = 'delete'
1669
+ } = options;
1670
+ const softDeleteField = (_options$softDeleteFi = options.softDeleteField) !== null && _options$softDeleteFi !== void 0 ? _options$softDeleteFi : 'deletedAt';
1671
+ const sudo = context.sudo();
1672
+ const where = action === 'softDelete' ? {
1673
+ [field]: null,
1674
+ [softDeleteField]: null
1675
+ } : {
1676
+ [field]: null
1677
+ };
1678
+ let total = 0;
1679
+ for (;;) {
1680
+ const orphans = await sudo.db[collection].findMany({
1681
+ where,
1682
+ take: 100
1683
+ });
1684
+ if (!orphans.length) break;
1685
+ for (const orphan of orphans) {
1686
+ if (action === 'delete') {
1687
+ await sudo.db[collection].deleteOne({
1688
+ where: {
1689
+ id: String(orphan.id)
1690
+ }
1691
+ });
1692
+ } else {
1693
+ await sudo.db[collection].updateOne({
1694
+ where: {
1695
+ id: String(orphan.id)
1696
+ },
1697
+ data: {
1698
+ [softDeleteField]: new Date().toISOString()
1699
+ }
1700
+ });
1701
+ }
1702
+ total++;
1703
+ }
1704
+ if (orphans.length < 100) break;
1705
+ }
1706
+ return total;
1707
+ }
1708
+
398
1709
  /**
399
1710
  * Factory for building reusable field group mixins.
400
1711
  *
@@ -413,14 +1724,14 @@ function createMixin(fields, hooks) {
413
1724
  }
414
1725
 
415
1726
  // ================================================================
416
- // defineList — a typed wrapper around list() with mixin support
1727
+ // defineCollection — a typed wrapper around list() with mixin support
417
1728
  // ================================================================
418
1729
 
419
1730
  /**
420
1731
  * Defines a list with optional mixins for reusable field groups and hooks.
421
1732
  *
422
1733
  * @example
423
- * export const Post = defineList({
1734
+ * export const Post = defineCollection({
424
1735
  * mixins: [withTimestamps()],
425
1736
  * fields: {
426
1737
  * title: text({ validation: validators.required }),
@@ -428,9 +1739,18 @@ function createMixin(fields, hooks) {
428
1739
  * },
429
1740
  * })
430
1741
  */
431
- function defineList(config) {
1742
+ function defineCollection(config) {
432
1743
  const {
433
1744
  mixins = [],
1745
+ access,
1746
+ computed,
1747
+ constraints,
1748
+ defaultFilter,
1749
+ stateMachine,
1750
+ policies,
1751
+ events,
1752
+ searchable,
1753
+ versioned,
434
1754
  ...listConfig
435
1755
  } = config;
436
1756
  const mixinFields = {};
@@ -439,9 +1759,26 @@ function defineList(config) {
439
1759
  if (mixin.fields) Object.assign(mixinFields, mixin.fields);
440
1760
  if (mixin.hooks) mixinHooksList.push(mixin.hooks);
441
1761
  }
442
- const mergedHooks = mergeMixinHooks(mixinHooksList, listConfig.hooks);
443
- return list({
1762
+
1763
+ // Feature hooks run AFTER mixin + user hooks so computed fields and constraint checks
1764
+ // observe the final resolved data, and events/search/version snapshots fire last.
1765
+ const featureHooks = compileFeatureHooks({
1766
+ computed,
1767
+ constraints,
1768
+ stateMachine,
1769
+ events,
1770
+ searchable,
1771
+ versioned
1772
+ });
1773
+ const mergedHooks = mergeMixinHooks(mixinHooksList, listConfig.hooks, featureHooks);
1774
+ const baseAccess = access !== null && access !== void 0 ? access : accessPresets.public;
1775
+ const finalAccess = applyAccessFeatures(baseAccess, {
1776
+ defaultFilter,
1777
+ policies
1778
+ });
1779
+ return collection({
444
1780
  ...listConfig,
1781
+ access: finalAccess,
445
1782
  fields: {
446
1783
  ...mixinFields,
447
1784
  ...listConfig.fields
@@ -486,13 +1823,13 @@ function mergeResolveInput(a, b) {
486
1823
  }
487
1824
 
488
1825
  /**
489
- * Merge mixin hooks with the list's own hooks. Each Keystone hook may be either a function or a
1826
+ * Merge mixin hooks with the list's own hooks. Each list hook may be either a function or a
490
1827
  * `{ create, update, delete }` object — `merge` (from resolve-hooks) handles both forms for the
491
1828
  * void hooks, and `mergeResolveInput` handles the data-threading `resolveInput` hook.
492
1829
  */
493
- function mergeMixinHooks(mixinHooks, listHooks) {
494
- if (mixinHooks.length === 0) return listHooks !== null && listHooks !== void 0 ? listHooks : {};
495
- const all = [...mixinHooks, ...(listHooks ? [listHooks] : [])];
1830
+ function mergeMixinHooks(mixinHooks, listHooks, featureHooks = []) {
1831
+ if (mixinHooks.length === 0 && featureHooks.length === 0) return listHooks !== null && listHooks !== void 0 ? listHooks : {};
1832
+ const all = [...mixinHooks, ...(listHooks ? [listHooks] : []), ...featureHooks];
496
1833
  const merged = {};
497
1834
  for (const hooks of all) {
498
1835
  merged.resolveInput = mergeResolveInput(merged.resolveInput, hooks.resolveInput);
@@ -518,7 +1855,7 @@ function mergeMixinHooks(mixinHooks, listHooks) {
518
1855
  * })
519
1856
  */
520
1857
  function defineConfig(nixxieConfig) {
521
- return config(nixxieConfig);
1858
+ return buildConfig(nixxieConfig);
522
1859
  }
523
1860
 
524
1861
  // ================================================================
@@ -529,21 +1866,42 @@ function defineConfig(nixxieConfig) {
529
1866
  * Defines a list action. Typed alias for `action()`.
530
1867
  */
531
1868
  function defineAction(actionConfig) {
532
- return action(actionConfig);
1869
+ return createAction(actionConfig);
533
1870
  }
534
1871
 
1872
+ exports.previewDelete = resolveHooks.previewDelete;
535
1873
  exports.g = nextFields.g;
536
1874
  exports.gWithContext = nextFields.gWithContext;
537
1875
  exports.graphql = nextFields.g;
538
- exports.action = action;
539
- exports.config = config;
1876
+ exports.accessPresets = accessPresets;
1877
+ exports.applyScheduledPublishing = applyScheduledPublishing;
1878
+ exports.approveChanges = approveChanges;
1879
+ exports.cleanupOrphans = cleanupOrphans;
1880
+ exports.collection = collection;
1881
+ exports.createAction = createAction;
540
1882
  exports.createMixin = createMixin;
541
1883
  exports.defineAction = defineAction;
1884
+ exports.defineCollection = defineCollection;
542
1885
  exports.defineConfig = defineConfig;
543
- exports.defineList = defineList;
544
- exports.group = group;
545
- exports.list = list;
1886
+ exports.fieldGroup = fieldGroup;
1887
+ exports.purgeExpired = purgeExpired;
1888
+ exports.recordView = recordView;
1889
+ exports.rejectChanges = rejectChanges;
1890
+ exports.submitForApproval = submitForApproval;
1891
+ exports.tenantAccessFilter = tenantAccessFilter;
1892
+ exports.validateEnv = validateEnv;
546
1893
  exports.validators = validators;
1894
+ exports.withApproval = withApproval;
547
1895
  exports.withAudit = withAudit;
1896
+ exports.withExpiry = withExpiry;
1897
+ exports.withLocale = withLocale;
1898
+ exports.withPublishing = withPublishing;
1899
+ exports.withSEO = withSEO;
1900
+ exports.withScheduledPublishing = withScheduledPublishing;
1901
+ exports.withSlug = withSlug;
548
1902
  exports.withSoftDelete = withSoftDelete;
1903
+ exports.withSortable = withSortable;
1904
+ exports.withTenant = withTenant;
549
1905
  exports.withTimestamps = withTimestamps;
1906
+ exports.withTreeStructure = withTreeStructure;
1907
+ exports.withViewCount = withViewCount;