-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathapi.ts
More file actions
606 lines (528 loc) · 18 KB
/
api.ts
File metadata and controls
606 lines (528 loc) · 18 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import {composeThemeGid, parseGid, DEVELOPMENT_THEME_ROLE} from './utils.js'
import {buildTheme} from './factories.js'
import {Result, Checksum, Key, Theme, ThemeAsset, Operation} from './types.js'
import {ThemeUpdate} from '../../../cli/api/graphql/admin/generated/theme_update.js'
import {ThemeDelete} from '../../../cli/api/graphql/admin/generated/theme_delete.js'
import {ThemeDuplicate} from '../../../cli/api/graphql/admin/generated/theme_duplicate.js'
import {ThemePublish} from '../../../cli/api/graphql/admin/generated/theme_publish.js'
import {ThemeCreate} from '../../../cli/api/graphql/admin/generated/theme_create.js'
import {GetThemeFileBodies} from '../../../cli/api/graphql/admin/generated/get_theme_file_bodies.js'
import {GetThemeFileChecksums} from '../../../cli/api/graphql/admin/generated/get_theme_file_checksums.js'
import {
ThemeFilesUpsert,
ThemeFilesUpsertMutation,
} from '../../../cli/api/graphql/admin/generated/theme_files_upsert.js'
import {ThemeFilesDelete} from '../../../cli/api/graphql/admin/generated/theme_files_delete.js'
import {
OnlineStoreThemeFileBodyInputType,
OnlineStoreThemeFilesUpsertFileInput,
MetafieldOwnerType,
ThemeRole,
} from '../../../cli/api/graphql/admin/generated/types.js'
import {MetafieldDefinitionsByOwnerType} from '../../../cli/api/graphql/admin/generated/metafield_definitions_by_owner_type.js'
import {GetThemes} from '../../../cli/api/graphql/admin/generated/get_themes.js'
import {GetTheme} from '../../../cli/api/graphql/admin/generated/get_theme.js'
import {OnlineStorePasswordProtection} from '../../../cli/api/graphql/admin/generated/online_store_password_protection.js'
import {RequestModeInput} from '../http.js'
import {adminRequestDoc} from '../api/admin.js'
import {AdminSession} from '../session.js'
import {AbortError} from '../error.js'
import {outputDebug} from '../output.js'
import {recordTiming, recordEvent, recordError} from '../analytics.js'
export type ThemeParams = Partial<Pick<Theme, 'name' | 'role' | 'processing' | 'src'>>
export type AssetParams = Pick<ThemeAsset, 'key'> & Partial<Pick<ThemeAsset, 'value' | 'attachment'>>
const SkeletonThemeCdn = 'https://cdn.shopify.com/static/online-store/theme-skeleton.zip'
const THEME_API_NETWORK_BEHAVIOUR: RequestModeInput = {
useNetworkLevelRetry: true,
useAbortSignal: false,
maxRetryTimeMs: 90 * 1000,
recordCommandRetries: true,
}
export async function fetchTheme(id: number, session: AdminSession): Promise<Theme | undefined> {
const gid = composeThemeGid(id)
recordEvent('theme-api:fetch-theme')
try {
const {theme} = await adminRequestDoc({
query: GetTheme,
session,
variables: {id: gid},
responseOptions: {handleErrors: false},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (theme) {
return buildTheme({
id: parseGid(theme.id),
processing: theme.processing,
role: theme.role.toLowerCase(),
name: theme.name,
})
}
// eslint-disable-next-line no-catch-all/no-catch-all
} catch (error) {
/**
* Consumers of this and other theme APIs in this file expect either a theme
* or `undefined`.
*
* Error handlers should not inspect GraphQL error messages directly, as
* they are internationalized.
*/
recordError(error)
outputDebug(`Error fetching theme with ID: ${id}`)
}
}
export async function fetchThemes(session: AdminSession): Promise<Theme[]> {
const themes: Theme[] = []
let after: string | null = null
recordEvent('theme-api:fetch-themes')
while (true) {
// eslint-disable-next-line no-await-in-loop
const response = await adminRequestDoc({
query: GetThemes,
session,
variables: {after},
responseOptions: {handleErrors: false},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!response.themes) {
unexpectedGraphQLError('Failed to fetch themes')
}
const {nodes, pageInfo} = response.themes
nodes.forEach((theme) => {
const t = buildTheme({
id: parseGid(theme.id),
processing: theme.processing,
role: theme.role.toLowerCase(),
name: theme.name,
})
if (t) {
themes.push(t)
}
})
if (!pageInfo.hasNextPage) {
return themes
}
after = pageInfo.endCursor as string
}
}
export async function themeCreate(params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {
const themeSource = params.src ?? SkeletonThemeCdn
recordEvent('theme-api:create-theme')
const {themeCreate} = await adminRequestDoc({
query: ThemeCreate,
session,
variables: {
name: params.name ?? '',
source: themeSource,
role: (params.role ?? DEVELOPMENT_THEME_ROLE).toUpperCase() as ThemeRole,
},
responseOptions: {handleErrors: false},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!themeCreate) {
unexpectedGraphQLError('Failed to create theme')
}
const {theme, userErrors} = themeCreate
if (userErrors.length) {
const userErrors = themeCreate.userErrors.map((error) => error.message).join(', ')
throw recordError(new AbortError(userErrors))
}
if (!theme) {
unexpectedGraphQLError('Failed to create theme')
}
return buildTheme({
id: parseGid(theme.id),
name: theme.name,
role: theme.role.toLowerCase(),
})
}
export async function fetchThemeAssets(id: number, filenames: Key[], session: AdminSession): Promise<ThemeAsset[]> {
const assets: ThemeAsset[] = []
let after: string | null = null
recordEvent('theme-api:fetch-assets')
while (true) {
// eslint-disable-next-line no-await-in-loop
const response = await adminRequestDoc({
query: GetThemeFileBodies,
session,
variables: {id: themeGid(id), filenames, after},
responseOptions: {handleErrors: false},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!response.theme?.files?.nodes || !response.theme?.files?.pageInfo) {
const userErrors = response.theme?.files?.userErrors.map((error) => error.filename).join(', ')
unexpectedGraphQLError(`Error fetching assets: ${userErrors}`)
}
const {nodes, pageInfo} = response.theme.files
assets.push(
// eslint-disable-next-line no-await-in-loop
...(await Promise.all(
nodes.map(async (file) => {
const {attachment, value} = await parseThemeFileContent(file.body)
return {
attachment,
key: file.filename,
checksum: file.checksumMd5 as string,
value,
}
}),
)),
)
if (!pageInfo.hasNextPage) {
return assets
}
after = pageInfo.endCursor as string
}
}
export async function deleteThemeAssets(id: number, filenames: Key[], session: AdminSession): Promise<Result[]> {
const batchSize = 50
const results: Result[] = []
recordEvent('theme-api:delete-assets')
for (let i = 0; i < filenames.length; i += batchSize) {
const batch = filenames.slice(i, i + batchSize)
// eslint-disable-next-line no-await-in-loop
const {themeFilesDelete} = await adminRequestDoc({
query: ThemeFilesDelete,
session,
variables: {
themeId: composeThemeGid(id),
files: batch,
},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!themeFilesDelete) {
unexpectedGraphQLError('Failed to delete theme assets')
}
const {deletedThemeFiles, userErrors} = themeFilesDelete
if (deletedThemeFiles) {
deletedThemeFiles.forEach((file) => {
results.push({key: file.filename, success: true, operation: Operation.Delete})
})
}
if (userErrors.length > 0) {
userErrors.forEach((error) => {
if (error.filename) {
recordError(`Asset deletion failed for ${error.filename}: ${error.message}`)
results.push({
key: error.filename,
success: false,
operation: Operation.Delete,
errors: {asset: [error.message]},
})
} else {
unexpectedGraphQLError(`Failed to delete theme assets: ${error.message}`)
}
})
}
}
return results
}
export async function bulkUploadThemeAssets(
id: number,
assets: AssetParams[],
session: AdminSession,
): Promise<Result[]> {
const results: Result[] = []
recordEvent('theme-api:bulk-upload-assets')
for (let i = 0; i < assets.length; i += 50) {
const chunk = assets.slice(i, i + 50)
const files = prepareFilesForUpload(chunk)
recordTiming('theme-api:upload-files')
// eslint-disable-next-line no-await-in-loop
const uploadResults = await uploadFiles(id, files, session)
recordTiming('theme-api:upload-files')
results.push(...processUploadResults(uploadResults))
}
return results
}
function prepareFilesForUpload(assets: AssetParams[]): OnlineStoreThemeFilesUpsertFileInput[] {
return assets.map((asset) => {
if (asset.attachment) {
return {
filename: asset.key,
body: {
type: 'BASE64' as const,
value: asset.attachment,
},
}
} else {
return {
filename: asset.key,
body: {
type: 'TEXT' as const,
value: asset.value ?? '',
},
}
}
})
}
async function uploadFiles(
themeId: number,
files: {filename: string; body: {type: OnlineStoreThemeFileBodyInputType; value: string}}[],
session: AdminSession,
): Promise<ThemeFilesUpsertMutation> {
return adminRequestDoc({
query: ThemeFilesUpsert,
session,
variables: {themeId: themeGid(themeId), files},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
}
function processUploadResults(uploadResults: ThemeFilesUpsertMutation): Result[] {
const {themeFilesUpsert} = uploadResults
if (!themeFilesUpsert) {
unexpectedGraphQLError('Failed to upload theme files')
}
const {upsertedThemeFiles, userErrors} = themeFilesUpsert
const results: Result[] = []
upsertedThemeFiles?.forEach((file) => {
results.push({
key: file.filename,
success: true,
operation: Operation.Upload,
})
})
userErrors.forEach((error) => {
if (!error.filename) {
unexpectedGraphQLError(`Error uploading theme files: ${error.message}`)
}
recordError(`Asset upload failed for ${error.filename}: ${error.message}`)
results.push({
key: error.filename,
success: false,
operation: Operation.Upload,
errors: {asset: [error.message]},
})
})
return results
}
export async function fetchChecksums(id: number, session: AdminSession): Promise<Checksum[]> {
const checksums: Checksum[] = []
let after: string | null = null
recordEvent('theme-api:fetch-checksums')
while (true) {
// eslint-disable-next-line no-await-in-loop
const response = await adminRequestDoc({
query: GetThemeFileChecksums,
session,
variables: {id: themeGid(id), after},
responseOptions: {handleErrors: false},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!response?.theme?.files?.nodes || !response?.theme?.files?.pageInfo) {
const userErrors = response.theme?.files?.userErrors.map((error) => error.filename).join(', ')
throw recordError(new AbortError(`Failed to fetch checksums for: ${userErrors}`))
}
const {nodes, pageInfo} = response.theme.files
checksums.push(
...nodes.map((file) => ({
key: file.filename,
checksum: file.checksumMd5 as string,
})),
)
if (!pageInfo.hasNextPage) {
return checksums
}
after = pageInfo.endCursor as string
}
}
export async function themeUpdate(id: number, params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {
const name = params.name
const input: {[key: string]: string} = {}
if (name) {
input.name = name
}
recordEvent('theme-api:update-theme')
const {themeUpdate} = await adminRequestDoc({
query: ThemeUpdate,
session,
variables: {id: composeThemeGid(id), input},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!themeUpdate) {
// An unexpected error occurred during the GraphQL request execution
unexpectedGraphQLError('Failed to update theme')
}
const {theme, userErrors} = themeUpdate
if (userErrors.length) {
const userErrors = themeUpdate.userErrors.map((error) => error.message).join(', ')
throw recordError(new AbortError(userErrors))
}
if (!theme) {
// An unexpected error if neither theme nor userErrors are returned
unexpectedGraphQLError('Failed to update theme')
}
return buildTheme({
id: parseGid(theme.id),
name: theme.name,
role: theme.role.toLowerCase(),
})
}
export async function themePublish(id: number, session: AdminSession): Promise<Theme | undefined> {
recordEvent('theme-api:publish-theme')
const {themePublish} = await adminRequestDoc({
query: ThemePublish,
session,
variables: {id: composeThemeGid(id)},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!themePublish) {
// An unexpected error occurred during the GraphQL request execution
unexpectedGraphQLError('Failed to update theme')
}
const {theme, userErrors} = themePublish
if (userErrors.length) {
const userErrors = themePublish.userErrors.map((error) => error.message).join(', ')
throw recordError(new AbortError(userErrors))
}
if (!theme) {
// An unexpected error if neither theme nor userErrors are returned
unexpectedGraphQLError('Failed to update theme')
}
return buildTheme({
id: parseGid(theme.id),
name: theme.name,
role: theme.role.toLowerCase(),
})
}
export async function themeDelete(id: number, session: AdminSession): Promise<boolean | undefined> {
recordEvent('theme-api:delete-theme')
const {themeDelete} = await adminRequestDoc({
query: ThemeDelete,
session,
variables: {id: composeThemeGid(id)},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
})
if (!themeDelete) {
// An unexpected error occurred during the GraphQL request execution
unexpectedGraphQLError('Failed to update theme')
}
const {deletedThemeId, userErrors} = themeDelete
if (userErrors.length) {
const userErrors = themeDelete.userErrors.map((error) => error.message).join(', ')
throw recordError(new AbortError(userErrors))
}
if (!deletedThemeId) {
// An unexpected error if neither theme nor userErrors are returned
unexpectedGraphQLError('Failed to update theme')
}
return true
}
export interface ThemeDuplicateResult {
theme?: Theme
userErrors: {field?: string[] | null; message: string}[]
requestId?: string
}
export async function themeDuplicate(
id: number,
name: string | undefined,
session: AdminSession,
): Promise<ThemeDuplicateResult> {
let requestId: string | undefined
recordEvent('theme-api:duplicate-theme')
const {themeDuplicate} = await adminRequestDoc({
query: ThemeDuplicate,
session,
variables: {id: composeThemeGid(id), name},
preferredBehaviour: THEME_API_NETWORK_BEHAVIOUR,
responseOptions: {
onResponse: (response) => {
requestId = response.headers.get('x-request-id') ?? undefined
},
},
})
if (!themeDuplicate) {
// An unexpected error occurred during the GraphQL request execution
recordError('Failed to duplicate theme')
return {
theme: undefined,
userErrors: [{message: 'Failed to duplicate theme'}],
requestId,
}
}
const {newTheme, userErrors} = themeDuplicate
if (userErrors.length > 0) {
return {
theme: undefined,
userErrors,
requestId,
}
}
if (!newTheme) {
// An unexpected error if neither theme nor userErrors are returned
return {
theme: undefined,
userErrors: [{message: 'Failed to duplicate theme'}],
requestId,
}
}
const theme = buildTheme({
id: parseGid(newTheme.id),
name: newTheme.name,
role: newTheme.role.toLowerCase(),
})
return {
theme,
userErrors: [],
requestId,
}
}
export async function metafieldDefinitionsByOwnerType(type: MetafieldOwnerType, session: AdminSession) {
recordEvent('theme-api:fetch-metafield-definitions')
const {metafieldDefinitions} = await adminRequestDoc({
query: MetafieldDefinitionsByOwnerType,
session,
variables: {ownerType: type},
})
return metafieldDefinitions.nodes.map((definition) => ({
key: definition.key,
namespace: definition.namespace,
name: definition.name,
description: definition.description,
type: {
name: definition.type.name,
category: definition.type.category,
},
}))
}
export async function passwordProtected(session: AdminSession): Promise<boolean> {
recordEvent('theme-api:check-password-protection')
const {onlineStore} = await adminRequestDoc({
query: OnlineStorePasswordProtection,
session,
})
if (!onlineStore) {
unexpectedGraphQLError("Unable to get details about the storefront's password protection")
}
const {passwordProtection} = onlineStore
return passwordProtection.enabled
}
function unexpectedGraphQLError(message: string): never {
throw recordError(new AbortError(message))
}
function themeGid(id: number): string {
return `gid://shopify/OnlineStoreTheme/${id}`
}
type OnlineStoreThemeFileBody =
| {__typename: 'OnlineStoreThemeFileBodyBase64'; contentBase64: string}
| {__typename: 'OnlineStoreThemeFileBodyText'; content: string}
| {__typename: 'OnlineStoreThemeFileBodyUrl'; url: string}
export async function parseThemeFileContent(
body: OnlineStoreThemeFileBody,
): Promise<{value?: string; attachment?: string}> {
switch (body.__typename) {
case 'OnlineStoreThemeFileBodyText':
return {value: body.content}
case 'OnlineStoreThemeFileBodyBase64':
return {attachment: body.contentBase64}
case 'OnlineStoreThemeFileBodyUrl':
try {
// eslint-disable-next-line no-restricted-globals
const response = await fetch(body.url)
const arrayBuffer = await response.arrayBuffer()
return {attachment: Buffer.from(arrayBuffer).toString('base64')}
} catch (error) {
// Raise error if we can't download the file
throw recordError(new AbortError(`Error downloading content from URL: ${body.url}`))
}
}
}