@sanity/export 2.33.1-performance-opts.1 → 3.0.0-definetype.62

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.
@@ -1,105 +1,69 @@
1
1
  "use strict";
2
2
 
3
- var _excluded = ["asset"];
4
-
5
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
6
-
7
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
8
-
9
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
10
-
11
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
12
-
13
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
14
-
15
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
16
-
17
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
18
-
19
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
20
-
21
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
22
-
23
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
24
-
25
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
26
-
27
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
28
-
29
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
30
4
 
31
- var path = require('path');
5
+ const path = require('path');
32
6
 
33
- var crypto = require('crypto');
7
+ const crypto = require('crypto');
34
8
 
35
- var _require = require('url'),
36
- parseUrl = _require.parse,
37
- formatUrl = _require.format;
9
+ const {
10
+ parse: parseUrl,
11
+ format: formatUrl
12
+ } = require('url');
38
13
 
39
- var fse = require('fs-extra');
14
+ const {
15
+ mkdirSync,
16
+ createWriteStream
17
+ } = require('fs');
40
18
 
41
- var miss = require('mississippi');
19
+ const miss = require('mississippi');
42
20
 
43
- var PQueue = require('p-queue');
21
+ const PQueue = require('p-queue');
44
22
 
45
- var _require2 = require('lodash'),
46
- omit = _require2.omit,
47
- noop = _require2.noop;
23
+ const {
24
+ omit,
25
+ noop
26
+ } = require('lodash');
48
27
 
49
- var pkg = require('../package.json');
28
+ const pkg = require('../package.json');
50
29
 
51
- var requestStream = require('./requestStream');
30
+ const requestStream = require('./requestStream');
52
31
 
53
- var debug = require('./debug');
32
+ const debug = require('./debug');
54
33
 
55
- var EXCLUDE_PROPS = ['_id', '_type', 'assetId', 'extension', 'mimeType', 'path', 'url'];
56
- var ACTION_REMOVE = 'remove';
57
- var ACTION_REWRITE = 'rewrite';
58
- var ASSET_DOWNLOAD_CONCURRENCY = 8;
34
+ const rimraf = require('./util/rimraf');
35
+
36
+ const EXCLUDE_PROPS = ['_id', '_type', 'assetId', 'extension', 'mimeType', 'path', 'url'];
37
+ const ACTION_REMOVE = 'remove';
38
+ const ACTION_REWRITE = 'rewrite';
39
+ const ASSET_DOWNLOAD_CONCURRENCY = 8;
59
40
 
60
41
  class AssetHandler {
61
42
  constructor(options) {
62
- var _this = this;
63
-
64
- _defineProperty(this, "rewriteAssets", miss.through.obj( /*#__PURE__*/function () {
65
- var _ref = _asyncToGenerator(function* (doc, enc, callback) {
66
- if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
67
- var type = doc._type === 'sanity.imageAsset' ? 'image' : 'file';
68
- var filePath = "".concat(type, "s/").concat(generateFilename(doc._id));
69
-
70
- _this.assetsSeen.set(doc._id, type);
71
-
72
- _this.queueAssetDownload(doc, filePath, type);
73
-
74
- callback();
75
- return;
76
- }
77
-
78
- callback(null, _this.findAndModify(doc, ACTION_REWRITE));
79
- });
80
-
81
- return function (_x, _x2, _x3) {
82
- return _ref.apply(this, arguments);
83
- };
84
- }()));
43
+ _defineProperty(this, "rewriteAssets", miss.through.obj(async (doc, enc, callback) => {
44
+ if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
45
+ const type = doc._type === 'sanity.imageAsset' ? 'image' : 'file';
46
+ const filePath = "".concat(type, "s/").concat(generateFilename(doc._id));
47
+ this.assetsSeen.set(doc._id, type);
48
+ this.queueAssetDownload(doc, filePath, type);
49
+ callback();
50
+ return;
51
+ }
85
52
 
86
- _defineProperty(this, "stripAssets", miss.through.obj( /*#__PURE__*/function () {
87
- var _ref2 = _asyncToGenerator(function* (doc, enc, callback) {
88
- if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
89
- callback();
90
- return;
91
- }
53
+ callback(null, this.findAndModify(doc, ACTION_REWRITE));
54
+ }));
92
55
 
93
- callback(null, _this.findAndModify(doc, ACTION_REMOVE));
94
- });
56
+ _defineProperty(this, "stripAssets", miss.through.obj(async (doc, enc, callback) => {
57
+ if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
58
+ callback();
59
+ return;
60
+ }
95
61
 
96
- return function (_x4, _x5, _x6) {
97
- return _ref2.apply(this, arguments);
98
- };
99
- }()));
62
+ callback(null, this.findAndModify(doc, ACTION_REMOVE));
63
+ }));
100
64
 
101
65
  _defineProperty(this, "skipAssets", miss.through.obj((doc, enc, callback) => {
102
- var isAsset = ['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type);
66
+ const isAsset = ['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type);
103
67
 
104
68
  if (isAsset) {
105
69
  callback();
@@ -113,7 +77,7 @@ class AssetHandler {
113
77
 
114
78
  _defineProperty(this, "findAndModify", (item, action) => {
115
79
  if (Array.isArray(item)) {
116
- var children = item.map(child => this.findAndModify(child, action));
80
+ const children = item.map(child => this.findAndModify(child, action));
117
81
  return children.filter(Boolean);
118
82
  }
119
83
 
@@ -121,30 +85,32 @@ class AssetHandler {
121
85
  return item;
122
86
  }
123
87
 
124
- var isAsset = isAssetField(item);
88
+ const isAsset = isAssetField(item);
125
89
 
126
90
  if (isAsset && action === ACTION_REMOVE) {
127
91
  return undefined;
128
92
  }
129
93
 
130
94
  if (isAsset && action === ACTION_REWRITE) {
131
- var asset = item.asset,
132
- other = _objectWithoutProperties(item, _excluded);
133
-
134
- var assetId = asset._ref;
135
- var assetType = getAssetType(item);
136
- var filePath = "".concat(assetType, "s/").concat(generateFilename(assetId));
137
- return _objectSpread({
138
- _sanityAsset: "".concat(assetType, "@file://./").concat(filePath)
139
- }, this.findAndModify(other, action));
95
+ const {
96
+ asset,
97
+ ...other
98
+ } = item;
99
+ const assetId = asset._ref;
100
+ const assetType = getAssetType(item);
101
+ const filePath = "".concat(assetType, "s/").concat(generateFilename(assetId));
102
+ return {
103
+ _sanityAsset: "".concat(assetType, "@file://./").concat(filePath),
104
+ ...this.findAndModify(other, action)
105
+ };
140
106
  }
141
107
 
142
- var newItem = {};
143
- var keys = Object.keys(item);
108
+ const newItem = {};
109
+ const keys = Object.keys(item);
144
110
 
145
- for (var i = 0; i < keys.length; i++) {
146
- var key = keys[i];
147
- var value = item[key];
111
+ for (let i = 0; i < keys.length; i++) {
112
+ const key = keys[i];
113
+ const value = item[key];
148
114
  newItem[key] = this.findAndModify(value, action);
149
115
 
150
116
  if (typeof newItem[key] === 'undefined') {
@@ -155,7 +121,7 @@ class AssetHandler {
155
121
  return newItem;
156
122
  });
157
123
 
158
- var concurrency = options.concurrency || ASSET_DOWNLOAD_CONCURRENCY;
124
+ const concurrency = options.concurrency || ASSET_DOWNLOAD_CONCURRENCY;
159
125
  debug('Using asset download concurrency of %d', concurrency);
160
126
  this.client = options.client;
161
127
  this.tmpDir = options.tmpDir;
@@ -214,26 +180,30 @@ class AssetHandler {
214
180
  /* eslint-disable no-sync */
215
181
 
216
182
 
217
- fse.ensureDirSync(path.join(this.tmpDir, 'files'));
218
- fse.ensureDirSync(path.join(this.tmpDir, 'images'));
183
+ mkdirSync(path.join(this.tmpDir, 'files'), {
184
+ recursive: true
185
+ });
186
+ mkdirSync(path.join(this.tmpDir, 'images'), {
187
+ recursive: true
188
+ });
219
189
  /* eslint-enable no-sync */
220
190
 
221
191
  this.assetDirsCreated = true;
222
192
  }
223
193
 
224
194
  getAssetRequestOptions(assetDoc) {
225
- var token = this.client.config().token;
226
- var headers = {
195
+ const token = this.client.config().token;
196
+ const headers = {
227
197
  'User-Agent': "".concat(pkg.name, "@").concat(pkg.version)
228
198
  };
229
- var isImage = assetDoc._type === 'sanity.imageAsset';
230
- var url = parseUrl(assetDoc.url, true);
199
+ const isImage = assetDoc._type === 'sanity.imageAsset';
200
+ const url = parseUrl(assetDoc.url, true);
231
201
 
232
202
  if (isImage && ['cdn.sanity.io', 'cdn.sanity.work'].includes(url.hostname) && token) {
233
203
  headers.Authorization = "Bearer ".concat(token);
234
- url.query = _objectSpread(_objectSpread({}, url.query || {}), {}, {
204
+ url.query = { ...(url.query || {}),
235
205
  dlRaw: 'true'
236
- });
206
+ };
237
207
  }
238
208
 
239
209
  return {
@@ -242,95 +212,80 @@ class AssetHandler {
242
212
  };
243
213
  }
244
214
 
245
- downloadAsset(assetDoc, dstPath) {
246
- var _arguments = arguments,
247
- _this2 = this;
248
-
249
- return _asyncToGenerator(function* () {
250
- var attemptNum = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : 0;
251
- var url = assetDoc.url;
252
-
253
- var options = _this2.getAssetRequestOptions(assetDoc);
254
-
255
- var stream;
256
-
257
- try {
258
- stream = yield requestStream(options);
259
- } catch (err) {
260
- _this2.reject(err);
261
-
262
- return false;
263
- }
264
-
265
- if (stream.statusCode !== 200) {
266
- _this2.queue.clear();
267
-
268
- var err = yield tryGetErrorFromStream(stream);
269
- var errMsg = "Referenced asset URL \"".concat(url, "\" returned HTTP ").concat(stream.statusCode);
270
-
271
- if (err) {
272
- errMsg = "".concat(errMsg, ":\n\n").concat(err);
273
- }
215
+ async downloadAsset(assetDoc, dstPath) {
216
+ let attemptNum = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
217
+ const {
218
+ url
219
+ } = assetDoc;
220
+ const options = this.getAssetRequestOptions(assetDoc);
221
+ let stream;
222
+
223
+ try {
224
+ stream = await requestStream(options);
225
+ } catch (err) {
226
+ this.reject(err);
227
+ return false;
228
+ }
274
229
 
275
- _this2.reject(new Error(errMsg));
230
+ if (stream.statusCode !== 200) {
231
+ this.queue.clear();
232
+ const err = await tryGetErrorFromStream(stream);
233
+ let errMsg = "Referenced asset URL \"".concat(url, "\" returned HTTP ").concat(stream.statusCode);
276
234
 
277
- return false;
235
+ if (err) {
236
+ errMsg = "".concat(errMsg, ":\n\n").concat(err);
278
237
  }
279
238
 
280
- _this2.maybeCreateAssetDirs();
281
-
282
- debug('Asset stream ready, writing to filesystem at %s', dstPath);
283
- var tmpPath = path.join(_this2.tmpDir, dstPath);
284
-
285
- var _yield$writeHashedStr = yield writeHashedStream(tmpPath, stream),
286
- sha1 = _yield$writeHashedStr.sha1,
287
- md5 = _yield$writeHashedStr.md5,
288
- size = _yield$writeHashedStr.size; // Verify it against our downloaded stream to make sure we have the same copy
289
-
290
-
291
- var contentLength = stream.headers['content-length'];
292
- var remoteSha1 = stream.headers['x-sanity-sha1'];
293
- var remoteMd5 = stream.headers['x-sanity-md5'];
294
- var hasHash = Boolean(remoteSha1 || remoteMd5);
295
- var method = sha1 ? 'sha1' : 'md5'; // Asset validity is primarily determined by the sha1 hash. However, the sha1 hash is computed
296
- // before certain processes (i.e. svg sanitization) which can result in a different hash.
297
- // When the sha1 hashes don't match, fallback to using the md5 hash.
298
-
299
- var sha1Differs = remoteSha1 && sha1 !== remoteSha1;
300
- var md5Differs = remoteMd5 && md5 !== remoteMd5;
301
- var differs = sha1Differs && md5Differs;
302
-
303
- if (differs && attemptNum < 3) {
304
- debug('%s does not match downloaded asset, retrying (#%d) [%s]', method, attemptNum + 1, url);
305
- return _this2.downloadAsset(assetDoc, dstPath, attemptNum + 1);
306
- } else if (differs) {
307
- var details = [hasHash && (method === 'md5' ? "md5 should be ".concat(remoteMd5, ", got ").concat(md5) : "sha1 should be ".concat(remoteSha1, ", got ").concat(sha1)), contentLength && parseInt(contentLength, 10) !== size && "Asset should be ".concat(contentLength, " bytes, got ").concat(size), "Did not succeed after ".concat(attemptNum, " attempts.")];
308
- var detailsString = "Details:\n - ".concat(details.filter(Boolean).join('\n - '));
309
- yield fse.unlink(tmpPath);
310
-
311
- _this2.queue.clear();
312
-
313
- var error = new Error("Failed to download asset at ".concat(assetDoc.url, ", giving up. ").concat(detailsString));
314
-
315
- _this2.reject(error);
316
-
317
- return false;
318
- }
239
+ this.reject(new Error(errMsg));
240
+ return false;
241
+ }
319
242
 
320
- var isImage = assetDoc._type === 'sanity.imageAsset';
321
- var type = isImage ? 'image' : 'file';
322
- var id = "".concat(type, "-").concat(sha1);
323
- var metaProps = omit(assetDoc, EXCLUDE_PROPS);
243
+ this.maybeCreateAssetDirs();
244
+ debug('Asset stream ready, writing to filesystem at %s', dstPath);
245
+ const tmpPath = path.join(this.tmpDir, dstPath);
246
+ const {
247
+ sha1,
248
+ md5,
249
+ size
250
+ } = await writeHashedStream(tmpPath, stream); // Verify it against our downloaded stream to make sure we have the same copy
251
+
252
+ const contentLength = stream.headers['content-length'];
253
+ const remoteSha1 = stream.headers['x-sanity-sha1'];
254
+ const remoteMd5 = stream.headers['x-sanity-md5'];
255
+ const hasHash = Boolean(remoteSha1 || remoteMd5);
256
+ const method = sha1 ? 'sha1' : 'md5'; // Asset validity is primarily determined by the sha1 hash. However, the sha1 hash is computed
257
+ // before certain processes (i.e. svg sanitization) which can result in a different hash.
258
+ // When the sha1 hashes don't match, fallback to using the md5 hash.
259
+
260
+ const sha1Differs = remoteSha1 && sha1 !== remoteSha1;
261
+ const md5Differs = remoteMd5 && md5 !== remoteMd5;
262
+ const differs = sha1Differs && md5Differs;
263
+
264
+ if (differs && attemptNum < 3) {
265
+ debug('%s does not match downloaded asset, retrying (#%d) [%s]', method, attemptNum + 1, url);
266
+ return this.downloadAsset(assetDoc, dstPath, attemptNum + 1);
267
+ } else if (differs) {
268
+ const details = [hasHash && (method === 'md5' ? "md5 should be ".concat(remoteMd5, ", got ").concat(md5) : "sha1 should be ".concat(remoteSha1, ", got ").concat(sha1)), contentLength && parseInt(contentLength, 10) !== size && "Asset should be ".concat(contentLength, " bytes, got ").concat(size), "Did not succeed after ".concat(attemptNum, " attempts.")];
269
+ const detailsString = "Details:\n - ".concat(details.filter(Boolean).join('\n - '));
270
+ await rimraf(tmpPath);
271
+ this.queue.clear();
272
+ const error = new Error("Failed to download asset at ".concat(assetDoc.url, ", giving up. ").concat(detailsString));
273
+ this.reject(error);
274
+ return false;
275
+ }
324
276
 
325
- if (Object.keys(metaProps).length > 0) {
326
- _this2.assetMap[id] = metaProps;
327
- }
277
+ const isImage = assetDoc._type === 'sanity.imageAsset';
278
+ const type = isImage ? 'image' : 'file';
279
+ const id = "".concat(type, "-").concat(sha1);
280
+ const metaProps = omit(assetDoc, EXCLUDE_PROPS);
328
281
 
329
- _this2.downloading.splice(_this2.downloading.findIndex(datUrl => datUrl === url), 1);
282
+ if (Object.keys(metaProps).length > 0) {
283
+ this.assetMap[id] = metaProps;
284
+ }
330
285
 
331
- _this2.filesWritten++;
332
- return true;
333
- })();
286
+ this.downloading.splice(this.downloading.findIndex(datUrl => datUrl === url), 1);
287
+ this.filesWritten++;
288
+ return true;
334
289
  }
335
290
 
336
291
  }
@@ -344,10 +299,7 @@ function getAssetType(item) {
344
299
  return null;
345
300
  }
346
301
 
347
- var _ref3 = item.asset._ref.match(/^(image|file)-/) || [],
348
- _ref4 = _slicedToArray(_ref3, 2),
349
- type = _ref4[1];
350
-
302
+ const [, type] = item.asset._ref.match(/^(image|file)-/) || [];
351
303
  return type || null;
352
304
  }
353
305
 
@@ -356,26 +308,22 @@ function isSanityAsset(assetId) {
356
308
  }
357
309
 
358
310
  function generateFilename(assetId) {
359
- var _ref5 = assetId.match(/^(image|file)-(.*?)(-[a-z]+)?$/) || [],
360
- _ref6 = _slicedToArray(_ref5, 4),
361
- asset = _ref6[2],
362
- ext = _ref6[3];
363
-
364
- var extension = (ext || 'bin').replace(/^-/, '');
311
+ const [,, asset, ext] = assetId.match(/^(image|file)-(.*?)(-[a-z]+)?$/) || [];
312
+ const extension = (ext || 'bin').replace(/^-/, '');
365
313
  return asset ? "".concat(asset, ".").concat(extension) : "".concat(assetId, ".bin");
366
314
  }
367
315
 
368
316
  function writeHashedStream(filePath, stream) {
369
- var size = 0;
370
- var md5 = crypto.createHash('md5');
371
- var sha1 = crypto.createHash('sha1');
372
- var hasher = miss.through((chunk, enc, cb) => {
317
+ let size = 0;
318
+ const md5 = crypto.createHash('md5');
319
+ const sha1 = crypto.createHash('sha1');
320
+ const hasher = miss.through((chunk, enc, cb) => {
373
321
  size += chunk.length;
374
322
  md5.update(chunk);
375
323
  sha1.update(chunk);
376
324
  cb(null, chunk);
377
325
  });
378
- return new Promise((resolve, reject) => miss.pipe(stream, hasher, fse.createWriteStream(filePath), err => {
326
+ return new Promise((resolve, reject) => miss.pipe(stream, hasher, createWriteStream(filePath), err => {
379
327
  if (err) {
380
328
  reject(err);
381
329
  return;
@@ -395,7 +343,7 @@ function tryGetErrorFromStream(stream) {
395
343
 
396
344
  function parse(body) {
397
345
  try {
398
- var parsed = JSON.parse(body.toString('utf8'));
346
+ const parsed = JSON.parse(body.toString('utf8'));
399
347
  resolve(parsed.message || parsed.error || null);
400
348
  } catch (err) {
401
349
  resolve(body.toString('utf8').slice(0, 16000));