@depup/payload 3.82.0-depup.0 → 3.86.0-depup.5
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.
- package/README.md +16 -14
- package/bin.js +11 -0
- package/changes.json +26 -18
- package/dist/admin/fields/Row.d.ts +2 -2
- package/dist/admin/fields/Row.d.ts.map +1 -1
- package/dist/admin/fields/Row.js.map +1 -1
- package/dist/admin/forms/Field.d.ts +1 -3
- package/dist/admin/forms/Field.d.ts.map +1 -1
- package/dist/admin/forms/Field.js.map +1 -1
- package/dist/admin/views/index.d.ts +5 -1
- package/dist/admin/views/index.d.ts.map +1 -1
- package/dist/admin/views/index.js.map +1 -1
- package/dist/bin/generateImportMap/index.d.ts.map +1 -1
- package/dist/bin/generateImportMap/index.js +1 -0
- package/dist/bin/generateImportMap/index.js.map +1 -1
- package/dist/bin/generateImportMap/iterateCollections.d.ts.map +1 -1
- package/dist/bin/generateImportMap/iterateCollections.js +11 -0
- package/dist/bin/generateImportMap/iterateCollections.js.map +1 -1
- package/dist/bin/index.d.ts.map +1 -1
- package/dist/bin/index.js +3 -1
- package/dist/bin/index.js.map +1 -1
- package/dist/collections/config/sanitize.d.ts +5 -0
- package/dist/collections/config/sanitize.d.ts.map +1 -1
- package/dist/collections/config/sanitize.js +21 -0
- package/dist/collections/config/sanitize.js.map +1 -1
- package/dist/collections/config/sanitize.spec.js +120 -0
- package/dist/collections/config/sanitize.spec.js.map +1 -0
- package/dist/collections/config/types.d.ts +24 -1
- package/dist/collections/config/types.d.ts.map +1 -1
- package/dist/collections/config/types.js.map +1 -1
- package/dist/collections/operations/create.d.ts.map +1 -1
- package/dist/collections/operations/create.js +1 -0
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/delete.d.ts.map +1 -1
- package/dist/collections/operations/delete.js +3 -0
- package/dist/collections/operations/delete.js.map +1 -1
- package/dist/collections/operations/restoreVersion.d.ts.map +1 -1
- package/dist/collections/operations/restoreVersion.js +1 -0
- package/dist/collections/operations/restoreVersion.js.map +1 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +7 -2
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.d.ts +9 -0
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.d.ts.map +1 -0
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.js +170 -0
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.js.map +1 -0
- package/dist/collections/operations/utilities/update.d.ts.map +1 -1
- package/dist/collections/operations/utilities/update.js +16 -8
- package/dist/collections/operations/utilities/update.js.map +1 -1
- package/dist/config/build.js +5 -4
- package/dist/config/build.js.map +1 -1
- package/dist/config/definePlugin.d.ts +41 -0
- package/dist/config/definePlugin.d.ts.map +1 -0
- package/dist/config/definePlugin.js +34 -0
- package/dist/config/definePlugin.js.map +1 -0
- package/dist/config/orderable/index.d.ts.map +1 -1
- package/dist/config/orderable/index.js +23 -0
- package/dist/config/orderable/index.js.map +1 -1
- package/dist/config/types.d.ts +30 -2
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/email/normalizeSendEmailOptions.d.ts +13 -0
- package/dist/email/normalizeSendEmailOptions.d.ts.map +1 -0
- package/dist/email/normalizeSendEmailOptions.js +20 -0
- package/dist/email/normalizeSendEmailOptions.js.map +1 -0
- package/dist/email/types.d.ts +7 -2
- package/dist/email/types.d.ts.map +1 -1
- package/dist/email/types.js.map +1 -1
- package/dist/errors/APIError.d.ts +2 -1
- package/dist/errors/APIError.d.ts.map +1 -1
- package/dist/errors/APIError.js +1 -3
- package/dist/errors/APIError.js.map +1 -1
- package/dist/errors/ValidationError.d.ts +3 -1
- package/dist/errors/ValidationError.d.ts.map +1 -1
- package/dist/errors/ValidationError.js +1 -3
- package/dist/errors/ValidationError.js.map +1 -1
- package/dist/fields/config/sanitize.d.ts.map +1 -1
- package/dist/fields/config/sanitize.js +3 -0
- package/dist/fields/config/sanitize.js.map +1 -1
- package/dist/fields/config/sanitize.spec.js +66 -0
- package/dist/fields/config/sanitize.spec.js.map +1 -1
- package/dist/fields/config/types.d.ts +3 -2
- package/dist/fields/config/types.d.ts.map +1 -1
- package/dist/fields/config/types.js.map +1 -1
- package/dist/fields/hooks/beforeValidate/promise.js +2 -2
- package/dist/fields/hooks/beforeValidate/promise.js.map +1 -1
- package/dist/globals/operations/restoreVersion.d.ts.map +1 -1
- package/dist/globals/operations/restoreVersion.js +1 -0
- package/dist/globals/operations/restoreVersion.js.map +1 -1
- package/dist/index.bundled.d.ts +484 -115
- package/dist/index.d.ts +19 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -2
- package/dist/index.js.map +1 -1
- package/dist/queues/config/collection.d.ts.map +1 -1
- package/dist/queues/config/collection.js +0 -1
- package/dist/queues/config/collection.js.map +1 -1
- package/dist/queues/endpoints/run.d.ts.map +1 -1
- package/dist/queues/endpoints/run.js +0 -3
- package/dist/queues/endpoints/run.js.map +1 -1
- package/dist/queues/errors/calculateBackoffWaitUntil.d.ts.map +1 -1
- package/dist/queues/errors/calculateBackoffWaitUntil.js +5 -13
- package/dist/queues/errors/calculateBackoffWaitUntil.js.map +1 -1
- package/dist/queues/errors/handleWorkflowError.d.ts.map +1 -1
- package/dist/queues/errors/handleWorkflowError.js +9 -1
- package/dist/queues/errors/handleWorkflowError.js.map +1 -1
- package/dist/queues/operations/handleSchedules/countRunnableOrActiveJobsForQueue.d.ts.map +1 -1
- package/dist/queues/operations/handleSchedules/countRunnableOrActiveJobsForQueue.js +2 -1
- package/dist/queues/operations/handleSchedules/countRunnableOrActiveJobsForQueue.js.map +1 -1
- package/dist/queues/operations/handleSchedules/defaultAfterSchedule.js +1 -1
- package/dist/queues/operations/handleSchedules/defaultAfterSchedule.js.map +1 -1
- package/dist/queues/operations/handleSchedules/index.d.ts.map +1 -1
- package/dist/queues/operations/handleSchedules/index.js +4 -1
- package/dist/queues/operations/handleSchedules/index.js.map +1 -1
- package/dist/queues/operations/runJobs/index.d.ts.map +1 -1
- package/dist/queues/operations/runJobs/index.js +44 -26
- package/dist/queues/operations/runJobs/index.js.map +1 -1
- package/dist/queues/operations/runJobs/runJSONJob/index.d.ts.map +1 -1
- package/dist/queues/operations/runJobs/runJSONJob/index.js +1 -0
- package/dist/queues/operations/runJobs/runJSONJob/index.js.map +1 -1
- package/dist/queues/utilities/updateJob.d.ts.map +1 -1
- package/dist/queues/utilities/updateJob.js +2 -1
- package/dist/queues/utilities/updateJob.js.map +1 -1
- package/dist/types/index.d.ts +4 -6
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/uploads/checkFileAccess.d.ts.map +1 -1
- package/dist/uploads/checkFileAccess.js +30 -9
- package/dist/uploads/checkFileAccess.js.map +1 -1
- package/dist/uploads/checkFileRestrictions.d.ts.map +1 -1
- package/dist/uploads/checkFileRestrictions.js +48 -8
- package/dist/uploads/checkFileRestrictions.js.map +1 -1
- package/dist/uploads/fetchAPI-multipart/isEligibleRequest.d.ts.map +1 -1
- package/dist/uploads/fetchAPI-multipart/isEligibleRequest.js +2 -1
- package/dist/uploads/fetchAPI-multipart/isEligibleRequest.js.map +1 -1
- package/dist/uploads/fetchAPI-multipart/isEligibleRequest.spec.js +29 -0
- package/dist/uploads/fetchAPI-multipart/isEligibleRequest.spec.js.map +1 -0
- package/dist/uploads/fetchAPI-multipart/processMultipart.d.ts.map +1 -1
- package/dist/uploads/fetchAPI-multipart/processMultipart.js +11 -2
- package/dist/uploads/fetchAPI-multipart/processMultipart.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts +2 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js +5 -2
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/getSafeFilename.d.ts +9 -4
- package/dist/uploads/getSafeFilename.d.ts.map +1 -1
- package/dist/uploads/getSafeFilename.js +5 -5
- package/dist/uploads/getSafeFilename.js.map +1 -1
- package/dist/uploads/types.d.ts +4 -0
- package/dist/uploads/types.d.ts.map +1 -1
- package/dist/uploads/types.js.map +1 -1
- package/dist/utilities/addDataAndFileToRequest.d.ts.map +1 -1
- package/dist/utilities/addDataAndFileToRequest.js +16 -3
- package/dist/utilities/addDataAndFileToRequest.js.map +1 -1
- package/dist/utilities/addDataAndFileToRequest.spec.js +41 -0
- package/dist/utilities/addDataAndFileToRequest.spec.js.map +1 -0
- package/dist/utilities/createPayloadRequest.d.ts.map +1 -1
- package/dist/utilities/createPayloadRequest.js +1 -0
- package/dist/utilities/createPayloadRequest.js.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.d.ts.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.js +74 -31
- package/dist/utilities/filterDataToSelectedLocales.js.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.spec.js +337 -0
- package/dist/utilities/filterDataToSelectedLocales.spec.js.map +1 -1
- package/dist/utilities/formatErrors.d.ts +1 -1
- package/dist/utilities/formatErrors.d.ts.map +1 -1
- package/dist/utilities/formatErrors.js +4 -7
- package/dist/utilities/formatErrors.js.map +1 -1
- package/dist/utilities/formatErrors.spec.js +101 -0
- package/dist/utilities/formatErrors.spec.js.map +1 -0
- package/dist/utilities/isURLAllowed.d.ts.map +1 -1
- package/dist/utilities/isURLAllowed.js +9 -3
- package/dist/utilities/isURLAllowed.js.map +1 -1
- package/dist/utilities/isURLAllowed.spec.js +78 -0
- package/dist/utilities/isURLAllowed.spec.js.map +1 -0
- package/dist/utilities/parseParams/index.d.ts +1 -1
- package/dist/utilities/parseParams/index.d.ts.map +1 -1
- package/dist/utilities/parseParams/index.js +3 -0
- package/dist/utilities/parseParams/index.js.map +1 -1
- package/dist/utilities/parseParams/index.spec.js +24 -0
- package/dist/utilities/parseParams/index.spec.js.map +1 -1
- package/dist/utilities/profiling.d.ts +12 -0
- package/dist/utilities/profiling.d.ts.map +1 -0
- package/dist/utilities/profiling.js +56 -0
- package/dist/utilities/profiling.js.map +1 -0
- package/dist/utilities/profiling.spec.js +53 -0
- package/dist/utilities/profiling.spec.js.map +1 -0
- package/dist/versions/saveVersion.js +1 -1
- package/dist/versions/saveVersion.js.map +1 -1
- package/dist/versions/schedule/job.d.ts.map +1 -1
- package/dist/versions/schedule/job.js +4 -1
- package/dist/versions/schedule/job.js.map +1 -1
- package/dist/versions/updateLatestVersion.d.ts.map +1 -1
- package/dist/versions/updateLatestVersion.js +55 -8
- package/dist/versions/updateLatestVersion.js.map +1 -1
- package/package.json +44 -37
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SanitizedConfig } from '../../../config/types.js';
|
|
2
|
+
import type { Field } from '../../../fields/config/types.js';
|
|
3
|
+
export declare const copyDataWithFreshRowIDs: ({ config, data, existingDoc, fields, }: {
|
|
4
|
+
config: SanitizedConfig;
|
|
5
|
+
data: Record<string, unknown>;
|
|
6
|
+
existingDoc: Record<string, unknown>;
|
|
7
|
+
fields: Field[];
|
|
8
|
+
}) => Record<string, unknown>;
|
|
9
|
+
//# sourceMappingURL=copyDataWithFreshRowIDs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copyDataWithFreshRowIDs.d.ts","sourceRoot":"","sources":["../../../../src/collections/operations/utilities/copyDataWithFreshRowIDs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAC/D,OAAO,KAAK,EAAkC,KAAK,EAAE,MAAM,iCAAiC,CAAA;AAwP5F,eAAO,MAAM,uBAAuB,2CAKjC;IACD,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACpC,MAAM,EAAE,KAAK,EAAE,CAAA;CAChB,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAUzB,CAAA"}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { tabHasName } from '../../../fields/config/types.js';
|
|
2
|
+
import { deepCopyObjectSimple } from '../../../utilities/deepCopyObject.js';
|
|
3
|
+
import { traverseFields } from '../../../utilities/traverseFields.js';
|
|
4
|
+
const buildLevelMap = (fields, map = new Map())=>{
|
|
5
|
+
for (const field of fields){
|
|
6
|
+
if (field.type === 'row' || field.type === 'collapsible') {
|
|
7
|
+
buildLevelMap(field.fields, map);
|
|
8
|
+
} else if (field.type === 'tabs') {
|
|
9
|
+
for (const tab of field.tabs){
|
|
10
|
+
if (tabHasName(tab)) {
|
|
11
|
+
map.set(tab.name, {
|
|
12
|
+
type: 'subfields',
|
|
13
|
+
fields: tab.fields,
|
|
14
|
+
localized: Boolean(tab.localized)
|
|
15
|
+
});
|
|
16
|
+
} else {
|
|
17
|
+
buildLevelMap(tab.fields, map);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
} else if (field.type === 'group') {
|
|
21
|
+
if ('name' in field && field.name) {
|
|
22
|
+
map.set(field.name, {
|
|
23
|
+
type: 'subfields',
|
|
24
|
+
fields: field.fields,
|
|
25
|
+
localized: Boolean(field.localized)
|
|
26
|
+
});
|
|
27
|
+
} else {
|
|
28
|
+
buildLevelMap(field.fields, map);
|
|
29
|
+
}
|
|
30
|
+
} else if ((field.type === 'array' || field.type === 'blocks') && field.name) {
|
|
31
|
+
map.set(field.name, {
|
|
32
|
+
type: 'rows',
|
|
33
|
+
field,
|
|
34
|
+
localized: Boolean(field.localized)
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return map;
|
|
39
|
+
};
|
|
40
|
+
const isLocaleKeyed = (value, config)=>{
|
|
41
|
+
if (Array.isArray(value)) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
const localeCodes = config.localization ? config.localization.localeCodes : [];
|
|
45
|
+
const keys = Object.keys(value);
|
|
46
|
+
return keys.length > 0 && keys.every((key)=>localeCodes.includes(key));
|
|
47
|
+
};
|
|
48
|
+
const resolveBlockFields = (field, blockType, config)=>{
|
|
49
|
+
if (typeof blockType !== 'string') {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
const block = config.blocks?.find((b)=>b.slug === blockType) ?? field.blocks.find((b)=>typeof b !== 'string' && b.slug === blockType);
|
|
53
|
+
return block?.fields ?? [];
|
|
54
|
+
};
|
|
55
|
+
const copyRow = ({ config, existingRowIDs, field, parentIsLocalized, row })=>{
|
|
56
|
+
if (!row || typeof row !== 'object') {
|
|
57
|
+
return deepCopyObjectSimple(row);
|
|
58
|
+
}
|
|
59
|
+
const subfields = field.type === 'array' ? field.fields : resolveBlockFields(field, row.blockType, config);
|
|
60
|
+
const newRow = copyObject({
|
|
61
|
+
config,
|
|
62
|
+
data: row,
|
|
63
|
+
existingRowIDs,
|
|
64
|
+
fields: subfields,
|
|
65
|
+
parentIsLocalized
|
|
66
|
+
});
|
|
67
|
+
if (typeof newRow.id === 'string' && !existingRowIDs.has(newRow.id)) {
|
|
68
|
+
delete newRow.id;
|
|
69
|
+
}
|
|
70
|
+
return newRow;
|
|
71
|
+
};
|
|
72
|
+
const copyObject = ({ config, data, existingRowIDs, fields, parentIsLocalized })=>{
|
|
73
|
+
const levelMap = buildLevelMap(fields);
|
|
74
|
+
const result = {};
|
|
75
|
+
for (const key of Object.keys(data)){
|
|
76
|
+
const value = data[key];
|
|
77
|
+
const entry = levelMap.get(key);
|
|
78
|
+
if (!entry || value === null || typeof value !== 'object') {
|
|
79
|
+
result[key] = deepCopyObjectSimple(value);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const childParentIsLocalized = parentIsLocalized || entry.localized;
|
|
83
|
+
if (entry.type === 'subfields') {
|
|
84
|
+
const valueIsLocaleKeyed = entry.localized && !parentIsLocalized && isLocaleKeyed(value, config);
|
|
85
|
+
result[key] = valueIsLocaleKeyed ? mapLocales(value, (localeValue)=>copyObject({
|
|
86
|
+
config,
|
|
87
|
+
data: localeValue,
|
|
88
|
+
existingRowIDs,
|
|
89
|
+
fields: entry.fields,
|
|
90
|
+
parentIsLocalized: true
|
|
91
|
+
})) : copyObject({
|
|
92
|
+
config,
|
|
93
|
+
data: value,
|
|
94
|
+
existingRowIDs,
|
|
95
|
+
fields: entry.fields,
|
|
96
|
+
parentIsLocalized: childParentIsLocalized
|
|
97
|
+
});
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const copyRows = (rows)=>Array.isArray(rows) ? rows.map((row)=>copyRow({
|
|
101
|
+
config,
|
|
102
|
+
existingRowIDs,
|
|
103
|
+
field: entry.field,
|
|
104
|
+
parentIsLocalized: childParentIsLocalized,
|
|
105
|
+
row
|
|
106
|
+
})) : deepCopyObjectSimple(rows);
|
|
107
|
+
result[key] = Array.isArray(value) ? copyRows(value) : mapLocales(value, copyRows);
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
};
|
|
111
|
+
const mapLocales = (value, copyLocaleValue)=>{
|
|
112
|
+
if (Array.isArray(value)) {
|
|
113
|
+
return deepCopyObjectSimple(value);
|
|
114
|
+
}
|
|
115
|
+
const out = {};
|
|
116
|
+
for (const locale of Object.keys(value)){
|
|
117
|
+
const localeValue = value[locale];
|
|
118
|
+
out[locale] = localeValue && typeof localeValue === 'object' ? copyLocaleValue(localeValue) : deepCopyObjectSimple(localeValue);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
};
|
|
122
|
+
const collectExistingRowIDs = ({ config, existingDoc, fields })=>{
|
|
123
|
+
const existingRowIDs = new Set();
|
|
124
|
+
traverseFields({
|
|
125
|
+
callback: ({ field, ref })=>{
|
|
126
|
+
if (field.type !== 'array' && field.type !== 'blocks' || !('name' in field) || !field.name || !ref || typeof ref !== 'object') {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const value = ref[field.name];
|
|
130
|
+
const visitRows = (rows)=>{
|
|
131
|
+
if (!Array.isArray(rows)) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
for (const row of rows){
|
|
135
|
+
if (row && typeof row === 'object' && typeof row.id === 'string') {
|
|
136
|
+
existingRowIDs.add(row.id);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
if (Array.isArray(value)) {
|
|
141
|
+
visitRows(value);
|
|
142
|
+
} else if (value && typeof value === 'object') {
|
|
143
|
+
for (const localeValue of Object.values(value)){
|
|
144
|
+
visitRows(localeValue);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
config,
|
|
149
|
+
fields,
|
|
150
|
+
fillEmpty: false,
|
|
151
|
+
ref: existingDoc
|
|
152
|
+
});
|
|
153
|
+
return existingRowIDs;
|
|
154
|
+
};
|
|
155
|
+
export const copyDataWithFreshRowIDs = ({ config, data, existingDoc, fields })=>{
|
|
156
|
+
const existingRowIDs = collectExistingRowIDs({
|
|
157
|
+
config,
|
|
158
|
+
existingDoc,
|
|
159
|
+
fields
|
|
160
|
+
});
|
|
161
|
+
return copyObject({
|
|
162
|
+
config,
|
|
163
|
+
data,
|
|
164
|
+
existingRowIDs,
|
|
165
|
+
fields,
|
|
166
|
+
parentIsLocalized: false
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
//# sourceMappingURL=copyDataWithFreshRowIDs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/operations/utilities/copyDataWithFreshRowIDs.ts"],"sourcesContent":["import type { SanitizedConfig } from '../../../config/types.js'\nimport type { ArrayField, Block, BlocksField, Field } from '../../../fields/config/types.js'\n\nimport { tabHasName } from '../../../fields/config/types.js'\nimport { deepCopyObjectSimple } from '../../../utilities/deepCopyObject.js'\nimport { traverseFields } from '../../../utilities/traverseFields.js'\n\ntype LevelEntry =\n | { field: ArrayField | BlocksField; localized: boolean; type: 'rows' }\n | { fields: Field[]; localized: boolean; type: 'subfields' }\n\nconst buildLevelMap = (fields: Field[], map: Map<string, LevelEntry> = new Map()) => {\n for (const field of fields) {\n if (field.type === 'row' || field.type === 'collapsible') {\n buildLevelMap(field.fields, map)\n } else if (field.type === 'tabs') {\n for (const tab of field.tabs) {\n if (tabHasName(tab)) {\n map.set(tab.name, {\n type: 'subfields',\n fields: tab.fields,\n localized: Boolean(tab.localized),\n })\n } else {\n buildLevelMap(tab.fields, map)\n }\n }\n } else if (field.type === 'group') {\n if ('name' in field && field.name) {\n map.set(field.name, {\n type: 'subfields',\n fields: field.fields,\n localized: Boolean(field.localized),\n })\n } else {\n buildLevelMap(field.fields, map)\n }\n } else if ((field.type === 'array' || field.type === 'blocks') && field.name) {\n map.set(field.name, { type: 'rows', field, localized: Boolean(field.localized) })\n }\n }\n return map\n}\n\nconst isLocaleKeyed = (value: object, config: SanitizedConfig): boolean => {\n if (Array.isArray(value)) {\n return false\n }\n const localeCodes = config.localization ? config.localization.localeCodes : []\n const keys = Object.keys(value)\n return keys.length > 0 && keys.every((key) => localeCodes.includes(key))\n}\n\nconst resolveBlockFields = (\n field: BlocksField,\n blockType: unknown,\n config: SanitizedConfig,\n): Field[] => {\n if (typeof blockType !== 'string') {\n return []\n }\n const block =\n config.blocks?.find((b) => b.slug === blockType) ??\n field.blocks.find((b): b is Block => typeof b !== 'string' && b.slug === blockType)\n return block?.fields ?? []\n}\n\nconst copyRow = ({\n config,\n existingRowIDs,\n field,\n parentIsLocalized,\n row,\n}: {\n config: SanitizedConfig\n existingRowIDs: Set<string>\n field: ArrayField | BlocksField\n parentIsLocalized: boolean\n row: unknown\n}): unknown => {\n if (!row || typeof row !== 'object') {\n return deepCopyObjectSimple(row as never)\n }\n\n const subfields =\n field.type === 'array'\n ? field.fields\n : resolveBlockFields(field, (row as Record<string, unknown>).blockType, config)\n\n const newRow = copyObject({\n config,\n data: row as Record<string, unknown>,\n existingRowIDs,\n fields: subfields,\n parentIsLocalized,\n })\n\n if (typeof newRow.id === 'string' && !existingRowIDs.has(newRow.id)) {\n delete newRow.id\n }\n\n return newRow\n}\n\nconst copyObject = ({\n config,\n data,\n existingRowIDs,\n fields,\n parentIsLocalized,\n}: {\n config: SanitizedConfig\n data: Record<string, unknown>\n existingRowIDs: Set<string>\n fields: Field[]\n parentIsLocalized: boolean\n}): Record<string, unknown> => {\n const levelMap = buildLevelMap(fields)\n const result: Record<string, unknown> = {}\n\n for (const key of Object.keys(data)) {\n const value = data[key]\n const entry = levelMap.get(key)\n\n if (!entry || value === null || typeof value !== 'object') {\n result[key] = deepCopyObjectSimple(value as never)\n continue\n }\n\n const childParentIsLocalized = parentIsLocalized || entry.localized\n\n if (entry.type === 'subfields') {\n const valueIsLocaleKeyed =\n entry.localized && !parentIsLocalized && isLocaleKeyed(value, config)\n\n result[key] = valueIsLocaleKeyed\n ? mapLocales(value, (localeValue) =>\n copyObject({\n config,\n data: localeValue,\n existingRowIDs,\n fields: entry.fields,\n parentIsLocalized: true,\n }),\n )\n : copyObject({\n config,\n data: value as Record<string, unknown>,\n existingRowIDs,\n fields: entry.fields,\n parentIsLocalized: childParentIsLocalized,\n })\n continue\n }\n\n const copyRows = (rows: unknown) =>\n Array.isArray(rows)\n ? rows.map((row) =>\n copyRow({\n config,\n existingRowIDs,\n field: entry.field,\n parentIsLocalized: childParentIsLocalized,\n row,\n }),\n )\n : deepCopyObjectSimple(rows as never)\n\n result[key] = Array.isArray(value) ? copyRows(value) : mapLocales(value, copyRows)\n }\n\n return result\n}\n\nconst mapLocales = (\n value: object,\n copyLocaleValue: (localeValue: Record<string, unknown>) => unknown,\n): unknown => {\n if (Array.isArray(value)) {\n return deepCopyObjectSimple(value as never)\n }\n const out: Record<string, unknown> = {}\n for (const locale of Object.keys(value)) {\n const localeValue = (value as Record<string, unknown>)[locale]\n out[locale] =\n localeValue && typeof localeValue === 'object'\n ? copyLocaleValue(localeValue as Record<string, unknown>)\n : deepCopyObjectSimple(localeValue as never)\n }\n return out\n}\n\nconst collectExistingRowIDs = ({\n config,\n existingDoc,\n fields,\n}: {\n config: SanitizedConfig\n existingDoc: Record<string, unknown>\n fields: Field[]\n}): Set<string> => {\n const existingRowIDs = new Set<string>()\n\n traverseFields({\n callback: ({ field, ref }) => {\n if (\n (field.type !== 'array' && field.type !== 'blocks') ||\n !('name' in field) ||\n !field.name ||\n !ref ||\n typeof ref !== 'object'\n ) {\n return\n }\n\n const value = (ref as Record<string, unknown>)[field.name]\n\n const visitRows = (rows: unknown) => {\n if (!Array.isArray(rows)) {\n return\n }\n for (const row of rows) {\n if (\n row &&\n typeof row === 'object' &&\n typeof (row as Record<string, unknown>).id === 'string'\n ) {\n existingRowIDs.add((row as Record<string, unknown>).id as string)\n }\n }\n }\n\n if (Array.isArray(value)) {\n visitRows(value)\n } else if (value && typeof value === 'object') {\n for (const localeValue of Object.values(value as Record<string, unknown>)) {\n visitRows(localeValue)\n }\n }\n },\n config,\n fields,\n fillEmpty: false,\n ref: existingDoc,\n })\n\n return existingRowIDs\n}\n\nexport const copyDataWithFreshRowIDs = ({\n config,\n data,\n existingDoc,\n fields,\n}: {\n config: SanitizedConfig\n data: Record<string, unknown>\n existingDoc: Record<string, unknown>\n fields: Field[]\n}): Record<string, unknown> => {\n const existingRowIDs = collectExistingRowIDs({ config, existingDoc, fields })\n\n return copyObject({\n config,\n data,\n existingRowIDs,\n fields,\n parentIsLocalized: false,\n })\n}\n"],"names":["tabHasName","deepCopyObjectSimple","traverseFields","buildLevelMap","fields","map","Map","field","type","tab","tabs","set","name","localized","Boolean","isLocaleKeyed","value","config","Array","isArray","localeCodes","localization","keys","Object","length","every","key","includes","resolveBlockFields","blockType","block","blocks","find","b","slug","copyRow","existingRowIDs","parentIsLocalized","row","subfields","newRow","copyObject","data","id","has","levelMap","result","entry","get","childParentIsLocalized","valueIsLocaleKeyed","mapLocales","localeValue","copyRows","rows","copyLocaleValue","out","locale","collectExistingRowIDs","existingDoc","Set","callback","ref","visitRows","add","values","fillEmpty","copyDataWithFreshRowIDs"],"mappings":"AAGA,SAASA,UAAU,Q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B;QACAN;QACAhC;QACAiC,mBAAmB;IACrB;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/collections/operations/utilities/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAGhD,OAAO,KAAK,EACV,cAAc,EACd,UAAU,EACV,eAAe,EACf,mBAAmB,EACpB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,KAAK,EACV,UAAU,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,UAAU,EACV,6BAA6B,EAC9B,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,EACV,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,UAAU,EACX,MAAM,uBAAuB,CAAA;AAkB9B,MAAM,MAAM,wBAAwB,CAAC,KAAK,SAAS,cAAc,IAAI;IACnE,QAAQ,EAAE,OAAO,CAAA;IACjB,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,WAAW,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,KAAK,EAAE,MAAM,CAAA;IACb,cAAc,EAAE,UAAU,GAAG,UAAU,CAAA;IACvC,QAAQ,EAAE,OAAO,CAAA;IACjB,cAAc,EAAE,mBAAmB,CAAA;IACnC,aAAa,EAAE,UAAU,EAAE,CAAA;IAC3B,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,cAAc,EAAE,OAAO,CAAA;IACvB,YAAY,EAAE,OAAO,CAAA;IACrB,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,EAAE,UAAU,CAAA;IAClB,gBAAgB,EAAE,OAAO,CAAA;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,cAAc,GACzB,KAAK,SAAS,cAAc,EAC5B,OAAO,SAAS,wBAAwB,CAAC,KAAK,CAAC,uUAuB9C,wBAAwB,CAAC,KAAK,CAAC,KAAG,OAAO,CAAC,6BAA6B,CAAC,KAAK,EAAE,OAAO,CAAC,
|
|
1
|
+
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/collections/operations/utilities/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAGhD,OAAO,KAAK,EACV,cAAc,EACd,UAAU,EACV,eAAe,EACf,mBAAmB,EACpB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,KAAK,EACV,UAAU,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,UAAU,EACV,6BAA6B,EAC9B,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,EACV,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,UAAU,EACX,MAAM,uBAAuB,CAAA;AAkB9B,MAAM,MAAM,wBAAwB,CAAC,KAAK,SAAS,cAAc,IAAI;IACnE,QAAQ,EAAE,OAAO,CAAA;IACjB,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,WAAW,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,KAAK,EAAE,MAAM,CAAA;IACb,cAAc,EAAE,UAAU,GAAG,UAAU,CAAA;IACvC,QAAQ,EAAE,OAAO,CAAA;IACjB,cAAc,EAAE,mBAAmB,CAAA;IACnC,aAAa,EAAE,UAAU,EAAE,CAAA;IAC3B,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,cAAc,EAAE,OAAO,CAAA;IACvB,YAAY,EAAE,OAAO,CAAA;IACrB,OAAO,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,EAAE,UAAU,CAAA;IAClB,gBAAgB,EAAE,OAAO,CAAA;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAA;CAC9B,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,cAAc,GACzB,KAAK,SAAS,cAAc,EAC5B,OAAO,SAAS,wBAAwB,CAAC,KAAK,CAAC,uUAuB9C,wBAAwB,CAAC,KAAK,CAAC,KAAG,OAAO,CAAC,6BAA6B,CAAC,KAAK,EAAE,OAAO,CAAC,CAqXzF,CAAA"}
|
|
@@ -68,14 +68,22 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
68
68
|
// /////////////////////////////////////
|
|
69
69
|
// Delete any associated files
|
|
70
70
|
// /////////////////////////////////////
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
71
|
+
// When saving a draft on a document whose latest version is published, the file
|
|
72
|
+
// referenced by docWithLocales is still actively used by the published main document.
|
|
73
|
+
// Deleting it here would break the published document's file even though no publish
|
|
74
|
+
// is happening. Only skip deletion in this case; when the latest version is already a
|
|
75
|
+
// draft, it is safe to delete the old draft file as it is being replaced.
|
|
76
|
+
const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published';
|
|
77
|
+
if (!isDraftOverPublished) {
|
|
78
|
+
await deleteAssociatedFiles({
|
|
79
|
+
collectionConfig,
|
|
80
|
+
config,
|
|
81
|
+
doc: docWithLocales,
|
|
82
|
+
files: filesToUpload,
|
|
83
|
+
overrideDelete: false,
|
|
84
|
+
req
|
|
85
|
+
});
|
|
86
|
+
}
|
|
79
87
|
// /////////////////////////////////////
|
|
80
88
|
// beforeValidate - Fields
|
|
81
89
|
// /////////////////////////////////////
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, getLatestCollectionVersion, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideAccess: boolean\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n publishSpecificLocale?: string\n req: PayloadRequest\n select: SelectType\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n}\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n publishSpecificLocale,\n req,\n select,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const password = data?.password\n const publishAllLocales =\n !draftArg &&\n (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) ? false : true))\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n if (isSavingDraft) {\n data._status = 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Delete any associated files\n // /////////////////////////////////////\n\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // Write files to local storage\n // /////////////////////////////////////\n\n if (!collectionConfig.upload.disableLocalStorage) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: originalDoc,\n docWithLocales,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n skipValidation:\n // only skip validation for drafts when draft validation is false\n (isSavingDraft && !hasDraftValidationEnabled(collectionConfig)) ||\n // Skip validation for trash operations since they're just metadata updates\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n // Skip validation for unpublish operations — they only change _status, not document data\n unpublishAllLocales,\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let result: JsonObject = await beforeChange(beforeChangeArgs)\n let snapshotToSave: JsonObject | undefined\n\n if (config.localization && collectionConfig.versions) {\n let snapshotData: JsonObject | undefined\n let currentDoc\n\n if (collectionConfig.versions.drafts && collectionConfig.versions.drafts.localizeStatus) {\n if (publishAllLocales || unpublishAllLocales) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (!isSavingDraft) {\n // publishing a single locale\n currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: id } },\n })\n snapshotData = result\n }\n } else if (publishSpecificLocale) {\n // previous way of publishing a single locale\n currentDoc = await getLatestCollectionVersion({\n id,\n config: collectionConfig,\n payload,\n published: true,\n query: {\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n },\n req,\n })\n snapshotData = {\n ...result,\n _status: 'draft',\n }\n }\n\n if (snapshotData) {\n snapshotToSave = deepCopyObjectSimple(snapshotData || {})\n\n result = mergeLocalizedData({\n configBlockReferences: config.blocks,\n dataWithLocales: result || {},\n docWithLocales: currentDoc || {},\n fields: collectionConfig.fields,\n selectedLocales: [locale],\n })\n }\n }\n\n const dataToUpdate: JsonObject = { ...result }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n result = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n result = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: result,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n publishSpecificLocale,\n req,\n snapshot: snapshotToSave,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: result,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n}\n"],"names":["ensureUsernameOrEmail","generatePasswordSaltHash","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","getLatestCollectionVersion","saveVersion","deleteAssociatedFiles","uploadFiles","checkDocumentLockStatus","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","mergeLocalizedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","publishSpecificLocale","req","select","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","password","isSavingDraft","Boolean","_status","shouldSavePassword","auth","disableLocalStrategy","enableFields","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","draft","global","isRestoringDraftFromTrash","deletedAt","authOptions","operation","files","overrideDelete","hooks","length","hook","upload","disableLocalStorage","beforeChangeArgs","skipValidation","trash","result","snapshotToSave","localization","versions","snapshotData","currentDoc","drafts","localizeStatus","accessibleLocaleCodes","localeCodes","filterAvailableLocales","filteredLocales","locales","map","code","localeCode","db","findOne","where","equals","published","query","configBlockReferences","blocks","dataWithLocales","fields","selectedLocales","dataToUpdate","hash","salt","updatedAt","Date","toISOString","updateOne","sn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AC;YACAsE,UAAUjC;YACVkC,WAAWpE;QACb;IACF;IAEA,wCAAwC;IACxC,qBAAqB;IACrB,wCAAwC;IAExCiC,SAAS,MAAMpE,UAAU;QACvBiD,YAAYjC;QACZkC,SAASlB,IAAIkB,OAAO;QACpB/B;QACAgC,KAAKiB;QACLhB,OAAO/B;QACPC;QACA+B,QAAQ;QACR7B;QACAC;QACAG;QACAI;QACAC;QACAC;IACF;IAEA,wCAAwC;IACxC,yBAAyB;IACzB,wCAAwC;IAExC,IAAIlB,iBAAiB4C,KAAK,EAAE5D,WAAW6D,QAAQ;QAC7C,KAAK,MAAMC,QAAQ9C,iBAAiB4C,KAAK,CAAC5D,SAAS,CAAE;YACnDoE,SACE,AAAC,MAAMN,KAAK;gBACVb,YAAYjC;gBACZkC,SAASlB,IAAIkB,OAAO;gBACpBC,KAAKiB;gBACL3C;gBACAO;YACF,MAAOoC;QACX;IACF;IAEA,wCAAwC;IACxC,uBAAuB;IACvB,wCAAwC;IAExCA,SAAS,MAAMrE,YAAY;QACzBkD,YAAYjC;QACZkC,SAASlB,IAAIkB,OAAO;QACpBhC;QACAiC,KAAKiB;QACLf,QAAQ;QACRI,WAAW;QACX+C,aAAaxD;QACbhB;IACF;IAEA,wCAAwC;IACxC,2BAA2B;IAC3B,wCAAwC;IAExC,IAAIhB,iBAAiB4C,KAAK,EAAE7D,aAAa8D,QAAQ;QAC/C,KAAK,MAAMC,QAAQ9C,iBAAiB4C,KAAK,CAAC7D,WAAW,CAAE;YACrDqE,SACE,AAAC,MAAMN,KAAK;gBACVb,YAAYjC;gBACZkC,SAASlB,IAAIkB,OAAO;gBACpBhC;gBACAiC,KAAKiB;gBACLX,WAAW;gBACXhC;gBACA+E,aAAaxD;gBACbhB;YACF,MAAOoC;QACX;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, getLatestCollectionVersion, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideAccess: boolean\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n publishSpecificLocale?: string\n req: PayloadRequest\n select: SelectType\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n}\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n publishSpecificLocale,\n req,\n select,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const password = data?.password\n const publishAllLocales =\n !draftArg &&\n (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) ? false : true))\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n if (isSavingDraft) {\n data._status = 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Delete any associated files\n // /////////////////////////////////////\n\n // When saving a draft on a document whose latest version is published, the file\n // referenced by docWithLocales is still actively used by the published main document.\n // Deleting it here would break the published document's file even though no publish\n // is happening. Only skip deletion in this case; when the latest version is already a\n // draft, it is safe to delete the old draft file as it is being replaced.\n const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published'\n\n if (!isDraftOverPublished) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n }\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // Write files to local storage\n // /////////////////////////////////////\n\n if (!collectionConfig.upload.disableLocalStorage) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: originalDoc,\n docWithLocales,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n skipValidation:\n // only skip validation for drafts when draft validation is false\n (isSavingDraft && !hasDraftValidationEnabled(collectionConfig)) ||\n // Skip validation for trash operations since they're just metadata updates\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n // Skip validation for unpublish operations — they only change _status, not document data\n unpublishAllLocales,\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let result: JsonObject = await beforeChange(beforeChangeArgs)\n let snapshotToSave: JsonObject | undefined\n\n if (config.localization && collectionConfig.versions) {\n let snapshotData: JsonObject | undefined\n let currentDoc\n\n if (collectionConfig.versions.drafts && collectionConfig.versions.drafts.localizeStatus) {\n if (publishAllLocales || unpublishAllLocales) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (!isSavingDraft) {\n // publishing a single locale\n currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: id } },\n })\n snapshotData = result\n }\n } else if (publishSpecificLocale) {\n // previous way of publishing a single locale\n currentDoc = await getLatestCollectionVersion({\n id,\n config: collectionConfig,\n payload,\n published: true,\n query: {\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n },\n req,\n })\n snapshotData = {\n ...result,\n _status: 'draft',\n }\n }\n\n if (snapshotData) {\n snapshotToSave = deepCopyObjectSimple(snapshotData || {})\n\n result = mergeLocalizedData({\n configBlockReferences: config.blocks,\n dataWithLocales: result || {},\n docWithLocales: currentDoc || {},\n fields: collectionConfig.fields,\n selectedLocales: [locale],\n })\n }\n }\n\n const dataToUpdate: JsonObject = { ...result }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n result = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n result = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: result,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n publishSpecificLocale,\n req,\n snapshot: snapshotToSave,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: result,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n}\n"],"names":["ensureUsernameOrEmail","generatePasswordSaltHash","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","getLatestCollectionVersion","saveVersion","deleteAssociatedFiles","uploadFiles","checkDocumentLockStatus","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","mergeLocalizedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","publishSpecificLocale","req","select","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","password","isSavingDraft","Boolean","_status","shouldSavePassword","auth","disableLocalStrategy","enableFields","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","draft","global","isRestoringDraftFromTrash","deletedAt","authOptions","operation","isDraftOverPublished","files","overrideDelete","hooks","length","hook","upload","disableLocalStorage","beforeChangeArgs","skipValidation","trash","result","snapshotToSave","localization","versions","snapshotData","currentDoc","drafts","localizeStatus","accessibleLocaleCodes","localeCodes","filterAvailableLocales","filteredLocales","locales","map","code","localeCode","db","findOne","where","equals","published","query","configBlockReferences","blocks","dataWithLocales","fields","selectedLocales","dataToUpdate","hash","salt","updatedAt","Date","toISOString","updateOne","snapshot","unpublish","previousDoc"],"mappings":"AAwB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ACX;IACF;IAEA,OAAOA;AACT,EAAC"}
|
package/dist/config/build.js
CHANGED
|
@@ -5,11 +5,12 @@ import { sanitizeConfig } from './sanitize.js';
|
|
|
5
5
|
* @returns Built and sanitized Payload Config
|
|
6
6
|
*/ export async function buildConfig(config) {
|
|
7
7
|
if (Array.isArray(config.plugins)) {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
const sorted = [
|
|
9
|
+
...config.plugins
|
|
10
|
+
].sort((a, b)=>(a.order ?? 0) - (b.order ?? 0));
|
|
11
|
+
for (const plugin of sorted){
|
|
12
|
+
config = await plugin(config);
|
|
11
13
|
}
|
|
12
|
-
return await sanitizeConfig(configAfterPlugins);
|
|
13
14
|
}
|
|
14
15
|
return await sanitizeConfig(config);
|
|
15
16
|
}
|
package/dist/config/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/build.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from './types.js'\n\nimport { sanitizeConfig } from './sanitize.js'\n\n/**\n * @description Builds and validates Payload configuration\n * @param config Payload Config\n * @returns Built and sanitized Payload Config\n */\nexport async function buildConfig(config: Config): Promise<SanitizedConfig> {\n if (Array.isArray(config.plugins)) {\n
|
|
1
|
+
{"version":3,"sources":["../../src/config/build.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from './types.js'\n\nimport { sanitizeConfig } from './sanitize.js'\n\n/**\n * @description Builds and validates Payload configuration\n * @param config Payload Config\n * @returns Built and sanitized Payload Config\n */\nexport async function buildConfig(config: Config): Promise<SanitizedConfig> {\n if (Array.isArray(config.plugins)) {\n const sorted = [...config.plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))\n\n for (const plugin of sorted) {\n config = await plugin(config)\n }\n }\n\n return await sanitizeConfig(config)\n}\n"],"names":["sanitizeConfig","buildConfig","config","Array","isArray","plugins","sorted","sort","a","b","order","plugin"],"mappings":"AAEA,SAASA,cAAc,QAAQ,gBAAe;AAE9C;;;;CAIC,GACD,OAAO,eAAeC,YAAYC,MAAc;IAC9C,IAAIC,MAAMC,OAAO,CAACF,OAAOG,OAAO,GAAG;QACjC,MAAMC,SAAS;eAAIJ,OAAOG,OAAO;SAAC,CAACE,IAAI,CAAC,CAACC,GAAGC,IAAM,AAACD,CAAAA,EAAEE,KAAK,IAAI,CAAA,IAAMD,CAAAA,EAAEC,KAAK,IAAI,CAAA;QAE/E,KAAK,MAAMC,UAAUL,OAAQ;YAC3BJ,SAAS,MAAMS,OAAOT;QACxB;IACF;IAEA,OAAO,MAAMF,eAAeE;AAC9B"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Config, Plugin, PluginsMap } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Helper for authoring plugins with order, slug, and typed options.
|
|
4
|
+
* Eliminates boilerplate and ensures metadata is always set consistently.
|
|
5
|
+
*
|
|
6
|
+
* The `plugin` function receives a single object containing `config`, `plugins`
|
|
7
|
+
* (a slug-keyed map of other plugins), and any user-provided options spread in.
|
|
8
|
+
*
|
|
9
|
+
* @experimental
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* // With options:
|
|
13
|
+
* export const seoPlugin = definePlugin<SEOPluginOptions>({
|
|
14
|
+
* slug: 'plugin-seo',
|
|
15
|
+
* order: 10,
|
|
16
|
+
* plugin: ({ config, plugins, collections }) => ({ ...config }),
|
|
17
|
+
* })
|
|
18
|
+
*
|
|
19
|
+
* // Without options:
|
|
20
|
+
* export const myPlugin = definePlugin({
|
|
21
|
+
* slug: 'my-plugin',
|
|
22
|
+
* plugin: ({ config }) => ({ ...config }),
|
|
23
|
+
* })
|
|
24
|
+
*/
|
|
25
|
+
export declare function definePlugin(descriptor: {
|
|
26
|
+
order?: number;
|
|
27
|
+
plugin: (args: {
|
|
28
|
+
config: Config;
|
|
29
|
+
plugins: PluginsMap;
|
|
30
|
+
}) => Config | Promise<Config>;
|
|
31
|
+
slug?: string;
|
|
32
|
+
}): () => Plugin;
|
|
33
|
+
export declare function definePlugin<TOptions extends Record<string, unknown>>(descriptor: {
|
|
34
|
+
order?: number;
|
|
35
|
+
plugin: (args: {
|
|
36
|
+
config: Config;
|
|
37
|
+
plugins: PluginsMap;
|
|
38
|
+
} & TOptions) => Config | Promise<Config>;
|
|
39
|
+
slug?: string;
|
|
40
|
+
}): (options: TOptions) => Plugin;
|
|
41
|
+
//# sourceMappingURL=definePlugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"definePlugin.d.ts","sourceRoot":"","sources":["../../src/config/definePlugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAc5D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE;IACvC,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,CAAC,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,UAAU,CAAA;KAAE,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;IACnF,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,GAAG,MAAM,MAAM,CAAA;AAChB,wBAAgB,YAAY,CAAC,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,UAAU,EAAE;IACjF,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,CAAC,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,UAAU,CAAA;KAAE,GAAG,QAAQ,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;IAC9F,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,GAAG,CAAC,OAAO,EAAE,QAAQ,KAAK,MAAM,CAAA"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
function buildPluginsMap(plugins) {
|
|
2
|
+
const map = {};
|
|
3
|
+
if (plugins) {
|
|
4
|
+
for (const p of plugins){
|
|
5
|
+
if (p.slug) {
|
|
6
|
+
map[p.slug] = p;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
return map;
|
|
11
|
+
}
|
|
12
|
+
export function definePlugin(descriptor) {
|
|
13
|
+
return (options)=>{
|
|
14
|
+
const pluginFn = (config)=>{
|
|
15
|
+
const plugins = buildPluginsMap(config.plugins);
|
|
16
|
+
const args = {
|
|
17
|
+
...options,
|
|
18
|
+
config,
|
|
19
|
+
plugins
|
|
20
|
+
};
|
|
21
|
+
return descriptor.plugin(args);
|
|
22
|
+
};
|
|
23
|
+
pluginFn.options = options;
|
|
24
|
+
if (descriptor.slug !== undefined) {
|
|
25
|
+
pluginFn.slug = descriptor.slug;
|
|
26
|
+
}
|
|
27
|
+
if (descriptor.order !== undefined) {
|
|
28
|
+
pluginFn.order = descriptor.order;
|
|
29
|
+
}
|
|
30
|
+
return pluginFn;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=definePlugin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/config/definePlugin.ts"],"sourcesContent":["import type { Config, Plugin, PluginsMap } from './types.js'\n\nfunction buildPluginsMap(plugins: Plugin[] | undefined): PluginsMap {\n const map: Record<string, Plugin | undefined> = {}\n if (plugins) {\n for (const p of plugins) {\n if (p.slug) {\n map[p.slug] = p\n }\n }\n }\n return map as PluginsMap\n}\n\n/**\n * Helper for authoring plugins with order, slug, and typed options.\n * Eliminates boilerplate and ensures metadata is always set consistently.\n *\n * The `plugin` function receives a single object containing `config`, `plugins`\n * (a slug-keyed map of other plugins), and any user-provided options spread in.\n *\n * @experimental\n *\n * @example\n * // With options:\n * export const seoPlugin = definePlugin<SEOPluginOptions>({\n * slug: 'plugin-seo',\n * order: 10,\n * plugin: ({ config, plugins, collections }) => ({ ...config }),\n * })\n *\n * // Without options:\n * export const myPlugin = definePlugin({\n * slug: 'my-plugin',\n * plugin: ({ config }) => ({ ...config }),\n * })\n */\nexport function definePlugin(descriptor: {\n order?: number\n plugin: (args: { config: Config; plugins: PluginsMap }) => Config | Promise<Config>\n slug?: string\n}): () => Plugin\nexport function definePlugin<TOptions extends Record<string, unknown>>(descriptor: {\n order?: number\n plugin: (args: { config: Config; plugins: PluginsMap } & TOptions) => Config | Promise<Config>\n slug?: string\n}): (options: TOptions) => Plugin\nexport function definePlugin<TOptions extends Record<string, unknown>>(descriptor: {\n order?: number\n plugin: (args: { config: Config; plugins: PluginsMap } & TOptions) => Config | Promise<Config>\n slug?: string\n}): (options?: TOptions) => Plugin {\n return (options?: TOptions): Plugin => {\n const pluginFn: Plugin = (config) => {\n const plugins = buildPluginsMap(config.plugins)\n\n const args = {\n ...options,\n config,\n plugins,\n } as { config: Config; plugins: PluginsMap } & TOptions\n\n return descriptor.plugin(args)\n }\n\n pluginFn.options = options as Record<string, unknown>\n\n if (descriptor.slug !== undefined) {\n pluginFn.slug = descriptor.slug\n }\n if (descriptor.order !== undefined) {\n pluginFn.order = descriptor.order\n }\n\n return pluginFn\n }\n}\n"],"names":["buildPluginsMap","plugins","map","p","slug","definePlugin","descriptor","options","pluginFn","config","args","plugin","undefined","order"],"mappings":"AAEA,SAASA,gBAAgBC,OAA6B;IACpD,MAAMC,MAA0C,CAAC;IACjD,IAAID,SAAS;QACX,KAAK,MAAME,KAAKF,QAAS;YACvB,IAAIE,EAAEC,IAAI,EAAE;gBACVF,GAAG,CAACC,EAAEC,IAAI,CAAC,GAAGD;YAChB;QACF;IACF;IACA,OAAOD;AACT;AAmCA,OAAO,SAASG,aAAuDC,UAItE;IACC,OAAO,CAACC;QACN,MAAMC,WAAmB,CAACC;YACxB,MAAMR,UAAUD,gBAAgBS,OAAOR,OAAO;YAE9C,MAAMS,OAAO;gBACX,GAAGH,OAAO;gBACVE;gBACAR;YACF;YAEA,OAAOK,WAAWK,MAAM,CAACD;QAC3B;QAEAF,SAASD,OAAO,GAAGA;QAEnB,IAAID,WAAWF,IAAI,KAAKQ,WAAW;YACjCJ,SAASJ,IAAI,GAAGE,WAAWF,IAAI;QACjC;QACA,IAAIE,WAAWO,KAAK,KAAKD,WAAW;YAClCJ,SAASK,KAAK,GAAGP,WAAWO,KAAK;QACnC;QAEA,OAAOL;IACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/config/orderable/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAEnD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/config/orderable/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAEnD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,aAAa,CAAA;AAgB5E,eAAO,MAAM,yBAAyB,eACxB,gBAAgB,UACpB,MAAM,uBACO,MAAM,EAAE,+BACA,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,kBA2F9D,CAAA;AAED;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,cAAc,EAAE,MAAM,CAAA;IACtB,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,YAAY,EAAE,SAAS,GAAG,MAAM,CAAA;IAChC,kBAAkB,EAAE,MAAM,CAAA;IAC1B,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAA;QACV,GAAG,EAAE,MAAM,CAAA;KACZ,CAAA;CACF,CAAA;AAED,eAAO,MAAM,oBAAoB,WACvB,eAAe,8BACK,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,SAiN7D,CAAA"}
|
|
@@ -4,8 +4,10 @@ import { APIError } from '../../errors/index.js';
|
|
|
4
4
|
import { sanitizeField } from '../../fields/config/sanitize.js';
|
|
5
5
|
import { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js';
|
|
6
6
|
import { commitTransaction } from '../../utilities/commitTransaction.js';
|
|
7
|
+
import { hasDraftsEnabled } from '../../utilities/getVersionsConfig.js';
|
|
7
8
|
import { initTransaction } from '../../utilities/initTransaction.js';
|
|
8
9
|
import { killTransaction } from '../../utilities/killTransaction.js';
|
|
10
|
+
import { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion.js';
|
|
9
11
|
import { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js';
|
|
10
12
|
import { getJoinScopeContext } from './utils/getJoinScopeContext.js';
|
|
11
13
|
import { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js';
|
|
@@ -259,8 +261,28 @@ export const addOrderableEndpoint = (config, joinFieldPathsByCollection)=>{
|
|
|
259
261
|
// Currently N (= docsToMove.length) is always 1. Maybe in the future we will
|
|
260
262
|
// allow dragging and reordering multiple documents at once via the UI.
|
|
261
263
|
const orderValues = newKeyWillBe === 'greater' ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMove.length) : generateNKeysBetween(adjacentDocKey, targetKey, docsToMove.length);
|
|
264
|
+
const draftsEnabled = hasDraftsEnabled(collection);
|
|
262
265
|
// Update each document with its new order value
|
|
263
266
|
for (const [index, id] of docsToMove.entries()){
|
|
267
|
+
let draft;
|
|
268
|
+
if (draftsEnabled) {
|
|
269
|
+
const latestVersion = await getLatestCollectionVersion({
|
|
270
|
+
id,
|
|
271
|
+
config: collection,
|
|
272
|
+
payload: req.payload,
|
|
273
|
+
query: {
|
|
274
|
+
collection: collection.slug,
|
|
275
|
+
req,
|
|
276
|
+
where: {
|
|
277
|
+
id: {
|
|
278
|
+
equals: id
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
req
|
|
283
|
+
});
|
|
284
|
+
draft = latestVersion?._status === 'draft';
|
|
285
|
+
}
|
|
264
286
|
await req.payload.update({
|
|
265
287
|
id,
|
|
266
288
|
collection: collection.slug,
|
|
@@ -268,6 +290,7 @@ export const addOrderableEndpoint = (config, joinFieldPathsByCollection)=>{
|
|
|
268
290
|
[orderableFieldName]: orderValues[index]
|
|
269
291
|
},
|
|
270
292
|
depth: 0,
|
|
293
|
+
draft,
|
|
271
294
|
req
|
|
272
295
|
});
|
|
273
296
|
}
|