@sanity/cross-dataset-duplicator 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js DELETED
@@ -1,1104 +0,0 @@
1
- import { useClient, useSchema, useWorkspaces, Preview, definePlugin } from 'sanity';
2
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
- import React, { useState, useEffect, useCallback, createContext, useContext } from 'react';
4
- import { InfoOutlineIcon, ArrowRightIcon, SearchIcon, LaunchIcon } from '@sanity/icons';
5
- import { useSecrets, SettingsView } from '@sanity/studio-secrets';
6
- import { Card, Flex, Button, Badge, Tooltip, Box, Text, useTheme, Container, Stack, Label, Select, Checkbox, Spinner, Grid, TextInput } from '@sanity/ui';
7
- import mapLimit from 'async/mapLimit';
8
- import asyncify from 'async/asyncify';
9
- import { extractWithPath } from '@sanity/mutator';
10
- import { dset } from 'dset';
11
- import { isAssetId, isSanityFileAsset } from '@sanity/asset-utils';
12
- function createInitialMessage() {
13
- let docCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
14
- let refsCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
15
- const message = [docCount === 1 ? "This Document contains" : "These ".concat(docCount, " Documents contain"), refsCount === 1 ? "1 Reference." : "".concat(refsCount, " References."), refsCount === 1 ? "That Document" : "Those Documents", "may have References too. If referenced Documents do not exist at the target Destination, this transaction will fail."];
16
- return message.join(" ");
17
- }
18
- const stickyStyles = function () {
19
- let isDarkMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
20
- return {
21
- position: "sticky",
22
- top: 0,
23
- zIndex: 100,
24
- backgroundColor: isDarkMode ? "rgba(10,10,10,0.95)" : "rgba(255,255,255,0.95)"
25
- };
26
- };
27
- async function getDocumentsInArray(options) {
28
- const {
29
- fetchIds,
30
- client,
31
- pluginConfig,
32
- currentIds,
33
- projection
34
- } = options;
35
- const collection = [];
36
- const filter = ["_id in $fetchIds", pluginConfig.filter].filter(Boolean).join(" && ");
37
- const query = "*[".concat(filter, "]").concat(projection != null ? projection : "");
38
- const data = await client.fetch(query, {
39
- fetchIds: fetchIds != null ? fetchIds : []
40
- });
41
- if (!(data == null ? void 0 : data.length)) {
42
- return [];
43
- }
44
- const localCurrentIds = currentIds != null ? currentIds : /* @__PURE__ */new Set();
45
- const newDataIds = new Set(data.map(dataDoc => dataDoc._id).filter(id => (currentIds == null ? void 0 : currentIds.size) ? !localCurrentIds.has(id) : Boolean(id)));
46
- if (newDataIds.size) {
47
- collection.push(...data);
48
- localCurrentIds.add(...newDataIds);
49
- await Promise.all(data.map(async doc => {
50
- const expr = ".._ref";
51
- const references = extractWithPath(expr, doc).map(ref => ref.value);
52
- if (references.length) {
53
- const newReferenceIds = new Set(references.filter(ref => !localCurrentIds.has(ref)));
54
- if (newReferenceIds.size) {
55
- const referenceDocs = await getDocumentsInArray({
56
- fetchIds: Array.from(newReferenceIds),
57
- currentIds: localCurrentIds,
58
- client,
59
- pluginConfig
60
- });
61
- if (referenceDocs == null ? void 0 : referenceDocs.length) {
62
- collection.push(...referenceDocs);
63
- }
64
- }
65
- }
66
- }));
67
- }
68
- const uniqueCollection = collection.filter(Boolean).reduce((acc, cur) => {
69
- if (acc.some(doc => doc._id === cur._id)) {
70
- return acc;
71
- }
72
- return [...acc, cur];
73
- }, []);
74
- return uniqueCollection;
75
- }
76
- const buttons = ["All", "None", null, "New", "Existing", "Older", null, "Documents", "Assets"];
77
- function SelectButtons(props) {
78
- const {
79
- payload,
80
- setPayload
81
- } = props;
82
- const [disabledActions, setDisabledActions] = useState([]);
83
- useEffect(() => {
84
- if (!(disabledActions == null ? void 0 : disabledActions.length) && payload.every(item => item.include)) {
85
- setDisabledActions(["ALL"]);
86
- }
87
- }, [disabledActions == null ? void 0 : disabledActions.length, payload]);
88
- function handleSelectButton(action) {
89
- if (!action || !payload.length) return;
90
- const newPayload = [...payload];
91
- switch (action) {
92
- case "ALL":
93
- newPayload.map(item => item.include = true);
94
- break;
95
- case "NONE":
96
- newPayload.map(item => item.include = false);
97
- break;
98
- case "NEW":
99
- newPayload.map(item => item.include = Boolean(item.status === "CREATE"));
100
- break;
101
- case "EXISTING":
102
- newPayload.map(item => item.include = Boolean(item.status === "EXISTS"));
103
- break;
104
- case "OLDER":
105
- newPayload.map(item => item.include = Boolean(item.status === "OVERWRITE"));
106
- break;
107
- case "ASSETS":
108
- newPayload.map(item => item.include = isAssetId(item.doc._id));
109
- break;
110
- case "DOCUMENTS":
111
- newPayload.map(item => item.include = !isAssetId(item.doc._id));
112
- break;
113
- }
114
- setDisabledActions([action]);
115
- setPayload(newPayload);
116
- }
117
- return /* @__PURE__ */jsx(Card, {
118
- padding: 1,
119
- radius: 3,
120
- shadow: 1,
121
- children: /* @__PURE__ */jsx(Flex, {
122
- gap: 2,
123
- wrap: "wrap",
124
- children: buttons.map((action, actionIndex) => action ? /* @__PURE__ */jsx(Button, {
125
- fontSize: 1,
126
- mode: "bleed",
127
- padding: 2,
128
- text: action,
129
- disabled: disabledActions.includes(action.toUpperCase()),
130
- onClick: () => handleSelectButton(action.toUpperCase())
131
- }, action) :
132
- // eslint-disable-next-line react/no-array-index-key
133
- /* @__PURE__ */
134
- jsx(Card, {
135
- borderLeft: true
136
- }, "divider-".concat(actionIndex)))
137
- })
138
- });
139
- }
140
- const documentTones = {
141
- EXISTS: "primary",
142
- OVERWRITE: "critical",
143
- UPDATE: "caution",
144
- CREATE: "positive",
145
- UNPUBLISHED: "caution"
146
- };
147
- const assetTones = {
148
- EXISTS: "critical",
149
- OVERWRITE: "critical",
150
- UPDATE: "critical",
151
- CREATE: "positive",
152
- UNPUBLISHED: "default"
153
- };
154
- const documentMessages = {
155
- // Only happens once document is copied the first time, and _updatedAt is the same
156
- EXISTS: "This document already exists at the Destination with the same ID with the same Updated time.",
157
- // Is true immediately after transaction as _updatedAt is updated by API after mutation
158
- // Is also true if the document at the destination has been manually modified
159
- // Presently, the plugin doesn't actually compare the two documents
160
- OVERWRITE: "A newer version of this document exists at the Destination, and it will be overwritten with this version.",
161
- // Document at destination is older
162
- UPDATE: "An older version of this document exists at the Destination, and it will be overwritten with this version.",
163
- // Document at destination doesn't exist
164
- CREATE: "This document will be created at the destination.",
165
- UNPUBLISHED: "A Draft version of this Document exists in this Dataset, but only the Published version will be duplicated to the destination."
166
- };
167
- const assetMessages = {
168
- EXISTS: "This Asset already exists at the Destination",
169
- OVERWRITE: "This Asset already exists at the Destination",
170
- UPDATE: "This Asset already exists at the Destination",
171
- CREATE: "This Asset does not yet exist at the Destination",
172
- UNPUBLISHED: ""
173
- };
174
- const assetStatus = {
175
- EXISTS: "RE-UPLOAD",
176
- OVERWRITE: "RE-UPLOAD",
177
- UPDATE: "RE-UPLOAD",
178
- CREATE: "UPLOAD",
179
- UNPUBLISHED: ""
180
- };
181
- function StatusBadge(props) {
182
- const {
183
- status,
184
- isAsset
185
- } = props;
186
- if (!status) {
187
- return null;
188
- }
189
- const badgeTone = isAsset ? assetTones[status] : documentTones[status];
190
- if (!badgeTone) {
191
- return /* @__PURE__ */jsx(Badge, {
192
- muted: true,
193
- padding: 2,
194
- fontSize: 1,
195
- mode: "outline",
196
- children: "Checking..."
197
- });
198
- }
199
- const badgeText = isAsset ? assetMessages[status] : documentMessages[status];
200
- const badgeStatus = isAsset ? assetStatus[status] : status;
201
- return /* @__PURE__ */jsx(Tooltip, {
202
- content: /* @__PURE__ */jsx(Box, {
203
- padding: 3,
204
- style: {
205
- maxWidth: 200
206
- },
207
- children: /* @__PURE__ */jsx(Text, {
208
- size: 1,
209
- children: badgeText
210
- })
211
- }),
212
- fallbackPlacements: ["right", "left"],
213
- placement: "top",
214
- portal: true,
215
- children: /* @__PURE__ */jsxs(Badge, {
216
- muted: true,
217
- padding: 3,
218
- fontSize: 1,
219
- tone: badgeTone,
220
- mode: "outline",
221
- children: [badgeStatus, /* @__PURE__ */jsx(Box, {
222
- marginLeft: 2,
223
- display: "inline-block",
224
- as: "span",
225
- children: /* @__PURE__ */jsx(InfoOutlineIcon, {})
226
- })]
227
- })
228
- });
229
- }
230
- function Feedback(props) {
231
- const {
232
- children,
233
- tone = "caution"
234
- } = props;
235
- return /* @__PURE__ */jsx(Card, {
236
- padding: 3,
237
- radius: 2,
238
- shadow: 1,
239
- tone,
240
- children: /* @__PURE__ */jsx(Text, {
241
- size: 1,
242
- children
243
- })
244
- });
245
- }
246
- const clientConfig = {
247
- apiVersion: "2021-05-19"
248
- };
249
- function Duplicator(props) {
250
- var _a, _b, _c;
251
- const {
252
- docs,
253
- token,
254
- pluginConfig,
255
- onDuplicated
256
- } = props;
257
- const isDarkMode = useTheme().sanity.color.dark;
258
- const originClient = useClient(clientConfig);
259
- const schema = useSchema();
260
- const workspaces = useWorkspaces();
261
- const workspacesOptions = workspaces.map(workspace => ({
262
- ...workspace,
263
- disabled: workspace.dataset === originClient.config().dataset && workspace.projectId === originClient.config().projectId
264
- }));
265
- const [destination, setDestination] = useState(workspaces.length ? (_a = workspacesOptions.find(space => !space.disabled)) != null ? _a : null : null);
266
- const [message, setMessage] = useState(null);
267
- const [payload, setPayload] = useState([]);
268
- const [hasReferences, setHasReferences] = useState(false);
269
- const [isDuplicating, setIsDuplicating] = useState(false);
270
- const [isGathering, setIsGathering] = useState(false);
271
- const [progress, setProgress] = useState([0, 0]);
272
- useEffect(() => {
273
- const expr = ".._ref";
274
- const initialRefs = [];
275
- const initialPayload = [];
276
- docs.forEach(doc => {
277
- const refs = extractWithPath(expr, doc).map(ref => ref.value);
278
- initialRefs.push(...refs);
279
- initialPayload.push({
280
- include: true,
281
- doc
282
- });
283
- });
284
- updatePayloadStatuses(initialPayload);
285
- const docCount = docs.length;
286
- const refsCount = initialRefs.length;
287
- if (initialRefs.length) {
288
- setHasReferences(true);
289
- setMessage({
290
- tone: "caution",
291
- text: createInitialMessage(docCount, refsCount)
292
- });
293
- }
294
- }, [docs]);
295
- useEffect(() => {
296
- updatePayloadStatuses();
297
- }, [destination]);
298
- async function updatePayloadStatuses() {
299
- let newPayload = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
300
- const payloadActual = newPayload.length ? newPayload : payload;
301
- if (!payloadActual.length || !(destination == null ? void 0 : destination.name)) {
302
- return;
303
- }
304
- const payloadIds = payloadActual.map(_ref => {
305
- let {
306
- doc
307
- } = _ref;
308
- return doc._id;
309
- });
310
- const destinationClient = originClient.withConfig({
311
- ...clientConfig,
312
- dataset: destination.dataset,
313
- projectId: destination.projectId
314
- });
315
- const destinationData = await destinationClient.fetch("*[_id in $payloadIds]{ _id, _updatedAt }", {
316
- payloadIds
317
- });
318
- const updatedPayload = payloadActual.map(item => {
319
- var _a2;
320
- const existingDoc = destinationData.find(doc => doc._id === item.doc._id);
321
- if ((existingDoc == null ? void 0 : existingDoc._updatedAt) && ((_a2 = item == null ? void 0 : item.doc) == null ? void 0 : _a2._updatedAt)) {
322
- if (existingDoc._updatedAt === item.doc._updatedAt) {
323
- item.status = "EXISTS";
324
- } else if (existingDoc._updatedAt && item.doc._updatedAt) {
325
- item.status = new Date(existingDoc._updatedAt) > new Date(item.doc._updatedAt) ? // Document at destination is newer
326
- "OVERWRITE" : // Document at destination is older
327
- "UPDATE";
328
- }
329
- } else {
330
- item.status = "CREATE";
331
- }
332
- return item;
333
- });
334
- setPayload(updatedPayload);
335
- }
336
- function handleCheckbox(_id) {
337
- const updatedPayload = payload.map(item => {
338
- if (item.doc._id === _id) {
339
- item.include = !item.include;
340
- }
341
- return item;
342
- });
343
- setPayload(updatedPayload);
344
- }
345
- async function handleReferences() {
346
- setIsGathering(true);
347
- const docIds = docs.map(doc => doc._id);
348
- const payloadDocs = await getDocumentsInArray({
349
- fetchIds: docIds,
350
- client: originClient,
351
- pluginConfig
352
- });
353
- const draftDocs = await getDocumentsInArray({
354
- fetchIds: docIds.map(id => "drafts.".concat(id)),
355
- client: originClient,
356
- projection: "{_id}",
357
- pluginConfig
358
- });
359
- const draftDocsIds = new Set(draftDocs.map(_ref2 => {
360
- let {
361
- _id
362
- } = _ref2;
363
- return _id;
364
- }));
365
- const payloadShaped = payloadDocs.map(doc => ({
366
- doc,
367
- // Include this in the transaction?
368
- include: true,
369
- // Does it exist at the destination?
370
- status: void 0,
371
- // Does it have any drafts?
372
- hasDraft: draftDocsIds.has("drafts.".concat(doc._id))
373
- }));
374
- setPayload(payloadShaped);
375
- updatePayloadStatuses(payloadShaped);
376
- setIsGathering(false);
377
- }
378
- async function handleDuplicate() {
379
- if (!destination) {
380
- return;
381
- }
382
- setIsDuplicating(true);
383
- const assetsCount = payload.filter(_ref3 => {
384
- let {
385
- doc,
386
- include
387
- } = _ref3;
388
- return include && isAssetId(doc._id);
389
- }).length;
390
- let currentProgress = 0;
391
- setProgress([currentProgress, assetsCount]);
392
- setMessage({
393
- text: "Duplicating...",
394
- tone: "transparent"
395
- });
396
- const destinationClient = originClient.withConfig({
397
- ...clientConfig,
398
- dataset: destination.dataset,
399
- projectId: destination.projectId
400
- });
401
- const transactionDocs = [];
402
- const svgMaps = [];
403
- async function fetchDoc(doc) {
404
- if (isAssetId(doc._id)) {
405
- const typeIsFile = isSanityFileAsset(doc);
406
- const downloadUrl = typeIsFile ? doc.url : "".concat(doc.url, "?dlRaw=true");
407
- const downloadConfig = typeIsFile ? {} : {
408
- headers: {
409
- Authorization: "Bearer ".concat(token)
410
- }
411
- };
412
- await fetch(downloadUrl, downloadConfig).then(async res => {
413
- const assetData = await res.blob();
414
- const options = {
415
- filename: doc.originalFilename
416
- };
417
- const assetDoc = await destinationClient.assets.upload(typeIsFile ? "file" : "image", assetData, options);
418
- if ((doc == null ? void 0 : doc.extension) === "svg") {
419
- svgMaps.push({
420
- old: doc._id,
421
- new: assetDoc._id
422
- });
423
- }
424
- transactionDocs.push(assetDoc);
425
- doc.url = assetDoc.url;
426
- doc.path = assetDoc.path;
427
- });
428
- currentProgress += 1;
429
- setMessage({
430
- text: "Duplicating ".concat(currentProgress, "/").concat(assetsCount, " ").concat(assetsCount === 1 ? "Assets" : "Assets"),
431
- tone: "default"
432
- });
433
- setProgress([currentProgress, assetsCount]);
434
- }
435
- return transactionDocs.push(doc);
436
- }
437
- const result = new Promise((resolve, reject) => {
438
- const payloadIncludedDocs = payload.filter(item => item.include).map(item => item.doc);
439
- mapLimit(payloadIncludedDocs, 3, asyncify(fetchDoc), err => {
440
- if (err) {
441
- setIsDuplicating(false);
442
- setMessage({
443
- tone: "critical",
444
- text: "Duplication Failed"
445
- });
446
- console.error(err);
447
- reject(new Error("Duplication Failed"));
448
- }
449
- resolve();
450
- });
451
- });
452
- await result;
453
- const transactionDocsMapped = transactionDocs.map(doc => {
454
- const expr = ".._ref";
455
- const references = extractWithPath(expr, doc);
456
- if (!references.length) {
457
- return doc;
458
- }
459
- references.forEach(ref => {
460
- var _a2;
461
- const newRefValue = (_a2 = svgMaps.find(asset => asset.old === ref.value)) == null ? void 0 : _a2.new;
462
- if (newRefValue) {
463
- const refPath = ref.path.join(".");
464
- dset(doc, refPath, newRefValue);
465
- }
466
- });
467
- return doc;
468
- });
469
- const transaction = destinationClient.transaction();
470
- transactionDocsMapped.forEach(doc => {
471
- transaction.createOrReplace(doc);
472
- });
473
- await transaction.commit().then(res => {
474
- setMessage({
475
- tone: "positive",
476
- text: "Duplication complete!"
477
- });
478
- updatePayloadStatuses();
479
- }).catch(err => {
480
- setMessage({
481
- tone: "critical",
482
- text: err.details.description
483
- });
484
- });
485
- setIsDuplicating(false);
486
- setProgress([0, 0]);
487
- if (onDuplicated) {
488
- try {
489
- await onDuplicated();
490
- } catch (error) {
491
- setMessage({
492
- tone: "critical",
493
- text: "Error in onDuplicated hook: ".concat(error)
494
- });
495
- }
496
- }
497
- }
498
- function handleChange(e) {
499
- if (!workspacesOptions.length) {
500
- return;
501
- }
502
- const targeted = workspacesOptions.find(space => space.name === e.currentTarget.value);
503
- if (targeted) {
504
- setDestination(targeted);
505
- }
506
- }
507
- const payloadCount = payload.length;
508
- const firstSvgIndex = payload.findIndex(_ref4 => {
509
- let {
510
- doc
511
- } = _ref4;
512
- return doc.extension === "svg";
513
- });
514
- const selectedDocumentsCount = payload.filter(item => item.include && !isAssetId(item.doc._id)).length;
515
- const selectedAssetsCount = payload.filter(item => item.include && isAssetId(item.doc._id)).length;
516
- const selectedTotal = selectedDocumentsCount + selectedAssetsCount;
517
- const destinationTitle = (_b = destination == null ? void 0 : destination.title) != null ? _b : destination == null ? void 0 : destination.name;
518
- const hasMultipleProjectIds = new Set(workspacesOptions.map(space => space == null ? void 0 : space.projectId).filter(Boolean)).size > 1;
519
- const headingText = [selectedTotal, "/", payloadCount, "Documents and Assets selected"].join(" ");
520
- const buttonText = React.useMemo(() => {
521
- const text = ["Duplicate"];
522
- if (selectedDocumentsCount > 1) {
523
- text.push(String(selectedDocumentsCount), selectedDocumentsCount === 1 ? "Document" : "Documents");
524
- }
525
- if (selectedAssetsCount > 1) {
526
- text.push("and", String(selectedAssetsCount), selectedAssetsCount === 1 ? "Asset" : "Assets");
527
- }
528
- if (originClient.config().projectId !== (destination == null ? void 0 : destination.projectId)) {
529
- text.push("between Projects");
530
- }
531
- text.push("to", String(destinationTitle));
532
- return text.join(" ");
533
- }, [selectedDocumentsCount, selectedAssetsCount, originClient, destination == null ? void 0 : destination.projectId, destinationTitle]);
534
- if (workspacesOptions.length < 2) {
535
- return /* @__PURE__ */jsxs(Feedback, {
536
- tone: "critical",
537
- children: [/* @__PURE__ */jsx("code", {
538
- children: "sanity.config.ts"
539
- }), " must contain at least two Workspaces to use this plugin."]
540
- });
541
- }
542
- return /* @__PURE__ */jsx(Container, {
543
- width: 1,
544
- children: /* @__PURE__ */jsx(Card, {
545
- border: true,
546
- children: /* @__PURE__ */jsxs(Stack, {
547
- children: [/* @__PURE__ */jsx(Card, {
548
- padding: 4,
549
- style: stickyStyles(isDarkMode),
550
- children: /* @__PURE__ */jsxs(Stack, {
551
- space: 4,
552
- children: [/* @__PURE__ */jsxs(Flex, {
553
- gap: 3,
554
- children: [/* @__PURE__ */jsxs(Stack, {
555
- style: {
556
- flex: 1
557
- },
558
- space: 3,
559
- children: [/* @__PURE__ */jsx(Label, {
560
- children: "Duplicate from"
561
- }), /* @__PURE__ */jsx(Select, {
562
- readOnly: true,
563
- value: (_c = workspacesOptions.find(space => space.disabled)) == null ? void 0 : _c.name,
564
- children: workspacesOptions.filter(space => space.disabled).map(space => {
565
- var _a2;
566
- return /* @__PURE__ */jsxs("option", {
567
- value: space.name,
568
- disabled: space.disabled,
569
- children: [(_a2 = space.title) != null ? _a2 : space.name, hasMultipleProjectIds ? " (".concat(space.projectId, ")") : ""]
570
- }, space.name);
571
- })
572
- })]
573
- }), /* @__PURE__ */jsx(Box, {
574
- padding: 4,
575
- paddingTop: 5,
576
- paddingBottom: 0,
577
- children: /* @__PURE__ */jsx(Text, {
578
- size: 3,
579
- children: /* @__PURE__ */jsx(ArrowRightIcon, {})
580
- })
581
- }), /* @__PURE__ */jsxs(Stack, {
582
- style: {
583
- flex: 1
584
- },
585
- space: 3,
586
- children: [/* @__PURE__ */jsx(Label, {
587
- children: "To Destination"
588
- }), /* @__PURE__ */jsx(Select, {
589
- onChange: handleChange,
590
- children: workspacesOptions.map(space => {
591
- var _a2;
592
- return /* @__PURE__ */jsxs("option", {
593
- value: space.name,
594
- disabled: space.disabled,
595
- children: [(_a2 = space.title) != null ? _a2 : space.name, hasMultipleProjectIds ? " (".concat(space.projectId, ")") : "", space.disabled ? " (Current)" : ""]
596
- }, space.name);
597
- })
598
- })]
599
- })]
600
- }), isDuplicating && /* @__PURE__ */jsx(Card, {
601
- border: true,
602
- radius: 2,
603
- children: /* @__PURE__ */jsx(Card, {
604
- style: {
605
- width: "100%",
606
- transform: "scaleX(".concat(progress[0] / progress[1], ")"),
607
- transformOrigin: "left",
608
- transition: "transform .2s ease",
609
- boxSizing: "border-box"
610
- },
611
- padding: 1,
612
- tone: "positive"
613
- })
614
- }), payload.length > 0 && /* @__PURE__ */jsxs(Fragment, {
615
- children: [/* @__PURE__ */jsx(Label, {
616
- children: headingText
617
- }), /* @__PURE__ */jsx(SelectButtons, {
618
- payload,
619
- setPayload
620
- })]
621
- })]
622
- })
623
- }), /* @__PURE__ */jsx(Card, {
624
- borderTop: true,
625
- padding: 4,
626
- children: /* @__PURE__ */jsxs(Stack, {
627
- space: 3,
628
- children: [message && /* @__PURE__ */jsx(Card, {
629
- padding: 3,
630
- radius: 2,
631
- shadow: 1,
632
- tone: message.tone,
633
- children: /* @__PURE__ */jsx(Text, {
634
- size: 1,
635
- children: message.text
636
- })
637
- }), payload.length > 0 ? /* @__PURE__ */jsx(Stack, {
638
- children: payload.map((_ref5, index) => {
639
- let {
640
- doc,
641
- include,
642
- status,
643
- hasDraft
644
- } = _ref5;
645
- const schemaType = schema.get(doc._type);
646
- return /* @__PURE__ */jsxs(React.Fragment, {
647
- children: [/* @__PURE__ */jsxs(Flex, {
648
- align: "center",
649
- children: [/* @__PURE__ */jsx(Checkbox, {
650
- checked: include,
651
- onChange: () => handleCheckbox(doc._id)
652
- }), /* @__PURE__ */jsx(Box, {
653
- flex: 1,
654
- paddingX: 3,
655
- children: schemaType ? /* @__PURE__ */jsx(Preview, {
656
- value: doc,
657
- schemaType
658
- }) : /* @__PURE__ */jsx(Card, {
659
- tone: "caution",
660
- children: "Invalid schema type"
661
- })
662
- }), /* @__PURE__ */jsxs(Flex, {
663
- align: "center",
664
- gap: 2,
665
- children: [hasDraft ? /* @__PURE__ */jsx(StatusBadge, {
666
- status: "UNPUBLISHED",
667
- isAsset: false
668
- }) : null, /* @__PURE__ */jsx(StatusBadge, {
669
- status,
670
- isAsset: isAssetId(doc._id)
671
- })]
672
- })]
673
- }), (doc == null ? void 0 : doc.extension) === "svg" && index === firstSvgIndex && /* @__PURE__ */jsx(Card, {
674
- padding: 3,
675
- radius: 2,
676
- shadow: 1,
677
- tone: "caution",
678
- children: /* @__PURE__ */jsxs(Text, {
679
- size: 1,
680
- children: ["Due to how SVGs are sanitized after first uploaded, duplicated SVG assets may have new ", /* @__PURE__ */jsx("code", {
681
- children: "_id"
682
- }), "'s at the destination. The newly generated ", /* @__PURE__ */jsx("code", {
683
- children: "_id"
684
- }), " will be the same in each duplication, but it will never be the same ", /* @__PURE__ */jsx("code", {
685
- children: "_id"
686
- }), " as the first time this Asset was uploaded. References to the asset will be updated to use the new ", /* @__PURE__ */jsx("code", {
687
- children: "_id"
688
- }), "."]
689
- })
690
- })]
691
- }, doc._id);
692
- })
693
- }) : /* @__PURE__ */jsx(Flex, {
694
- padding: 4,
695
- align: "center",
696
- justify: "center",
697
- children: /* @__PURE__ */jsx(Spinner, {})
698
- }), /* @__PURE__ */jsxs(Stack, {
699
- space: 2,
700
- children: [hasReferences && /* @__PURE__ */jsx(Button, {
701
- fontSize: 2,
702
- padding: 4,
703
- tone: "positive",
704
- mode: "ghost",
705
- icon: SearchIcon,
706
- onClick: handleReferences,
707
- text: "Gather References",
708
- disabled: isDuplicating || !selectedTotal || isGathering
709
- }), /* @__PURE__ */jsx(Button, {
710
- fontSize: 2,
711
- padding: 4,
712
- tone: "positive",
713
- icon: LaunchIcon,
714
- onClick: handleDuplicate,
715
- text: buttonText,
716
- disabled: isDuplicating || !selectedTotal || isGathering
717
- })]
718
- })]
719
- })
720
- })]
721
- })
722
- })
723
- });
724
- }
725
- function DuplicatorQuery(props) {
726
- var _a;
727
- const {
728
- token,
729
- pluginConfig
730
- } = props;
731
- const {
732
- queries: preDefinedQueries
733
- } = pluginConfig;
734
- const originClient = useClient(clientConfig);
735
- const schema = useSchema();
736
- const schemaTypes = schema.getTypeNames();
737
- const [value, setValue] = useState("");
738
- const [fetched, setFetched] = useState(false);
739
- const [initialData, setInitialData] = useState({
740
- docs: []
741
- // draftIds: []
742
- });
743
-
744
- function handleSubmit(e) {
745
- if (e) e.preventDefault();
746
- originClient.fetch(value).then(res => {
747
- const registeredAndPublishedDocs = res.length ? res.filter(doc => schemaTypes.includes(doc._type)).filter(doc => !doc._id.startsWith("drafts.")) : [];
748
- setInitialData({
749
- docs: registeredAndPublishedDocs
750
- // draftIds: initialDraftIds
751
- });
752
-
753
- setFetched(true);
754
- }).catch(err => console.error(err));
755
- }
756
- useEffect(() => {
757
- var _a2;
758
- if (!((_a2 = initialData.docs) == null ? void 0 : _a2.length) && value) {
759
- handleSubmit();
760
- }
761
- }, []);
762
- return /* @__PURE__ */jsx(Card, {
763
- padding: [0, 0, 0, 5],
764
- children: /* @__PURE__ */jsx(Container, {
765
- children: /* @__PURE__ */jsxs(Grid, {
766
- columns: [1, 1, 1, 2],
767
- gap: [1, 1, 1, 4],
768
- children: [/* @__PURE__ */jsxs(Box, {
769
- padding: [2, 2, 2, 0],
770
- children: [/* @__PURE__ */jsx(Card, {
771
- padding: 4,
772
- radius: 3,
773
- border: true,
774
- children: /* @__PURE__ */jsxs(Stack, {
775
- space: 4,
776
- children: [/* @__PURE__ */jsx(Box, {
777
- children: /* @__PURE__ */jsx(Label, {
778
- children: "Initial Documents Query"
779
- })
780
- }), /* @__PURE__ */jsx(Box, {
781
- children: /* @__PURE__ */jsx(Text, {
782
- children: "Start with a valid GROQ query to load initial documents. The query will need to return an Array of Objects. Drafts will be removed from the results."
783
- })
784
- }), /* @__PURE__ */jsx("form", {
785
- onSubmit: handleSubmit,
786
- children: /* @__PURE__ */jsxs(Flex, {
787
- children: [/* @__PURE__ */jsx(Box, {
788
- flex: 1,
789
- paddingRight: 2,
790
- children: /* @__PURE__ */jsx(TextInput, {
791
- style: {
792
- fontFamily: "monospace"
793
- },
794
- fontSize: 2,
795
- onChange: event => setValue(event.currentTarget.value),
796
- padding: 4,
797
- placeholder: "*[_type == \"article\"]",
798
- value: value != null ? value : ""
799
- })
800
- }), /* @__PURE__ */jsx(Button, {
801
- padding: 2,
802
- paddingX: 4,
803
- tone: "primary",
804
- onClick: handleSubmit,
805
- text: "Query",
806
- disabled: !value
807
- })]
808
- })
809
- })]
810
- })
811
- }), preDefinedQueries && (preDefinedQueries == null ? void 0 : preDefinedQueries.length) > 0 && /* @__PURE__ */jsx(Card, {
812
- marginTop: 2,
813
- padding: 4,
814
- radius: 3,
815
- border: true,
816
- children: /* @__PURE__ */jsx(Box, {
817
- children: /* @__PURE__ */jsxs(Stack, {
818
- space: 4,
819
- children: [/* @__PURE__ */jsx(Box, {
820
- children: /* @__PURE__ */jsx(Label, {
821
- children: "Predefined Queries"
822
- })
823
- }), /* @__PURE__ */jsx(Stack, {
824
- space: 2,
825
- children: preDefinedQueries.map(query => /* @__PURE__ */jsx(Button, {
826
- padding: 2,
827
- paddingX: 4,
828
- tone: "primary",
829
- onClick: () => setValue("*[".concat(query.query, "]")),
830
- text: query.label
831
- }, query.label.replace(/\s+/g, "-")))
832
- })]
833
- })
834
- })
835
- })]
836
- }), fetched && initialData.docs.length < 1 && /* @__PURE__ */jsx(Container, {
837
- width: 1,
838
- children: /* @__PURE__ */jsx(Card, {
839
- padding: 5,
840
- children: value ? "No documents match this query" : "Start with a valid GROQ query"
841
- })
842
- }), ((_a = initialData.docs) == null ? void 0 : _a.length) > 0 && /* @__PURE__ */jsx(Duplicator, {
843
- docs: initialData.docs,
844
- token,
845
- pluginConfig
846
- })]
847
- })
848
- })
849
- });
850
- }
851
- function DuplicatorWrapper(props) {
852
- const {
853
- docs,
854
- token,
855
- pluginConfig,
856
- onDuplicated
857
- } = props;
858
- const [inbound, setInbound] = useState([]);
859
- const {
860
- follow = []
861
- } = pluginConfig;
862
- const [mode, setMode] = useState(follow.length === 1 ? follow[0] : "outbound");
863
- const client = useClient(clientConfig);
864
- useEffect(() => {
865
- (async () => {
866
- if (follow.includes("inbound")) {
867
- const inboundReferences = await client.fetch("*[references($id)]", {
868
- id: docs[0]._id
869
- });
870
- setInbound([...props.docs, ...inboundReferences]);
871
- }
872
- })();
873
- }, []);
874
- return /* @__PURE__ */jsxs(Container, {
875
- children: [follow.length > 1 && (follow.includes("inbound") || follow.includes("outbound")) ? /* @__PURE__ */jsx(Card, {
876
- paddingX: 4,
877
- paddingBottom: 4,
878
- marginBottom: 4,
879
- borderBottom: true,
880
- children: /* @__PURE__ */jsxs(Grid, {
881
- columns: 2,
882
- gap: 4,
883
- children: [follow.includes("outbound") ? /* @__PURE__ */jsx(Button, {
884
- mode: "ghost",
885
- tone: "primary",
886
- selected: mode === "outbound",
887
- onClick: () => setMode("outbound"),
888
- text: "Outbound"
889
- }) : null, follow.includes("inbound") ? /* @__PURE__ */jsx(Button, {
890
- mode: "ghost",
891
- tone: "primary",
892
- selected: mode === "inbound",
893
- onClick: () => setMode("inbound"),
894
- disabled: inbound.length === 0,
895
- text: inbound.length > 0 ? "Inbound (".concat(inbound.length, ")") : "No inbound references"
896
- }) : null]
897
- })
898
- }) : null, /* @__PURE__ */jsx(Duplicator, {
899
- docs: mode === "outbound" ? docs : inbound,
900
- token,
901
- pluginConfig,
902
- onDuplicated
903
- })]
904
- });
905
- }
906
- const SECRET_NAMESPACE = "CrossDatasetDuplicator";
907
- const DEFAULT_CONFIG = {
908
- tool: true,
909
- types: [],
910
- filter: "",
911
- follow: ["outbound"],
912
- queries: []
913
- };
914
- function ResetSecret() {
915
- const client = useClient(clientConfig);
916
- const handleClick = useCallback(() => {
917
- client.delete({
918
- query: "*[_id == \"secrets.".concat(SECRET_NAMESPACE, "\"]")
919
- });
920
- }, [client]);
921
- return /* @__PURE__ */jsx(Flex, {
922
- align: "center",
923
- justify: "flex-end",
924
- paddingX: [2, 2, 2, 5],
925
- paddingY: 5,
926
- children: /* @__PURE__ */jsx(Button, {
927
- text: "Reset Secret",
928
- onClick: handleClick,
929
- mode: "ghost",
930
- tone: "critical",
931
- fontSize: 1,
932
- padding: 2
933
- })
934
- });
935
- }
936
- const CrossDatasetDuplicatorContext = createContext(DEFAULT_CONFIG);
937
- function useCrossDatasetDuplicatorConfig() {
938
- const pluginConfig = useContext(CrossDatasetDuplicatorContext);
939
- return pluginConfig;
940
- }
941
- function ConfigProvider(props) {
942
- const {
943
- pluginConfig,
944
- ...rest
945
- } = props;
946
- return /* @__PURE__ */jsx(CrossDatasetDuplicatorContext.Provider, {
947
- value: pluginConfig,
948
- children: props.renderDefault(rest)
949
- });
950
- }
951
- const secretConfigKeys = [{
952
- key: "bearerToken",
953
- title: "An API token with Viewer permissions is required to duplicate the original files of assets, and will be used for all Duplications. Create one at sanity.io/manage",
954
- description: ""
955
- }];
956
- function CrossDatasetDuplicator(props) {
957
- const {
958
- mode = "tool",
959
- docs = [],
960
- onDuplicated
961
- } = props != null ? props : {};
962
- const pluginConfig = useCrossDatasetDuplicatorConfig();
963
- const {
964
- loading,
965
- secrets
966
- } = useSecrets(SECRET_NAMESPACE);
967
- const [showSecretsPrompt, setShowSecretsPrompt] = useState(false);
968
- useEffect(() => {
969
- if (secrets) {
970
- setShowSecretsPrompt(!(secrets == null ? void 0 : secrets.bearerToken));
971
- }
972
- }, [secrets]);
973
- if (loading) {
974
- return /* @__PURE__ */jsx(Flex, {
975
- justify: "center",
976
- align: "center",
977
- children: /* @__PURE__ */jsx(Box, {
978
- padding: 5,
979
- children: /* @__PURE__ */jsx(Spinner, {})
980
- })
981
- });
982
- }
983
- if (!loading && showSecretsPrompt || !(secrets == null ? void 0 : secrets.bearerToken)) {
984
- return /* @__PURE__ */jsx(SettingsView, {
985
- title: "Token Required",
986
- namespace: SECRET_NAMESPACE,
987
- keys: secretConfigKeys,
988
- onClose: () => setShowSecretsPrompt(false)
989
- });
990
- }
991
- if (mode === "tool" && pluginConfig) {
992
- return /* @__PURE__ */jsxs(Fragment, {
993
- children: [/* @__PURE__ */jsx(DuplicatorQuery, {
994
- token: secrets == null ? void 0 : secrets.bearerToken,
995
- pluginConfig
996
- }), /* @__PURE__ */jsx(ResetSecret, {})]
997
- });
998
- }
999
- if (!(docs == null ? void 0 : docs.length)) {
1000
- return /* @__PURE__ */jsx(Feedback, {
1001
- children: "No docs passed into Duplicator Tool"
1002
- });
1003
- }
1004
- if (!pluginConfig) {
1005
- return /* @__PURE__ */jsx(Feedback, {
1006
- children: "No plugin config"
1007
- });
1008
- }
1009
- return /* @__PURE__ */jsx(DuplicatorWrapper, {
1010
- docs,
1011
- token: secrets == null ? void 0 : secrets.bearerToken,
1012
- pluginConfig,
1013
- onDuplicated
1014
- });
1015
- }
1016
- function CrossDatasetDuplicatorAction(props) {
1017
- const {
1018
- docs = [],
1019
- onDuplicated
1020
- } = props;
1021
- return /* @__PURE__ */jsx(CrossDatasetDuplicator, {
1022
- mode: "action",
1023
- docs,
1024
- onDuplicated
1025
- });
1026
- }
1027
- const DuplicateToAction = props => {
1028
- const {
1029
- draft,
1030
- published,
1031
- onComplete
1032
- } = props;
1033
- const [dialogOpen, setDialogOpen] = useState(false);
1034
- return {
1035
- disabled: draft,
1036
- title: draft ? "Document must be Published to begin" : null,
1037
- label: "Duplicate to...",
1038
- dialog: dialogOpen && published && {
1039
- type: "modal",
1040
- title: "Cross Dataset Duplicator",
1041
- content: /* @__PURE__ */jsx(CrossDatasetDuplicatorAction, {
1042
- docs: [published]
1043
- }),
1044
- onClose: () => {
1045
- onComplete();
1046
- setDialogOpen(false);
1047
- }
1048
- },
1049
- onHandle: () => setDialogOpen(true),
1050
- icon: LaunchIcon
1051
- };
1052
- };
1053
- DuplicateToAction.action = "duplicateTo";
1054
- function CrossDatasetDuplicatorTool(props) {
1055
- var _a;
1056
- const {
1057
- docs = []
1058
- } = (_a = props.tool.options) != null ? _a : {};
1059
- return /* @__PURE__ */jsx(CrossDatasetDuplicator, {
1060
- mode: "tool",
1061
- docs
1062
- });
1063
- }
1064
- const crossDatasetDuplicatorTool = () => ({
1065
- title: "Duplicator",
1066
- name: "duplicator",
1067
- icon: LaunchIcon,
1068
- component: CrossDatasetDuplicatorTool,
1069
- options: {
1070
- docs: []
1071
- }
1072
- });
1073
- const crossDatasetDuplicator = definePlugin(function () {
1074
- let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1075
- const pluginConfig = {
1076
- ...DEFAULT_CONFIG,
1077
- ...config
1078
- };
1079
- const {
1080
- types
1081
- } = pluginConfig;
1082
- return {
1083
- name: "@sanity/cross-dataset-duplicator",
1084
- tools: prev => pluginConfig.tool ? [...prev, crossDatasetDuplicatorTool()] : prev,
1085
- studio: {
1086
- components: {
1087
- layout: props => ConfigProvider({
1088
- ...props,
1089
- pluginConfig
1090
- })
1091
- }
1092
- },
1093
- document: {
1094
- actions: (prev, _ref6) => {
1095
- let {
1096
- schemaType
1097
- } = _ref6;
1098
- return types && types.includes(schemaType) ? [...prev, DuplicateToAction] : prev;
1099
- }
1100
- }
1101
- };
1102
- });
1103
- export { CrossDatasetDuplicatorAction, DuplicateToAction, crossDatasetDuplicator, useCrossDatasetDuplicatorConfig };
1104
- //# sourceMappingURL=index.esm.js.map