-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathutils.js
More file actions
208 lines (176 loc) · 6.49 KB
/
utils.js
File metadata and controls
208 lines (176 loc) · 6.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { AEM_ORIGIN } from '../../../public/utils/constants.js';
import { daFetch } from '../../../utils/daFetch.js';
import { mergeCopy, overwriteCopy } from '../../loc/project/index.js';
import { Queue } from '../../../public/utils/tree.js';
const SNAPSHOT_SCHEDULER_URL = 'https://helix-snapshot-scheduler-prod.adobeaem.workers.dev';
let org;
let site;
function formatError(resp) {
if (resp.status === 401 || resp.status === 403) {
return { error: 'You do not have privledges to take this snapshot action.' };
}
return { error: 'Not a valid project.' };
}
function formatResources(name, resources) {
return resources.map((res) => ({
path: res.path,
aemPreview: `https://main--${site}--${org}.aem.page${res.path}`,
url: `https://${name}--main--${site}--${org}.aem.reviews${res.path}`,
}));
}
function filterPaths(hrefs) {
return hrefs.reduce((acc, href) => {
try {
const { pathname } = new URL(href);
acc.push(pathname.endsWith('.html') ? pathname.replace('.html', '') : pathname);
} catch {
// do nothing
}
return acc;
}, []);
}
function comparePaths(first, second) {
return {
added: second.filter((item) => !first.includes(item)),
removed: first.filter((item) => !second.includes(item)),
};
}
export async function saveManifest(name, manifestToSave) {
const opts = { method: 'POST' };
if (manifestToSave) {
opts.body = JSON.stringify(manifestToSave);
opts.headers = { 'Content-Type': 'application/json' };
}
const resp = await daFetch(`${AEM_ORIGIN}/snapshot/${org}/${site}/main/${name}`, opts);
if (!resp.ok) return formatError(resp);
const { manifest } = await resp.json();
manifest.resources = formatResources(name, manifest.resources);
return manifest;
}
export async function reviewSnapshot(name, state) {
const opts = { method: 'POST' };
// Review status
const review = `?review=${state}&keepResources=true`;
const resp = await daFetch(`${AEM_ORIGIN}/snapshot/${org}/${site}/main/${name}${review}`, opts);
if (!resp.ok) return formatError(resp);
return { success: true };
}
export async function fetchManifest(name) {
const resp = await daFetch(`${AEM_ORIGIN}/snapshot/${org}/${site}/main/${name}`);
if (!resp.ok) return formatError(resp);
const { manifest } = await resp.json();
manifest.resources = formatResources(name, manifest.resources);
return manifest;
}
export async function fetchSnapshots() {
const resp = await daFetch(`${AEM_ORIGIN}/snapshot/${org}/${site}/main`);
if (!resp.ok) return formatError(resp);
const json = await resp.json();
const snapshots = json.snapshots.map((snapshot) => (
{ org, site, name: snapshot }
));
return { snapshots };
}
export async function deleteSnapshot(name, paths = ['/*']) {
const results = await Promise.all(paths.map(async (path) => {
const opts = { method: 'DELETE' };
const resp = await daFetch(`${AEM_ORIGIN}/snapshot/${org}/${site}/main/${name}${path}`, opts);
if (!resp.ok) return formatError(resp);
return { success: resp.status };
}));
const firstError = results.find((result) => result.error);
if (firstError) return firstError;
// once all resources are deleted, delete the snapshot as well
const opts = { method: 'DELETE' };
const resp = await daFetch(`${AEM_ORIGIN}/snapshot/${org}/${site}/main/${name}`, opts);
if (!resp.ok) return formatError(resp);
return { success: true };
}
export function setOrgSite(suppliedOrg, suppliedSite) {
org = suppliedOrg;
site = suppliedSite;
}
export async function updatePaths(name, currPaths, editedHrefs) {
const paths = filterPaths(editedHrefs);
const { removed, added } = comparePaths(currPaths, paths);
// Handle deletes
if (removed.length > 0) {
const deleteResult = await deleteSnapshot(name, removed);
if (deleteResult.error) return deleteResult;
}
// Handle adds
if (added.length > 0) {
const opts = {
method: 'POST',
body: JSON.stringify({ paths: added }),
headers: { 'Content-Type': 'application/json' },
};
// This is technically a bulk ops request
const resp = await daFetch(`${AEM_ORIGIN}/snapshot/${org}/${site}/main/${name}/*`, opts);
if (!resp.ok) return formatError(resp);
}
// The formatting of the response will be bulk job-like,
// so shamelessly use the supplied paths as our turth.
const toFormat = paths.map((path) => ({ path }));
return formatResources(name, toFormat);
}
export async function copyManifest(name, resources, direction) {
// The action to take
const copyUrl = async (url) => {
if (url.source.endsWith('.html')) {
await mergeCopy(url, `Snapshot ${direction}`);
} else {
await overwriteCopy(url, `Snapshot ${direction}`);
}
};
const urls = resources.reduce((acc, res) => {
try {
const url = new URL(res.aemPreview);
const path = url.pathname.endsWith('/') ? `${url.pathname}index` : url.pathname;
const extPath = path.endsWith('.json') ? path : `${path}.html`;
const main = `/${org}/${site}${extPath}`;
const fork = `/${org}/${site}/.snapshots/${name}${extPath}`;
url.source = direction === 'fork' ? main : fork;
url.destination = direction === 'fork' ? fork : main;
acc.push(url);
} catch {
console.log('error making url from manifest path');
}
return acc;
}, []);
// Setup a new Queue with the copy function
const queue = new Queue(copyUrl, 50);
await Promise.all(urls.map((url) => queue.push(url)));
}
export async function updateSchedule(snapshotId) {
const adminURL = `${SNAPSHOT_SCHEDULER_URL}/schedule`;
const body = {
org,
site,
snapshotId,
};
const headers = { 'content-type': 'application/json' };
const resp = await daFetch(`${adminURL}`, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
const result = resp.headers.get('X-Error');
return { status: resp.status, text: result };
}
export async function isRegistered() {
try {
const adminURL = `${SNAPSHOT_SCHEDULER_URL}/register/${org}/${site}`;
const resp = await daFetch(adminURL);
return resp.status === 200;
} catch (error) {
console.error('Error checking if registered for snapshot scheduler', error);
return false;
}
}
// Convert UTC date to local datetime-local format
export function formatLocalDate(utcDate) {
if (!utcDate) return '';
const d = new Date(utcDate);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}