codepen-commander 1.1.0 → 1.3.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/sync/info.js ADDED
@@ -0,0 +1,339 @@
1
+ import crypto from 'node:crypto';
2
+ import { CliError } from '../utils/json.js';
3
+ export const PEN_INFO_FIELDS = ['title', 'description', 'tags', 'access', 'template'];
4
+ const VALID_ACCESS = new Set(['public', 'private', 'protected', 'collaborators']);
5
+ function parseAccessValue(raw) {
6
+ const lower = raw.trim().toLowerCase();
7
+ if (!VALID_ACCESS.has(lower)) {
8
+ return null;
9
+ }
10
+ return (lower[0].toUpperCase() + lower.slice(1));
11
+ }
12
+ /**
13
+ * Extracts editable Pen metadata from a CodePen API v2 `Pen` payload.
14
+ * Intentionally excludes `password` (never stored in `.cdpn.json`) and volatile read-only stats.
15
+ */
16
+ export function extractPenInfo(pen) {
17
+ return {
18
+ title: typeof pen.title === 'string' ? pen.title : '',
19
+ description: typeof pen.description === 'string' ? pen.description : '',
20
+ tags: Array.isArray(pen.tags)
21
+ ? pen.tags
22
+ .filter((t) => typeof t === 'string')
23
+ .map((t) => t.trim())
24
+ .filter(Boolean)
25
+ : [],
26
+ access: pen.access,
27
+ template: Boolean(pen.template),
28
+ };
29
+ }
30
+ /**
31
+ * Returns a copy of complete Pen info with deterministic key ordering for hashing & serialization.
32
+ */
33
+ export function canonicalizePenInfo(info) {
34
+ return {
35
+ title: info.title,
36
+ description: info.description,
37
+ tags: [...info.tags],
38
+ access: info.access,
39
+ template: info.template,
40
+ };
41
+ }
42
+ /**
43
+ * Orders defined keys of a (potentially partial) `PenInfo` object consistently for writing `.cdpn.json`.
44
+ */
45
+ export function normalizePartialPenInfo(info) {
46
+ const ordered = {};
47
+ if (info.title !== undefined)
48
+ ordered.title = info.title;
49
+ if (info.description !== undefined)
50
+ ordered.description = info.description;
51
+ if (info.tags !== undefined)
52
+ ordered.tags = [...info.tags];
53
+ if (info.access !== undefined)
54
+ ordered.access = info.access;
55
+ if (info.template !== undefined)
56
+ ordered.template = info.template;
57
+ return ordered;
58
+ }
59
+ export function hasAnyPenInfoFields(info) {
60
+ if (!info)
61
+ return false;
62
+ return PEN_INFO_FIELDS.some((field) => info[field] !== undefined);
63
+ }
64
+ export function isCompletePenInfo(info) {
65
+ if (!info)
66
+ return false;
67
+ return (typeof info.title === 'string' &&
68
+ typeof info.description === 'string' &&
69
+ Array.isArray(info.tags) &&
70
+ typeof info.access === 'string' &&
71
+ typeof info.template === 'boolean');
72
+ }
73
+ /**
74
+ * Computes a deterministic SHA-256 digest of complete Pen metadata.
75
+ */
76
+ export function hashPenInfo(info) {
77
+ return crypto
78
+ .createHash('sha256')
79
+ .update(JSON.stringify(canonicalizePenInfo(info)))
80
+ .digest('hex');
81
+ }
82
+ /**
83
+ * Builds the `info` and `last_synced_info_hash` fields to persist in `.cdpn.json` from a synced `Pen`.
84
+ */
85
+ export function buildPenInfoConfigFields(pen) {
86
+ const info = extractPenInfo(pen);
87
+ return {
88
+ info,
89
+ last_synced_info_hash: hashPenInfo(info),
90
+ };
91
+ }
92
+ /**
93
+ * Validates and normalizes the optional `info` object parsed from `.cdpn.json`.
94
+ * Returns `undefined` when absent (backwards-compatible with older `.cdpn.json` files).
95
+ */
96
+ export function parsePenInfoInput(raw, configLabel = '.cdpn.json') {
97
+ if (raw === undefined || raw === null) {
98
+ return undefined;
99
+ }
100
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
101
+ throw new CliError(400, `Invalid ${configLabel}: "info" must be a JSON object.`);
102
+ }
103
+ const record = raw;
104
+ if (Object.hasOwn(record, 'password') && record.password !== undefined) {
105
+ throw new CliError(400, `Invalid ${configLabel}: "info.password" is not supported (passwords must not be stored in ${configLabel}).\n` +
106
+ 'Use `cdpn privacy protected` or `cdpn info --access Protected --password <password>` instead.');
107
+ }
108
+ const parsed = {};
109
+ if (record.title !== undefined) {
110
+ if (typeof record.title !== 'string') {
111
+ throw new CliError(400, `Invalid ${configLabel}: "info.title" must be a string.`);
112
+ }
113
+ parsed.title = record.title;
114
+ }
115
+ if (record.description !== undefined) {
116
+ if (typeof record.description !== 'string') {
117
+ throw new CliError(400, `Invalid ${configLabel}: "info.description" must be a string.`);
118
+ }
119
+ parsed.description = record.description;
120
+ }
121
+ if (record.tags !== undefined) {
122
+ if (!Array.isArray(record.tags) || !record.tags.every((t) => typeof t === 'string')) {
123
+ throw new CliError(400, `Invalid ${configLabel}: "info.tags" must be an array of strings.`);
124
+ }
125
+ parsed.tags = record.tags.map((t) => t.trim()).filter(Boolean);
126
+ }
127
+ if (record.access !== undefined) {
128
+ if (typeof record.access !== 'string') {
129
+ throw new CliError(400, `Invalid ${configLabel}: "info.access" must be one of Public, Private, Protected, or Collaborators.`);
130
+ }
131
+ const normalizedAccess = parseAccessValue(record.access);
132
+ if (!normalizedAccess) {
133
+ throw new CliError(400, `Invalid ${configLabel}: "info.access" value "${record.access}" is invalid. Use: Public, Private, Protected, or Collaborators.`);
134
+ }
135
+ parsed.access = normalizedAccess;
136
+ }
137
+ if (record.template !== undefined) {
138
+ if (typeof record.template !== 'boolean') {
139
+ throw new CliError(400, `Invalid ${configLabel}: "info.template" must be a boolean.`);
140
+ }
141
+ parsed.template = record.template;
142
+ }
143
+ return parsed;
144
+ }
145
+ function areTagArraysEqual(a, b) {
146
+ if (a.length !== b.length)
147
+ return false;
148
+ for (let i = 0; i < a.length; i++) {
149
+ if (a[i] !== b[i])
150
+ return false;
151
+ }
152
+ return true;
153
+ }
154
+ /**
155
+ * Offline baseline check used by `cdpn pull` to detect whether the user has uncommitted local
156
+ * edits to `info` inside `.cdpn.json`.
157
+ *
158
+ * Returns `false` for legacy `.cdpn.json` files without `info` so pulling seamlessly upgrades them.
159
+ */
160
+ export function isLocalInfoDirty(localInfo, lastSyncedInfoHash) {
161
+ if (!hasAnyPenInfoFields(localInfo)) {
162
+ return false;
163
+ }
164
+ if (lastSyncedInfoHash) {
165
+ if (isCompletePenInfo(localInfo) && hashPenInfo(localInfo) === lastSyncedInfoHash) {
166
+ return false;
167
+ }
168
+ return true;
169
+ }
170
+ // User explicitly provided `info` fields without a baseline hash -> protect local values on pull
171
+ return true;
172
+ }
173
+ /**
174
+ * Compares local `.cdpn.json` `info` (and optional `last_synced_info_hash` baseline) against
175
+ * the remote Pen's metadata from CodePen.
176
+ */
177
+ export function analyzeInfoSync(localInfo, lastSyncedInfoHash, remotePen) {
178
+ const remoteInfo = extractPenInfo(remotePen);
179
+ if (!hasAnyPenInfoFields(localInfo) || !localInfo) {
180
+ return {
181
+ tracked: false,
182
+ localChanged: false,
183
+ remoteChanged: false,
184
+ changes: [],
185
+ remoteInfo,
186
+ };
187
+ }
188
+ const changes = [];
189
+ if (localInfo.title !== undefined && localInfo.title !== remoteInfo.title) {
190
+ changes.push({ field: 'title', local: localInfo.title, remote: remoteInfo.title });
191
+ }
192
+ if (localInfo.description !== undefined && localInfo.description !== remoteInfo.description) {
193
+ changes.push({
194
+ field: 'description',
195
+ local: localInfo.description,
196
+ remote: remoteInfo.description,
197
+ });
198
+ }
199
+ if (localInfo.tags !== undefined && !areTagArraysEqual(localInfo.tags, remoteInfo.tags)) {
200
+ changes.push({
201
+ field: 'tags',
202
+ local: [...localInfo.tags],
203
+ remote: [...remoteInfo.tags],
204
+ });
205
+ }
206
+ if (localInfo.access !== undefined && localInfo.access !== remoteInfo.access) {
207
+ changes.push({ field: 'access', local: localInfo.access, remote: remoteInfo.access });
208
+ }
209
+ if (localInfo.template !== undefined && localInfo.template !== remoteInfo.template) {
210
+ changes.push({ field: 'template', local: localInfo.template, remote: remoteInfo.template });
211
+ }
212
+ if (changes.length === 0) {
213
+ return {
214
+ tracked: true,
215
+ localChanged: false,
216
+ remoteChanged: false,
217
+ changes: [],
218
+ remoteInfo,
219
+ };
220
+ }
221
+ if (lastSyncedInfoHash) {
222
+ const remoteChanged = hashPenInfo(remoteInfo) !== lastSyncedInfoHash;
223
+ const localChanged = isCompletePenInfo(localInfo)
224
+ ? hashPenInfo(localInfo) !== lastSyncedInfoHash
225
+ : true;
226
+ return {
227
+ tracked: true,
228
+ localChanged,
229
+ remoteChanged,
230
+ changes,
231
+ remoteInfo,
232
+ };
233
+ }
234
+ // No baseline hash (e.g. user manually added `info` to an older `.cdpn.json`): treat diffs as local edits
235
+ return {
236
+ tracked: true,
237
+ localChanged: true,
238
+ remoteChanged: false,
239
+ changes,
240
+ remoteInfo,
241
+ };
242
+ }
243
+ /**
244
+ * Validates and converts `InfoDiffItem[]` into a `PenUpdateRequest` payload for `PATCH /v2/pens/{id}`.
245
+ */
246
+ export function buildInfoUpdatePatch(changes) {
247
+ const patch = {};
248
+ for (const item of changes) {
249
+ switch (item.field) {
250
+ case 'title':
251
+ patch.title = item.local;
252
+ break;
253
+ case 'description':
254
+ patch.description = item.local;
255
+ break;
256
+ case 'tags': {
257
+ const tags = item.local;
258
+ if (tags.length > 5) {
259
+ throw new CliError(400, `CodePen allows at most 5 tags per Pen (found ${tags.length} in .cdpn.json).`);
260
+ }
261
+ patch.tags = [...tags];
262
+ break;
263
+ }
264
+ case 'access': {
265
+ const access = item.local;
266
+ if (access === 'Protected' && item.remote !== 'Protected') {
267
+ throw new CliError(400, 'Cannot change Pen access to "Protected" via .cdpn.json because Protected Pens require a password (which is not stored in .cdpn.json).\n' +
268
+ 'Run `cdpn privacy protected` or `cdpn info --access Protected --password <password>` instead.');
269
+ }
270
+ patch.access = access;
271
+ break;
272
+ }
273
+ case 'template':
274
+ patch.template = item.local;
275
+ break;
276
+ }
277
+ }
278
+ return patch;
279
+ }
280
+ /**
281
+ * Updates a local `CdpnConfig` after an explicit metadata command (`cdpn info` or `cdpn privacy`)
282
+ * patches CodePen, preserving any unpushed local edits to *other* `info` fields in `.cdpn.json`.
283
+ */
284
+ export function mergeUpdatedPenInfoIntoConfig(config, updatedPen, appliedPatch) {
285
+ const remoteInfo = extractPenInfo(updatedPen);
286
+ const remoteHash = hashPenInfo(remoteInfo);
287
+ if (!hasAnyPenInfoFields(config.info) || !isLocalInfoDirty(config.info, config.last_synced_info_hash)) {
288
+ return {
289
+ ...config,
290
+ info: remoteInfo,
291
+ last_synced_info_hash: remoteHash,
292
+ };
293
+ }
294
+ // Local `info` has unpushed edits: apply only the patched fields from remote and backfill missing fields
295
+ const merged = {
296
+ title: appliedPatch.title !== undefined
297
+ ? remoteInfo.title
298
+ : (config.info?.title ?? remoteInfo.title),
299
+ description: appliedPatch.description !== undefined
300
+ ? remoteInfo.description
301
+ : (config.info?.description ?? remoteInfo.description),
302
+ tags: appliedPatch.tags !== undefined
303
+ ? [...remoteInfo.tags]
304
+ : config.info?.tags !== undefined
305
+ ? [...config.info.tags]
306
+ : [...remoteInfo.tags],
307
+ access: appliedPatch.access !== undefined
308
+ ? remoteInfo.access
309
+ : (config.info?.access ?? remoteInfo.access),
310
+ template: appliedPatch.template !== undefined
311
+ ? remoteInfo.template
312
+ : (config.info?.template ?? remoteInfo.template),
313
+ };
314
+ return {
315
+ ...config,
316
+ info: merged,
317
+ last_synced_info_hash: remoteHash,
318
+ };
319
+ }
320
+ /**
321
+ * Formats an `info` field value cleanly for single-line terminal diff output.
322
+ */
323
+ export function formatInfoValue(field, value) {
324
+ if (field === 'tags') {
325
+ const arr = Array.isArray(value) ? value : [];
326
+ return `[${arr.join(', ')}]`;
327
+ }
328
+ if (field === 'template') {
329
+ return String(Boolean(value));
330
+ }
331
+ if (field === 'access') {
332
+ return String(value ?? '');
333
+ }
334
+ const str = String(value ?? '');
335
+ if (str.length > 60) {
336
+ return JSON.stringify(`${str.slice(0, 57)}…`);
337
+ }
338
+ return JSON.stringify(str);
339
+ }