lkb-fields-document 1.0.0 → 1.0.1

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 (109) hide show
  1. package/component-blocks/dist/lkb-fields-document-component-blocks.cjs.d.ts +2 -2
  2. package/component-blocks/dist/lkb-fields-document-component-blocks.cjs.js +16 -306
  3. package/component-blocks/dist/lkb-fields-document-component-blocks.node.cjs.js +16 -306
  4. package/dist/lkb-fields-document.cjs.d.ts +2 -2
  5. package/dist/lkb-fields-document.cjs.js +16 -1167
  6. package/dist/lkb-fields-document.node.cjs.js +16 -1167
  7. package/package.json +6 -6
  8. package/structure-views/dist/lkb-fields-document-structure-views.cjs.d.ts +2 -2
  9. package/structure-views/dist/lkb-fields-document-structure-views.cjs.js +16 -138
  10. package/structure-views/dist/lkb-fields-document-structure-views.node.cjs.js +16 -138
  11. package/views/dist/lkb-fields-document-views.cjs.d.ts +2 -2
  12. package/views/dist/lkb-fields-document-views.cjs.js +13 -111
  13. package/views/dist/lkb-fields-document-views.node.cjs.js +13 -111
  14. package/component-blocks/dist/lkb-fields-document-component-blocks.esm.js +0 -300
  15. package/component-blocks/dist/lkb-fields-document-component-blocks.node.esm.js +0 -300
  16. package/dist/Cell-0ac0ac66.node.cjs.js +0 -21
  17. package/dist/Cell-242f7404.esm.js +0 -17
  18. package/dist/Cell-3103f73d.node.esm.js +0 -17
  19. package/dist/Cell-bfb56d74.cjs.js +0 -21
  20. package/dist/Field-0e0f75ed.node.cjs.js +0 -1628
  21. package/dist/Field-28177061.cjs.js +0 -1628
  22. package/dist/Field-35b79e6b.node.esm.js +0 -1619
  23. package/dist/Field-92d13205.esm.js +0 -1619
  24. package/dist/api-2f524611.esm.js +0 -502
  25. package/dist/api-73636987.cjs.js +0 -506
  26. package/dist/api-8e2b20b8.node.cjs.js +0 -506
  27. package/dist/api-c32e360e.node.esm.js +0 -502
  28. package/dist/callout-ui-2aded278.cjs.js +0 -131
  29. package/dist/callout-ui-3e5ca544.node.esm.js +0 -126
  30. package/dist/callout-ui-8b5f2376.esm.js +0 -126
  31. package/dist/callout-ui-ad50f301.node.cjs.js +0 -131
  32. package/dist/declarations/src/component-blocks.d.ts +0 -4
  33. package/dist/declarations/src/component-blocks.d.ts.map +0 -1
  34. package/dist/declarations/src/document-editor/component-blocks/api.d.ts +0 -120
  35. package/dist/declarations/src/document-editor/component-blocks/api.d.ts.map +0 -1
  36. package/dist/declarations/src/document-editor/component-blocks/types.d.ts +0 -241
  37. package/dist/declarations/src/document-editor/component-blocks/types.d.ts.map +0 -1
  38. package/dist/declarations/src/document-editor/toolset/relationship/relationship-shared.d.ts +0 -10
  39. package/dist/declarations/src/document-editor/toolset/relationship/relationship-shared.d.ts.map +0 -1
  40. package/dist/declarations/src/index.d.ts +0 -7
  41. package/dist/declarations/src/index.d.ts.map +0 -1
  42. package/dist/declarations/src/my-component-blocks/index.d.ts +0 -46
  43. package/dist/declarations/src/my-component-blocks/index.d.ts.map +0 -1
  44. package/dist/declarations/src/structure/Cell.d.ts +0 -5
  45. package/dist/declarations/src/structure/Cell.d.ts.map +0 -1
  46. package/dist/declarations/src/structure/Field.d.ts +0 -5
  47. package/dist/declarations/src/structure/Field.d.ts.map +0 -1
  48. package/dist/declarations/src/structure/controller.d.ts +0 -10
  49. package/dist/declarations/src/structure/controller.d.ts.map +0 -1
  50. package/dist/declarations/src/structure/structure.d.ts +0 -4
  51. package/dist/declarations/src/structure/structure.d.ts.map +0 -1
  52. package/dist/declarations/src/structure-views.d.ts +0 -5
  53. package/dist/declarations/src/structure-views.d.ts.map +0 -1
  54. package/dist/declarations/src/types/DocumentFeatures.d.ts +0 -33
  55. package/dist/declarations/src/types/DocumentFeatures.d.ts.map +0 -1
  56. package/dist/declarations/src/types/DocumentFieldConfig.d.ts +0 -18
  57. package/dist/declarations/src/types/DocumentFieldConfig.d.ts.map +0 -1
  58. package/dist/declarations/src/types/FormattingConfig.d.ts +0 -28
  59. package/dist/declarations/src/types/FormattingConfig.d.ts.map +0 -1
  60. package/dist/declarations/src/types/RelationshipsConfig.d.ts +0 -9
  61. package/dist/declarations/src/types/RelationshipsConfig.d.ts.map +0 -1
  62. package/dist/declarations/src/types/StructureFieldConfig.d.ts +0 -10
  63. package/dist/declarations/src/types/StructureFieldConfig.d.ts.map +0 -1
  64. package/dist/declarations/src/validation/structure-validation.d.ts +0 -218
  65. package/dist/declarations/src/validation/structure-validation.d.ts.map +0 -1
  66. package/dist/declarations/src/views/Cell.d.ts +0 -5
  67. package/dist/declarations/src/views/Cell.d.ts.map +0 -1
  68. package/dist/declarations/src/views/Field.d.ts +0 -5
  69. package/dist/declarations/src/views/Field.d.ts.map +0 -1
  70. package/dist/declarations/src/views/controller.d.ts +0 -15
  71. package/dist/declarations/src/views/controller.d.ts.map +0 -1
  72. package/dist/declarations/src/views/document.d.ts +0 -4
  73. package/dist/declarations/src/views/document.d.ts.map +0 -1
  74. package/dist/declarations/src/views.d.ts +0 -7
  75. package/dist/declarations/src/views.d.ts.map +0 -1
  76. package/dist/editor-shared-a6e340e6.node.esm.js +0 -1993
  77. package/dist/editor-shared-a997ae98.node.cjs.js +0 -2007
  78. package/dist/editor-shared-cc1293ed.cjs.js +0 -2007
  79. package/dist/editor-shared-da518ba3.esm.js +0 -1993
  80. package/dist/form-from-preview-2042b9ef.cjs.js +0 -512
  81. package/dist/form-from-preview-5df6e492.node.esm.js +0 -508
  82. package/dist/form-from-preview-9e501058.node.cjs.js +0 -512
  83. package/dist/form-from-preview-b3a66f37.esm.js +0 -508
  84. package/dist/index-06c36775.cjs.js +0 -14
  85. package/dist/index-586adb8f.node.esm.js +0 -11
  86. package/dist/index-67d52357.esm.js +0 -11
  87. package/dist/index-c3223fdc.node.cjs.js +0 -14
  88. package/dist/layouts-6412fa2a.esm.js +0 -189
  89. package/dist/layouts-a4a3cf0b.node.cjs.js +0 -196
  90. package/dist/layouts-ba9a558b.cjs.js +0 -196
  91. package/dist/layouts-e653b908.node.esm.js +0 -189
  92. package/dist/lkb-fields-document.esm.js +0 -1162
  93. package/dist/lkb-fields-document.node.esm.js +0 -1162
  94. package/dist/shared-0533009e.cjs.js +0 -594
  95. package/dist/shared-4684cc24.node.cjs.js +0 -594
  96. package/dist/shared-5e864055.node.esm.js +0 -579
  97. package/dist/shared-aaba5901.esm.js +0 -579
  98. package/dist/toolbar-state-3359e2f3.cjs.js +0 -994
  99. package/dist/toolbar-state-945823b8.node.esm.js +0 -971
  100. package/dist/toolbar-state-9611743f.node.cjs.js +0 -994
  101. package/dist/toolbar-state-bc8fe661.esm.js +0 -971
  102. package/dist/utils-06bcddc4.node.cjs.js +0 -747
  103. package/dist/utils-200ff260.node.esm.js +0 -722
  104. package/dist/utils-6409f730.cjs.js +0 -747
  105. package/dist/utils-bc6a0b82.esm.js +0 -722
  106. package/structure-views/dist/lkb-fields-document-structure-views.esm.js +0 -131
  107. package/structure-views/dist/lkb-fields-document-structure-views.node.esm.js +0 -131
  108. package/views/dist/lkb-fields-document-views.esm.js +0 -95
  109. package/views/dist/lkb-fields-document-views.node.esm.js +0 -95
@@ -1,1167 +1,16 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var lkbCore = require('lkb-core');
6
- var types = require('lkb-core/types');
7
- var graphql = require('graphql');
8
- var utils = require('./utils-06bcddc4.node.cjs.js');
9
- var slate = require('slate');
10
- var editorShared = require('./editor-shared-a997ae98.node.cjs.js');
11
- var zod = require('zod');
12
- var index = require('./index-c3223fdc.node.cjs.js');
13
- require('slate-history');
14
- require('@emotion/weak-memoize');
15
- require('./shared-4684cc24.node.cjs.js');
16
- require('mdast-util-from-markdown');
17
- require('mdast-util-gfm-autolink-literal/from-markdown');
18
- require('micromark-extension-gfm-autolink-literal');
19
- require('mdast-util-gfm-strikethrough/from-markdown');
20
- require('micromark-extension-gfm-strikethrough');
21
- require('@braintree/sanitize-url');
22
-
23
- function assertValidComponentSchema(schema, lists, mode) {
24
- assertValidComponentSchemaInner(schema, [], [], new Set(), lists, mode);
25
- }
26
-
27
- // recursive things can exist but they have to either be:
28
- // - inside the non-default portion of a conditional field
29
- // - inside an array field
30
- // when we hit the non-default portion of a conditional field or an array field
31
- // checking inside of it essentially means pretend it's a new thing
32
- function assertValidComponentSchemaInner(schema, schemaAncestors, propPath, seenProps, lists, mode) {
33
- if (schema.kind === 'form') {
34
- if (mode === 'structure' && !schema.graphql) {
35
- throw new Error(`There is a form field without a configured GraphQL schema at "${propPath.join('.')}", fields used in the structure field must have a GraphQL schema.`);
36
- }
37
- return;
38
- }
39
- if (schema.kind === 'child') {
40
- if (mode === 'structure') {
41
- throw new Error(`There is a child field at "${propPath.join('.')}" but child fields are not allowed in structure fields.`);
42
- }
43
- return;
44
- }
45
- if (schema.kind === 'relationship') {
46
- if (lists.has(schema.listKey)) {
47
- return;
48
- }
49
- throw new Error(`The relationship field at "${propPath.join('.')}" has the listKey "${schema.listKey}" but no list named "${schema.listKey}" exists.`);
50
- }
51
- const ancestor = schemaAncestors.indexOf(schema);
52
- if (ancestor !== -1) {
53
- throw new Error(`The field "${propPath.join('.')}" is the same as it's ancestor. Use an array or conditional field for recursive structures.`);
54
- }
55
- if (seenProps.has(schema)) {
56
- return;
57
- }
58
- propPath.push(schema.kind);
59
- try {
60
- seenProps.add(schema);
61
- if (schema.kind === 'array') {
62
- assertValidComponentSchemaInner(schema.element, [], propPath, seenProps, lists, mode);
63
- return;
64
- }
65
- if (schema.kind === 'object') {
66
- schemaAncestors.push(schema);
67
- for (const [key, innerProp] of Object.entries(schema.fields)) {
68
- propPath.push(key);
69
- if (schema.fields[key] !== innerProp) {
70
- throw new Error(`Fields on an object field must not change over time but the field at "${propPath.join('.')}" changes between accesses`);
71
- }
72
- assertValidComponentSchemaInner(innerProp, schemaAncestors, propPath, seenProps, lists, mode);
73
- propPath.pop();
74
- }
75
- schemaAncestors.pop();
76
- return;
77
- }
78
- if (schema.kind === 'conditional') {
79
- schemaAncestors.push(schema);
80
- const stringifiedDefaultDiscriminant = schema.discriminant.defaultValue.toString();
81
- for (const [key, innerProp] of Object.entries(schema.values)) {
82
- propPath.push(key);
83
- if (schema.values[key] !== innerProp) {
84
- throw new Error(`Fields on a conditional field must not change over time but the field at "${propPath.join('.')}" changes between accesses`);
85
- }
86
- assertValidComponentSchemaInner(innerProp, key === stringifiedDefaultDiscriminant ? schemaAncestors : [], propPath, seenProps, lists, mode);
87
- propPath.pop();
88
- }
89
- schemaAncestors.pop();
90
- return;
91
- }
92
- } finally {
93
- propPath.pop();
94
- }
95
- utils.assertNever(schema);
96
- }
97
-
98
- const labelFieldAlias = '____document_field_relationship_item_label';
99
- const idFieldAlias = '____document_field_relationship_item_id';
100
- function addRelationshipData(nodes, context, relationships, componentBlocks) {
101
- return Promise.all(nodes === null || nodes === void 0 ? void 0 : nodes.map(async node => {
102
- if (node.type === 'relationship') {
103
- const relationship = relationships[node.relationship];
104
- if (!relationship) return node;
105
- return {
106
- ...node,
107
- data: await fetchDataForOne(context, {
108
- ...relationship,
109
- many: false
110
- }, node.data)
111
- };
112
- }
113
- if (node.type === 'component-block') {
114
- const componentBlock = componentBlocks[node.component];
115
- if (componentBlock) {
116
- const [props, children] = await Promise.all([addRelationshipDataToComponentProps({
117
- kind: 'object',
118
- fields: componentBlock.schema
119
- }, node.props, (relationship, data) => fetchRelationshipData(context, relationship, data)), addRelationshipData(node.children, context, relationships, componentBlocks)]);
120
- return {
121
- ...node,
122
- props,
123
- children
124
- };
125
- }
126
- }
127
- if ('children' in node && Array.isArray(node.children)) {
128
- return {
129
- ...node,
130
- children: await addRelationshipData(node.children, context, relationships, componentBlocks)
131
- };
132
- }
133
- return node;
134
- }));
135
- }
136
- async function fetchRelationshipData(context, relationship, data) {
137
- var _relationship$labelFi;
138
- if (!relationship.many) return fetchDataForOne(context, relationship, data);
139
- const ids = Array.isArray(data) ? data.filter(item => item.id != null).map(x => x.id) : [];
140
- if (!ids.length) return [];
141
- const list = context.__internal.lists[relationship.listKey];
142
- const {
143
- listQueryName
144
- } = list.graphql.names;
145
- const labelField = (_relationship$labelFi = relationship.labelField) !== null && _relationship$labelFi !== void 0 ? _relationship$labelFi : list.ui.labelField;
146
- const value = await context.graphql.run({
147
- query: `query($ids: [ID!]!) {items:${listQueryName}(where: { id: { in: $ids } }) {${idFieldAlias}:id ${labelFieldAlias}:${labelField}\n${relationship.selection || ''}}}`,
148
- variables: {
149
- ids
150
- }
151
- });
152
- return Array.isArray(value.items) ? value.items.map(({
153
- [labelFieldAlias]: label,
154
- [idFieldAlias]: id,
155
- ...data
156
- }) => {
157
- return {
158
- id,
159
- label,
160
- data
161
- };
162
- }) : [];
163
- }
164
- async function fetchDataForOne(context, relationship, data) {
165
- var _relationship$labelFi2;
166
- // Single related item
167
- const id = data === null || data === void 0 ? void 0 : data.id;
168
- if (id == null) return null;
169
-
170
- // An exception here indicates something wrong with either the system or the
171
- // configuration (e.g. a bad selection field). These will surface as system
172
- // errors from the GraphQL field resolver.
173
- const list = context.__internal.lists[relationship.listKey];
174
- const {
175
- itemQueryName
176
- } = list.graphql.names;
177
- const labelField = (_relationship$labelFi2 = relationship.labelField) !== null && _relationship$labelFi2 !== void 0 ? _relationship$labelFi2 : list.ui.labelField;
178
- const value = await context.graphql.run({
179
- query: `query($id: ID!) {item:${itemQueryName}(where: { id: $id }) {${labelFieldAlias}:${labelField}\n${relationship.selection || ''}}}`,
180
- variables: {
181
- id
182
- }
183
- });
184
- if (value.item === null) return {
185
- id,
186
- data: undefined,
187
- label: undefined
188
- };
189
- return {
190
- id,
191
- label: value.item[labelFieldAlias],
192
- data: (() => {
193
- const {
194
- [labelFieldAlias]: _ignore,
195
- ...otherData
196
- } = value.item;
197
- return otherData;
198
- })()
199
- };
200
- }
201
- async function addRelationshipDataToComponentProps(schema, value, fetchData) {
202
- switch (schema.kind) {
203
- case 'child':
204
- return value;
205
- case 'form':
206
- return value;
207
- case 'relationship':
208
- return fetchData(schema, value);
209
- case 'object':
210
- {
211
- return Object.fromEntries(await Promise.all(Object.keys(schema.fields).map(async key => [key,
212
- // if val[key] === undefined, we know a new field was added to the schema
213
- // but there is old data in the database that doesn't have the new field
214
- // we're intentionally not just magically adding it because we may want to
215
- // have a more optimised strategy of hydrating relationships so we don't
216
- // want to add something unrelated that requires the current "traverse everything" strategy
217
- value[key] === undefined ? undefined : await addRelationshipDataToComponentProps(schema.fields[key], value[key], fetchData)])));
218
- }
219
- case 'conditional':
220
- {
221
- return {
222
- discriminant: value.discriminant,
223
- value: await addRelationshipDataToComponentProps(schema.values[value.discriminant], value.value, fetchData)
224
- };
225
- }
226
- case 'array':
227
- {
228
- return await Promise.all(value.map(async innerVal => addRelationshipDataToComponentProps(schema.element, innerVal, fetchData)));
229
- }
230
- }
231
- utils.assertNever(schema);
232
- }
233
-
234
- // leaf types
235
- const zMarkValue = zod.z.union([zod.z.literal(true), zod.z.undefined()]);
236
- const zText = zod.z.object({
237
- type: zod.z.never().optional(),
238
- text: zod.z.string(),
239
- bold: zMarkValue,
240
- italic: zMarkValue,
241
- underline: zMarkValue,
242
- strikethrough: zMarkValue,
243
- code: zMarkValue,
244
- superscript: zMarkValue,
245
- subscript: zMarkValue,
246
- keyboard: zMarkValue,
247
- insertMenu: zMarkValue
248
- }).strict();
249
- const zTextAlign = zod.z.union([zod.z.undefined(), zod.z.literal('center'), zod.z.literal('end')]);
250
-
251
- // recursive types
252
- const zLink = zod.z.object({
253
- type: zod.z.literal('link'),
254
- href: zod.z.string().refinement(index.isValidURL, val => ({
255
- code: 'custom',
256
- message: `Invalid URL: ${val}`
257
- }))
258
- }).strict();
259
- const zHeading = zod.z.object({
260
- type: zod.z.literal('heading'),
261
- textAlign: zTextAlign,
262
- level: zod.z.union([zod.z.literal(1), zod.z.literal(2), zod.z.literal(3), zod.z.literal(4), zod.z.literal(5), zod.z.literal(6)])
263
- }).strict();
264
- const zParagraph = zod.z.object({
265
- type: zod.z.literal('paragraph'),
266
- textAlign: zTextAlign
267
- }).strict();
268
- const zBasicElement = type => zod.z.object({
269
- type: zod.z.literal(type)
270
- }).strict();
271
- const zBasicElements = [zBasicElement('blockquote'), zBasicElement('layout-area'), zBasicElement('code'), zBasicElement('divider'), zBasicElement('list-item'), zBasicElement('list-item-content'), zBasicElement('ordered-list'), zBasicElement('unordered-list')];
272
- const zLayout = zod.z.object({
273
- type: zod.z.literal('layout'),
274
- layout: zod.z.array(zod.z.number())
275
- }).strict();
276
- const zRelationshipData = zod.z.object({
277
- id: zod.z.string(),
278
- label: zod.z.string().optional(),
279
- data: zod.z.record(zod.z.string(), zod.z.any()).optional()
280
- }).strict();
281
- const zRelationship = zod.z.object({
282
- type: zod.z.literal('relationship'),
283
- relationship: zod.z.string(),
284
- data: zod.z.union([zRelationshipData, zod.z.null()])
285
- }).strict();
286
- const zComponentBlock = zod.z.object({
287
- type: zod.z.literal('component-block'),
288
- component: zod.z.string(),
289
- props: zod.z.record(zod.z.string(), zod.z.any())
290
- }).strict();
291
- const zComponentProp = type => zod.z.object({
292
- type: zod.z.literal(type),
293
- propPath: zod.z.array(zod.z.union([zod.z.string(), zod.z.number()])).optional()
294
- }).strict();
295
- const zComponentProps = [zComponentProp('component-block-prop'), zComponentProp('component-inline-prop')];
296
- const zBlock = zod.z.discriminatedUnion('type', [zComponentBlock.extend({
297
- children: zod.z.lazy(() => zChildren)
298
- }), ...zComponentProps.map(prop => prop.extend({
299
- children: zod.z.lazy(() => zChildren)
300
- })), ...zBasicElements.map(prop => prop.extend({
301
- children: zod.z.lazy(() => zChildren)
302
- })), zHeading.extend({
303
- children: zod.z.lazy(() => zChildren)
304
- }), zLayout.extend({
305
- children: zod.z.lazy(() => zChildren)
306
- }), zParagraph.extend({
307
- children: zod.z.lazy(() => zChildren)
308
- })]);
309
- const zInline = zod.z.discriminatedUnion('type', [zText, zLink.extend({
310
- children: zod.z.lazy(() => zChildren)
311
- }), zRelationship.extend({
312
- children: zod.z.lazy(() => zChildren)
313
- })]);
314
- const zChildren = zod.z.array(zod.z.union([zBlock, zInline]));
315
- const zDocument = zod.z.array(zBlock);
316
-
317
- // exports
318
-
319
- function isRelationshipData(value) {
320
- return zRelationshipData.safeParse(value).success;
321
- }
322
- function validateDocumentStructure(value) {
323
- const result = zDocument.safeParse(value);
324
- if (!result.success) {
325
- throw new Error(`Invalid document structure: ${result.error.message}`);
326
- }
327
- }
328
-
329
- class PropValidationError extends Error {
330
- constructor(message, path) {
331
- super(`${message} at ${path.join('.')}`);
332
- this.path = path;
333
- }
334
- }
335
- function validateComponentBlockProps(schema, value, relationships, path) {
336
- if (schema.kind === 'form') {
337
- value = value === undefined ? schema.defaultValue : value;
338
- if (schema.validate(value)) {
339
- return value;
340
- }
341
- throw new PropValidationError(`Invalid form prop value: ${JSON.stringify(value)}`, path);
342
- }
343
- if (schema.kind === 'child') {
344
- return null;
345
- }
346
- if (schema.kind === 'relationship') {
347
- if (schema.many) {
348
- if (Array.isArray(value) && value.every(isRelationshipData)) {
349
- // yes, ts understands this completely correctly, i'm as suprised as you are
350
- return value.map(x => ({
351
- id: x.id
352
- }));
353
- } else {
354
- throw new PropValidationError(`Invalid relationship value: ${JSON.stringify(value)}`, path);
355
- }
356
- }
357
- if (value === null || isRelationshipData(value)) {
358
- return value === null ? null : {
359
- id: value.id
360
- };
361
- } else {
362
- throw new PropValidationError(`Invalid relationship value: ${JSON.stringify(value)}`, path);
363
- }
364
- }
365
- if (schema.kind === 'conditional') {
366
- if (typeof value !== 'object' || value === null) {
367
- throw new PropValidationError(`Conditional value must be an object but is ${typeof value}`, path);
368
- }
369
- for (const key of Object.keys(value)) {
370
- if (key !== 'discriminant' && key !== 'value') {
371
- throw new PropValidationError(`Conditional value only allows keys named "discriminant" and "value", not "${key}"`, path);
372
- }
373
- }
374
- const discriminant = value.discriminant;
375
- const val = value.value;
376
- // for some reason mongo or mongoose or something is saving undefined as null
377
- // so we're doing this so that we avoid setting undefined on objects
378
- const obj = {};
379
- const discriminantVal = validateComponentBlockProps(schema.discriminant, discriminant, relationships, path.concat('discriminant'));
380
- if (discriminantVal !== undefined) {
381
- obj.discriminant = discriminantVal;
382
- }
383
- const conditionalFieldValue = validateComponentBlockProps(schema.values[discriminant], val, relationships, path.concat('value'));
384
- if (conditionalFieldValue !== undefined) {
385
- obj.value = conditionalFieldValue;
386
- }
387
- return obj;
388
- }
389
- if (schema.kind === 'object') {
390
- if (typeof value !== 'object' || value === null) {
391
- throw new PropValidationError(`Object value must be an object but is ${typeof value}`, path);
392
- }
393
- const val = {};
394
- for (const key of Object.keys(schema.fields)) {
395
- const propVal = validateComponentBlockProps(schema.fields[key], value[key], relationships, path.concat(key));
396
- // for some reason mongo or mongoose or something is saving undefined as null
397
- // so we're doing this so that we avoid setting undefined on objects
398
- if (propVal !== undefined) {
399
- val[key] = propVal;
400
- }
401
- }
402
- return val;
403
- }
404
- if (schema.kind === 'array') {
405
- if (!Array.isArray(value)) {
406
- throw new PropValidationError(`Array field value must be an array but is ${typeof value}`, path);
407
- }
408
- return value.map((innerVal, i) => {
409
- return validateComponentBlockProps(schema.element, innerVal, relationships, path.concat(i));
410
- });
411
- }
412
- utils.assertNever(schema);
413
- }
414
- function isText(node) {
415
- return slate.Text.isText(node);
416
- }
417
-
418
- // note that the errors thrown from here will only be exposed
419
- // as internal server error from the graphql api in prod
420
- // this is fine because these cases are pretty much all about
421
- // malicious content being inserted, not valid content
422
- function getValidatedNodeWithNormalizedComponentFormProps(node, componentBlocks, relationships) {
423
- if (isText(node)) return node;
424
- if (node.type === 'component-block') {
425
- if (Object.prototype.hasOwnProperty.call(componentBlocks, node.component)) {
426
- const componentBlock = componentBlocks[node.component];
427
- node = {
428
- ...node,
429
- props: validateComponentBlockProps({
430
- kind: 'object',
431
- fields: componentBlock.schema
432
- }, node.props, relationships, [])
433
- };
434
- }
435
- }
436
- if (node.type === 'relationship') {
437
- var _node$data;
438
- node = {
439
- type: 'relationship',
440
- data: ((_node$data = node.data) === null || _node$data === void 0 ? void 0 : _node$data.id) !== undefined ? {
441
- id: node.data.id,
442
- data: undefined,
443
- label: undefined
444
- } : null,
445
- relationship: node.relationship,
446
- children: node.children
447
- };
448
- }
449
- return {
450
- ...node,
451
- children: node.children.map(x => getValidatedNodeWithNormalizedComponentFormProps(x, componentBlocks, relationships))
452
- };
453
- }
454
- function validateAndNormalizeDocument(value, documentFeatures, componentBlocks, relationships) {
455
- validateDocumentStructure(value);
456
- const children = value.map(x => getValidatedNodeWithNormalizedComponentFormProps(x, componentBlocks, relationships));
457
- const editor = editorShared.createDocumentEditor(documentFeatures, componentBlocks, relationships);
458
- editor.children = children;
459
- slate.Editor.normalize(editor, {
460
- force: true
461
- });
462
- return editor.children;
463
- }
464
-
465
- function normaliseDocumentFeatures(config) {
466
- var _config$formatting;
467
- const {
468
- alignment,
469
- blockTypes,
470
- headingLevels,
471
- inlineMarks,
472
- listTypes,
473
- softBreaks
474
- } = typeof config.formatting === 'boolean' ? {
475
- alignment: config.formatting,
476
- blockTypes: config.formatting,
477
- headingLevels: config.formatting,
478
- inlineMarks: config.formatting,
479
- listTypes: config.formatting,
480
- softBreaks: config.formatting
481
- } : (_config$formatting = config.formatting) !== null && _config$formatting !== void 0 ? _config$formatting : {};
482
- const documentFeatures = {
483
- formatting: {
484
- alignment: {
485
- center: typeof alignment === 'boolean' ? alignment : !!(alignment !== null && alignment !== void 0 && alignment.center),
486
- end: typeof alignment === 'boolean' ? alignment : !!(alignment !== null && alignment !== void 0 && alignment.end)
487
- },
488
- blockTypes: {
489
- blockquote: typeof blockTypes === 'boolean' ? blockTypes : !!(blockTypes !== null && blockTypes !== void 0 && blockTypes.blockquote),
490
- code: typeof blockTypes === 'boolean' ? blockTypes : !!(blockTypes !== null && blockTypes !== void 0 && blockTypes.code)
491
- },
492
- headingLevels: typeof headingLevels === 'boolean' ? [1, 2, 3, 4, 5, 6].filter(_ => headingLevels) : [...new Set(headingLevels)].sort(),
493
- inlineMarks: {
494
- bold: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.bold),
495
- code: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.code),
496
- italic: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.italic),
497
- strikethrough: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.strikethrough),
498
- underline: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.underline),
499
- keyboard: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.keyboard),
500
- subscript: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.subscript),
501
- superscript: typeof inlineMarks === 'boolean' ? inlineMarks : !!(inlineMarks !== null && inlineMarks !== void 0 && inlineMarks.superscript)
502
- },
503
- listTypes: {
504
- ordered: typeof listTypes === 'boolean' ? listTypes : !!(listTypes !== null && listTypes !== void 0 && listTypes.ordered),
505
- unordered: typeof listTypes === 'boolean' ? listTypes : !!(listTypes !== null && listTypes !== void 0 && listTypes.unordered)
506
- },
507
- softBreaks: typeof softBreaks === 'boolean' ? softBreaks : !!softBreaks
508
- },
509
- links: !!config.links,
510
- layouts: [...new Set((config.layouts || []).map(x => JSON.stringify(x)))].map(x => JSON.parse(x)),
511
- dividers: !!config.dividers
512
- };
513
- return documentFeatures;
514
- }
515
-
516
- function normaliseRelationships(configRelationships, meta) {
517
- if (!configRelationships) return {};
518
- const relationships = {};
519
- for (const [key, relationship] of Object.entries(configRelationships)) {
520
- var _relationship$labelFi, _relationship$selecti;
521
- if (meta.lists[relationship.listKey] === undefined) {
522
- throw new Error(`An inline relationship ${relationship.label} (${key}) in the field at ${meta.listKey}.${meta.fieldKey} has listKey set to "${relationship.listKey}" but no list named "${relationship.listKey}" exists.`);
523
- }
524
- relationships[key] = {
525
- ...relationship,
526
- labelField: (_relationship$labelFi = relationship.labelField) !== null && _relationship$labelFi !== void 0 ? _relationship$labelFi : null,
527
- selection: (_relationship$selecti = relationship.selection) !== null && _relationship$selecti !== void 0 ? _relationship$selecti : null
528
- };
529
- }
530
- return relationships;
531
- }
532
-
533
- function document({
534
- componentBlocks = {},
535
- dividers,
536
- formatting,
537
- layouts,
538
- relationships: configRelationships,
539
- links,
540
- ...config
541
- } = {}) {
542
- return meta => {
543
- var _config$db, _config$db2;
544
- const documentFeatures = normaliseDocumentFeatures({
545
- dividers,
546
- formatting,
547
- layouts,
548
- links
549
- });
550
- const relationships = normaliseRelationships(configRelationships, meta);
551
- const inputResolver = data => {
552
- if (data === null) throw new graphql.GraphQLError('Input error: Document fields cannot be set to null');
553
- if (data === undefined) return data;
554
- return validateAndNormalizeDocument(data, documentFeatures, componentBlocks, relationships);
555
- };
556
- if (config.isIndexed === 'unique') {
557
- throw Error("isIndexed: 'unique' is not a supported option for field type document");
558
- }
559
- const lists = new Set(Object.keys(meta.lists));
560
- for (const [name, block] of Object.entries(componentBlocks)) {
561
- try {
562
- assertValidComponentSchema({
563
- kind: 'object',
564
- fields: block.schema
565
- }, lists, 'document');
566
- } catch (err) {
567
- throw new Error(`Component block ${name} in ${meta.listKey}.${meta.fieldKey}: ${err.message}`);
568
- }
569
- }
570
- const defaultValue = [{
571
- type: 'paragraph',
572
- children: [{
573
- text: ''
574
- }]
575
- }];
576
- return types.fieldType({
577
- kind: 'scalar',
578
- scalar: 'Json',
579
- mode: 'required',
580
- default: meta.provider === 'sqlite' ? undefined : {
581
- kind: 'literal',
582
- // TODO: waiting on https://github.com/prisma/prisma/issues/26571
583
- // input.create manages defaultValues anyway
584
- value: JSON.stringify(defaultValue !== null && defaultValue !== void 0 ? defaultValue : null)
585
- },
586
- map: (_config$db = config.db) === null || _config$db === void 0 ? void 0 : _config$db.map,
587
- extendPrismaSchema: (_config$db2 = config.db) === null || _config$db2 === void 0 ? void 0 : _config$db2.extendPrismaSchema
588
- })({
589
- ...config,
590
- input: {
591
- create: {
592
- arg: lkbCore.g.arg({
593
- type: lkbCore.g.JSON
594
- }),
595
- resolve(val) {
596
- if (val === undefined) {
597
- val = defaultValue;
598
- }
599
- return inputResolver(val);
600
- }
601
- },
602
- update: {
603
- arg: lkbCore.g.arg({
604
- type: lkbCore.g.JSON
605
- }),
606
- resolve: inputResolver
607
- }
608
- },
609
- output: lkbCore.g.field({
610
- type: lkbCore.g.object()({
611
- name: `${meta.listKey}_${meta.fieldKey}_Document`,
612
- fields: {
613
- document: lkbCore.g.field({
614
- args: {
615
- hydrateRelationships: lkbCore.g.arg({
616
- type: lkbCore.g.nonNull(lkbCore.g.Boolean),
617
- defaultValue: false
618
- })
619
- },
620
- type: lkbCore.g.nonNull(lkbCore.g.JSON),
621
- resolve({
622
- document
623
- }, {
624
- hydrateRelationships
625
- }, context) {
626
- return hydrateRelationships ? addRelationshipData(document, context, relationships, componentBlocks) : document;
627
- }
628
- })
629
- }
630
- }),
631
- resolve({
632
- value
633
- }) {
634
- if (value === null) return null;
635
- return {
636
- document: value
637
- };
638
- }
639
- }),
640
- views: 'lkb-fields-document/views',
641
- getAdminMeta() {
642
- return {
643
- relationships,
644
- documentFeatures,
645
- componentBlocksPassedOnServer: Object.keys(componentBlocks)
646
- };
647
- }
648
- });
649
- };
650
- }
651
-
652
- function getGraphQLInputType(name, schema, operation, cache, meta) {
653
- if (!cache.has(schema)) {
654
- const res = getGraphQLInputTypeInner(name, schema, operation, cache, meta);
655
- cache.set(schema, res);
656
- }
657
- return cache.get(schema);
658
- }
659
- function getGraphQLInputTypeInner(name, schema, operation, cache, meta) {
660
- if (schema.kind === 'form') {
661
- if (!schema.graphql) {
662
- throw new Error(`Field at ${name} is missing a graphql field`);
663
- }
664
- return schema.graphql.input;
665
- }
666
- if (schema.kind === 'object') {
667
- const input = lkbCore.g.inputObject({
668
- name: `${name}${operation[0].toUpperCase()}${operation.slice(1)}Input`,
669
- fields: () => Object.fromEntries(Object.entries(schema.fields).map(([key, val]) => {
670
- const type = getGraphQLInputType(`${name}${key[0].toUpperCase()}${key.slice(1)}`, val, operation, cache, meta);
671
- return [key, lkbCore.g.arg({
672
- type
673
- })];
674
- }))
675
- });
676
- return input;
677
- }
678
- if (schema.kind === 'array') {
679
- const innerType = getGraphQLInputType(name, schema.element, operation, cache, meta);
680
- return lkbCore.g.list(innerType);
681
- }
682
- if (schema.kind === 'conditional') {
683
- const input = lkbCore.g.inputObject({
684
- name: `${name}${operation[0].toUpperCase()}${operation.slice(1)}Input`,
685
- fields: () => Object.fromEntries(Object.entries(schema.values).map(([key, val]) => {
686
- const type = getGraphQLInputType(`${name}${key[0].toUpperCase()}${key.slice(1)}`, val, operation, cache, meta);
687
- return [key, lkbCore.g.arg({
688
- type
689
- })];
690
- }))
691
- });
692
- return input;
693
- }
694
- if (schema.kind === 'relationship') {
695
- const inputType = meta.lists[schema.listKey].types.relateTo[schema.many ? 'many' : 'one'][operation];
696
- // there are cases where this won't exist
697
- // for example if gql omit is enabled on the related field
698
- if (inputType === undefined) {
699
- throw new Error('');
700
- }
701
- return inputType;
702
- }
703
- if (schema.kind === 'child') {
704
- throw new Error(`Child fields are not supported in the structure field, found one at ${name}`);
705
- }
706
- utils.assertNever(schema);
707
- }
708
- async function getValueForUpdate(schema, value, prevValue, context, path) {
709
- if (value === undefined) return prevValue;
710
- if (prevValue === undefined) {
711
- prevValue = utils.getInitialPropsValue(schema);
712
- }
713
- if (schema.kind === 'form') {
714
- if (schema.validate(value)) return value;
715
- throw new Error(`The value of the form field at '${path.join('.')}' is invalid`);
716
- }
717
- if (value === null) {
718
- throw new Error(`${schema.kind[0].toUpperCase() + schema.kind.slice(1)} fields cannot be set to null but the field at '${path.join('.')}' is null`);
719
- }
720
- if (schema.kind === 'object') {
721
- return Object.fromEntries(await Promise.all(Object.entries(schema.fields).map(async ([key, val]) => {
722
- return [key, await getValueForUpdate(val, value[key], prevValue[key], context, path.concat(key))];
723
- })));
724
- }
725
- if (schema.kind === 'array') {
726
- return Promise.all(value.map((val, i) => getValueForUpdate(schema.element, val, prevValue[i], context, path.concat(i))));
727
- }
728
- if (schema.kind === 'relationship') {
729
- if (schema.many) {
730
- const val = value;
731
- return resolveRelateToManyForUpdateInput(val, context, schema.listKey, prevValue);
732
- } else {
733
- const val = value;
734
- return resolveRelateToOneForUpdateInput(val, context, schema.listKey);
735
- }
736
- }
737
- if (schema.kind === 'conditional') {
738
- const conditionalValueKeys = Object.keys(value);
739
- if (conditionalValueKeys.length !== 1) {
740
- throw new Error(`Conditional field inputs must set exactly one of the fields but the field at ${path.join('.')} has ${conditionalValueKeys.length} fields set`);
741
- }
742
- const key = conditionalValueKeys[0];
743
- let discriminant = key;
744
- if ((key === 'true' || key === 'false') && !schema.discriminant.validate(key)) {
745
- discriminant = key === 'true';
746
- }
747
- return {
748
- discriminant,
749
- value: await getValueForUpdate(schema.values[key], value[key], prevValue.discriminant === discriminant ? prevValue.value : utils.getInitialPropsValue(schema), context, path.concat('value'))
750
- };
751
- }
752
- if (schema.kind === 'child') {
753
- throw new Error(`Child fields are not supported in the structure field, found one at ${path.join('.')}`);
754
- }
755
- utils.assertNever(schema);
756
- }
757
- async function getValueForCreate(schema, value, context, path) {
758
- // If value is undefined, get the specified defaultValue
759
- if (value === undefined) return utils.getInitialPropsValue(schema);
760
- if (schema.kind === 'form') {
761
- if (schema.validate(value)) return value;
762
- throw new Error(`The value of the form field at '${path.join('.')}' is invalid`);
763
- }
764
- if (value === null) {
765
- throw new Error(`${schema.kind[0].toUpperCase() + schema.kind.slice(1)} fields cannot be set to null but the field at '${path.join('.')}' is null`);
766
- }
767
- if (schema.kind === 'array') {
768
- return Promise.all(value.map((val, i) => getValueForCreate(schema.element, val, context, path.concat(i))));
769
- }
770
- if (schema.kind === 'object') {
771
- return Object.fromEntries(await Promise.all(Object.entries(schema.fields).map(async ([key, val]) => {
772
- return [key, await getValueForCreate(val, value[key], context, path.concat(key))];
773
- })));
774
- }
775
- if (schema.kind === 'relationship') {
776
- if (schema.many) {
777
- const val = value;
778
- return resolveRelateToManyForCreateInput(val, context, schema.listKey);
779
- } else {
780
- const val = value;
781
- return resolveRelateToOneForCreateInput(val, context, schema.listKey);
782
- }
783
- }
784
- if (schema.kind === 'conditional') {
785
- if (value === null) throw new Error();
786
- const conditionalValueKeys = Object.keys(value);
787
- if (conditionalValueKeys.length !== 1) throw new Error();
788
- const key = conditionalValueKeys[0];
789
- let discriminant = key;
790
- if ((key === 'true' || key === 'false') && !schema.discriminant.validate(key)) {
791
- discriminant = key === 'true';
792
- }
793
- return {
794
- discriminant,
795
- value: await getValueForCreate(schema.values[key], value[key], context, path.concat('value'))
796
- };
797
- }
798
- if (schema.kind === 'child') {
799
- throw new Error(`Child fields are not supported in the structure field, found one at ${path.join('.')}`);
800
- }
801
- utils.assertNever(schema);
802
- }
803
- /** MANY */
804
-
805
- class RelationshipErrors extends Error {
806
- constructor(errors) {
807
- super('Multiple relationship errors');
808
- this.errors = errors;
809
- }
810
- }
811
- function getResolvedUniqueWheres(uniqueInputs, context, foreignListKey, operation) {
812
- return uniqueInputs.map(uniqueInput => checkUniqueItemExists(uniqueInput, foreignListKey, context, operation));
813
- }
814
-
815
- // these aren't here out of thinking this is better syntax(i do not think it is),
816
- // it's just because TS won't infer the arg is X bit
817
- const isFulfilled = arg => arg.status === 'fulfilled';
818
- const isRejected = arg => arg.status === 'rejected';
819
- async function resolveRelateToManyForCreateInput(value, context, foreignListKey, tag) {
820
- if (!Array.isArray(value.connect) && !Array.isArray(value.create)) {
821
- throw new Error(`You must provide "connect" or "create" in to-many relationship inputs for "create" operations.`);
822
- }
823
-
824
- // Perform queries for the connections
825
- const connects = Promise.allSettled(getResolvedUniqueWheres(value.connect || [], context, foreignListKey, 'connect'));
826
-
827
- // Perform nested mutations for the creations
828
- const creates = Promise.allSettled((value.create || []).map(x => resolveCreateMutation(x, context, foreignListKey)));
829
- const [connectResult, createResult] = await Promise.all([connects, creates]);
830
-
831
- // Collect all the errors
832
- const errors = [...connectResult, ...createResult].filter(isRejected);
833
- if (errors.length) {
834
- // readd tag
835
- throw new RelationshipErrors(errors.map(x => ({
836
- error: x.reason,
837
- tag: tag || ''
838
- })));
839
- }
840
-
841
- // Perform queries for the connections
842
- return [...connectResult, ...createResult].filter(isFulfilled).map(x => x.value);
843
- }
844
- async function resolveRelateToManyForUpdateInput(value, context, foreignListKey, prevVal) {
845
- if (!Array.isArray(value.connect) && !Array.isArray(value.create) && !Array.isArray(value.disconnect) && !Array.isArray(value.set)) {
846
- throw new Error(`You must provide at least one of "set", "connect", "create" or "disconnect" in to-many relationship inputs for "update" operations.`);
847
- }
848
- if (value.set && value.disconnect) {
849
- throw new Error(`The "set" and "disconnect" fields cannot both be provided to to-many relationship inputs for "update" operations.`);
850
- }
851
-
852
- // Perform queries for the connections
853
- const connects = Promise.allSettled(getResolvedUniqueWheres(value.connect || [], context, foreignListKey, 'connect'));
854
- const disconnects = Promise.allSettled(getResolvedUniqueWheres(value.disconnect || [], context, foreignListKey, 'disconnect'));
855
- const sets = Promise.allSettled(getResolvedUniqueWheres(value.set || [], context, foreignListKey, 'set'));
856
-
857
- // Perform nested mutations for the creations
858
- const creates = Promise.allSettled((value.create || []).map(x => resolveCreateMutation(x, context, foreignListKey)));
859
- const [connectResult, createResult, disconnectResult, setResult] = await Promise.all([connects, creates, disconnects, sets]);
860
-
861
- // Collect all the errors
862
- const errors = [...connectResult, ...createResult, ...disconnectResult, ...setResult].filter(isRejected);
863
- if (errors.length) throw new RelationshipErrors(errors.map(x => ({
864
- error: x.reason,
865
- tag: ''
866
- })));
867
- let values = prevVal;
868
- if (value.set) {
869
- values = setResult.filter(isFulfilled).map(x => x.value);
870
- }
871
- const idsToDisconnect = new Set(disconnectResult.filter(isFulfilled).map(x => x.value.id));
872
- values = values.filter(x => !idsToDisconnect.has(x.id));
873
- values.push(...connectResult.filter(isFulfilled).map(x => x.value));
874
- values.push(...createResult.filter(isFulfilled).map(x => x.value));
875
- return values;
876
- }
877
-
878
- /** ONE */
879
-
880
- function missingItem(operation, uniqueWhere) {
881
- throw new Error(`You cannot ${operation} the item '${JSON.stringify(uniqueWhere)}' - it may not exist`);
882
- }
883
- async function checkUniqueItemExists(uniqueInput, listKey, context, operation) {
884
- // Check whether the item exists (from this users POV).
885
- const item = await context.db[listKey].findOne({
886
- where: uniqueInput
887
- });
888
- if (item === null) throw missingItem(operation, uniqueInput);
889
- return {
890
- id: item.id.toString()
891
- };
892
- }
893
- async function handleCreateAndUpdate(value, context, foreignListKey) {
894
- if (value.connect) return checkUniqueItemExists(value.connect, foreignListKey, context, 'connect');
895
- return resolveCreateMutation(value, context, foreignListKey);
896
- }
897
- async function resolveCreateMutation(value, context, foreignListKey) {
898
- const mutationType = context.graphql.schema.getMutationType();
899
- const {
900
- id
901
- } = await mutationType.getFields()[context.__internal.lists[foreignListKey].graphql.names.createMutationName].resolve({}, {
902
- data: value.create
903
- }, context,
904
- // we happen to know this isn't used
905
- // no one else should rely on that though
906
- // it could change in the future
907
- {});
908
- return {
909
- id: id.toString()
910
- };
911
- }
912
- function resolveRelateToOneForCreateInput(value, context, foreignListKey) {
913
- const numOfKeys = Object.keys(value).length;
914
- if (numOfKeys !== 1) throw new Error(`You must provide "connect" or "create" in to-one relationship inputs for "create" operations.`);
915
- return handleCreateAndUpdate(value, context, foreignListKey);
916
- }
917
- function resolveRelateToOneForUpdateInput(value, context, foreignListKey) {
918
- if (Object.keys(value).length !== 1) throw new Error(`You must provide one of "connect", "create" or "disconnect" in to-one relationship inputs for "update" operations.`);
919
- if (value.connect || value.create) return handleCreateAndUpdate(value, context, foreignListKey);
920
- if (value.disconnect) return null;
921
- }
922
-
923
- function wrapGraphQLFieldInResolver(inputField, getVal) {
924
- return lkbCore.g.field({
925
- type: inputField.type,
926
- args: inputField.args,
927
- deprecationReason: inputField.deprecationReason,
928
- description: inputField.description,
929
- extensions: inputField.extensions,
930
- resolve(value, args, context, info) {
931
- const val = getVal(value);
932
- if (!inputField.resolve) {
933
- return val;
934
- }
935
- return inputField.resolve({
936
- value: val
937
- }, args, context, info);
938
- }
939
- });
940
- }
941
- function getOutputGraphQLField(name, schema, interfaceImplementations, cache, meta) {
942
- if (!cache.has(schema)) {
943
- const res = getOutputGraphQLFieldInner(name, schema, interfaceImplementations, cache, meta);
944
- cache.set(schema, res);
945
- }
946
- return cache.get(schema);
947
- }
948
- function getOutputGraphQLFieldInner(name, schema, interfaceImplementations, cache, meta) {
949
- if (schema.kind === 'form') {
950
- if (!schema.graphql) {
951
- throw new Error(`Field at ${name} is missing a graphql field`);
952
- }
953
- return wrapGraphQLFieldInResolver(schema.graphql.output, x => x.value);
954
- }
955
- if (schema.kind === 'object') {
956
- return lkbCore.g.field({
957
- type: lkbCore.g.object()({
958
- name,
959
- fields: () => Object.fromEntries(Object.entries(schema.fields).map(([key, val]) => {
960
- const field = getOutputGraphQLField(`${name}${key[0].toUpperCase()}${key.slice(1)}`, val, interfaceImplementations, cache, meta);
961
- return [key, wrapGraphQLFieldInResolver(field, source => source[key])];
962
- }))
963
- }),
964
- resolve({
965
- value
966
- }) {
967
- return value;
968
- }
969
- });
970
- }
971
- if (schema.kind === 'array') {
972
- const innerField = getOutputGraphQLField(name, schema.element, interfaceImplementations, cache, meta);
973
- const resolve = innerField.resolve;
974
- return lkbCore.g.field({
975
- type: lkbCore.g.list(innerField.type),
976
- args: innerField.args,
977
- deprecationReason: innerField.deprecationReason,
978
- description: innerField.description,
979
- extensions: innerField.extensions,
980
- resolve({
981
- value
982
- }, args, context, info) {
983
- if (!resolve) {
984
- return value;
985
- }
986
- return value.map(val => resolve({
987
- value: val
988
- }, args, context, info));
989
- }
990
- });
991
- }
992
- if (schema.kind === 'conditional') {
993
- let discriminantField;
994
- const getDiscriminantField = () => {
995
- if (!discriminantField) {
996
- discriminantField = getOutputGraphQLField(name + 'Discriminant', schema.discriminant, interfaceImplementations, cache, meta);
997
- }
998
- return discriminantField;
999
- };
1000
- const interfaceType = lkbCore.g.interface()({
1001
- name,
1002
- resolveType: value => {
1003
- const stringifiedDiscriminant = value.discriminant.toString();
1004
- return name + stringifiedDiscriminant[0].toUpperCase() + stringifiedDiscriminant.slice(1);
1005
- },
1006
- fields: () => ({
1007
- discriminant: getDiscriminantField()
1008
- })
1009
- });
1010
- interfaceImplementations.push(...Object.entries(schema.values).map(([key, val]) => {
1011
- const innerName = name + key[0].toUpperCase() + key.slice(1);
1012
- return lkbCore.g.object()({
1013
- name: innerName,
1014
- interfaces: [interfaceType],
1015
- fields: () => ({
1016
- discriminant: wrapGraphQLFieldInResolver(getDiscriminantField(), x => x.discriminant),
1017
- value: getOutputGraphQLField(`${innerName}Value`, val, interfaceImplementations, cache, meta)
1018
- })
1019
- });
1020
- }));
1021
- return lkbCore.g.field({
1022
- type: interfaceType,
1023
- resolve({
1024
- value
1025
- }) {
1026
- return value;
1027
- }
1028
- });
1029
- }
1030
- if (schema.kind === 'relationship') {
1031
- const listOutputType = meta.lists[schema.listKey].types.output;
1032
- return lkbCore.g.field({
1033
- type: schema.many ? lkbCore.g.list(listOutputType) : listOutputType,
1034
- resolve({
1035
- value
1036
- }, args, context) {
1037
- if (Array.isArray(value)) {
1038
- return context.db[schema.listKey].findMany({
1039
- where: {
1040
- id: {
1041
- in: value.map(x => x.id)
1042
- }
1043
- }
1044
- });
1045
- }
1046
- if ((value === null || value === void 0 ? void 0 : value.id) == null) {
1047
- return null;
1048
- }
1049
- return context.db[schema.listKey].findOne({
1050
- where: {
1051
- id: value.id
1052
- }
1053
- });
1054
- }
1055
- });
1056
- }
1057
- if (schema.kind === 'child') {
1058
- throw new Error('Child fields are not supported in the structure field');
1059
- }
1060
- utils.assertNever(schema);
1061
- }
1062
-
1063
- function structure({
1064
- schema,
1065
- ...config
1066
- }) {
1067
- return meta => {
1068
- var _config$hooks, _config$hooks2, _config$db, _config$hooks3, _config$hooks4;
1069
- if (config.isIndexed === 'unique') {
1070
- throw Error("isIndexed: 'unique' is not a supported option for field type structure");
1071
- }
1072
- const lists = new Set(Object.keys(meta.lists));
1073
- try {
1074
- assertValidComponentSchema(schema, lists, 'structure');
1075
- } catch (err) {
1076
- throw new Error(`${meta.listKey}.${meta.fieldKey}: ${err.message}`);
1077
- }
1078
- const defaultValue = utils.getInitialPropsValue(schema);
1079
- const unreferencedConcreteInterfaceImplementations = [];
1080
- const name = meta.listKey + meta.fieldKey[0].toUpperCase() + meta.fieldKey.slice(1);
1081
- const innerUpdate = typeof ((_config$hooks = config.hooks) === null || _config$hooks === void 0 ? void 0 : _config$hooks.resolveInput) === 'function' ? config.hooks.resolveInput : (_config$hooks2 = config.hooks) === null || _config$hooks2 === void 0 || (_config$hooks2 = _config$hooks2.resolveInput) === null || _config$hooks2 === void 0 ? void 0 : _config$hooks2.update;
1082
- return types.fieldType({
1083
- kind: 'scalar',
1084
- scalar: 'Json',
1085
- default: meta.provider === 'sqlite' ? undefined : {
1086
- kind: 'literal',
1087
- // TODO: waiting on https://github.com/prisma/prisma/issues/26571
1088
- // input.create manages defaultValues anyway
1089
- value: JSON.stringify(defaultValue !== null && defaultValue !== void 0 ? defaultValue : null)
1090
- },
1091
- map: (_config$db = config.db) === null || _config$db === void 0 ? void 0 : _config$db.map,
1092
- mode: 'required'
1093
- })({
1094
- ...config,
1095
- hooks: {
1096
- ...config.hooks,
1097
- resolveInput: {
1098
- create: typeof ((_config$hooks3 = config.hooks) === null || _config$hooks3 === void 0 ? void 0 : _config$hooks3.resolveInput) === 'function' ? config.hooks.resolveInput : (_config$hooks4 = config.hooks) === null || _config$hooks4 === void 0 || (_config$hooks4 = _config$hooks4.resolveInput) === null || _config$hooks4 === void 0 ? void 0 : _config$hooks4.create,
1099
- update: async args => {
1100
- let val = args.resolvedData[meta.fieldKey];
1101
- let prevVal = args.item[meta.fieldKey];
1102
- val = await getValueForUpdate(schema, val, prevVal, args.context, []);
1103
- return innerUpdate ? innerUpdate({
1104
- ...args,
1105
- resolvedData: {
1106
- ...args.resolvedData,
1107
- [meta.fieldKey]: val
1108
- }
1109
- }) : val;
1110
- }
1111
- }
1112
- },
1113
- input: {
1114
- create: {
1115
- arg: lkbCore.g.arg({
1116
- type: getGraphQLInputType(name, schema, 'create', new Map(), meta)
1117
- }),
1118
- async resolve(val, context) {
1119
- return await getValueForCreate(schema, val, context, []);
1120
- }
1121
- },
1122
- update: {
1123
- arg: lkbCore.g.arg({
1124
- type: getGraphQLInputType(name, schema, 'update', new Map(), meta)
1125
- }),
1126
- resolve(val) {
1127
- return val;
1128
- }
1129
- }
1130
- },
1131
- output: lkbCore.g.field({
1132
- type: lkbCore.g.object()({
1133
- name: `${name}Output`,
1134
- fields: {
1135
- structure: getOutputGraphQLField(name, schema, unreferencedConcreteInterfaceImplementations, new Map(), meta),
1136
- json: lkbCore.g.field({
1137
- type: lkbCore.g.JSON,
1138
- args: {
1139
- hydrateRelationships: lkbCore.g.arg({
1140
- type: lkbCore.g.nonNull(lkbCore.g.Boolean),
1141
- defaultValue: false
1142
- })
1143
- },
1144
- resolve({
1145
- value
1146
- }, args, context) {
1147
- if (!args.hydrateRelationships) return value;
1148
- return addRelationshipDataToComponentProps(schema, value, (schema, value) => {
1149
- return fetchRelationshipData(context, schema, value);
1150
- });
1151
- }
1152
- })
1153
- }
1154
- }),
1155
- resolve(source) {
1156
- return source;
1157
- }
1158
- }),
1159
- views: 'lkb-fields-document/structure-views',
1160
- getAdminMeta: () => ({}),
1161
- unreferencedConcreteInterfaceImplementations
1162
- });
1163
- };
1164
- }
1165
-
1166
- exports.document = document;
1167
- exports.structure = structure;
1
+ "use strict";
2
+ // this file might look strange and you might be wondering what it's for
3
+ // it's lets you import your source files by importing this entrypoint
4
+ // as you would import it if it was built with preconstruct build
5
+ // this file is slightly different to some others though
6
+ // it has a require hook which compiles your code with Babel
7
+ // this means that you don't have to set up @babel/register or anything like that
8
+ // but you can still require this module and it'll be compiled
9
+
10
+ // this bit of code imports the require hook and registers it
11
+ let unregister = require("../../../node_modules/.pnpm/@preconstruct+hook@0.4.0/node_modules/@preconstruct/hook").___internalHook(typeof __dirname === 'undefined' ? undefined : __dirname, "../../..", "..");
12
+
13
+ // this re-exports the source file
14
+ module.exports = require("../src/index.ts");
15
+
16
+ unregister();