@automattic/vip 2.30.0 → 2.31.0-dev1

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.
Files changed (47) hide show
  1. package/dist/bin/vip-dev-env-sync-sql.js +11 -18
  2. package/dist/bin/vip-export-sql.js +12 -11
  3. package/dist/bin/vip-import-sql.js +2 -2
  4. package/dist/bin/vip-whoami.js +7 -10
  5. package/dist/commands/dev-env-sync-sql.js +29 -15
  6. package/dist/commands/export-sql.js +1 -1
  7. package/dist/lib/analytics/clients/pendo.js +11 -20
  8. package/dist/lib/analytics/clients/tracks.js +12 -12
  9. package/dist/lib/analytics/index.js +9 -12
  10. package/dist/lib/api/app.js +10 -13
  11. package/dist/lib/api/cache-purge.js +3 -10
  12. package/dist/lib/api/feature-flags.js +4 -2
  13. package/dist/lib/api/http.js +10 -18
  14. package/dist/lib/api/user.js +3 -8
  15. package/dist/lib/api.js +11 -14
  16. package/dist/lib/app-logs/app-logs.js +3 -6
  17. package/dist/lib/cli/apiConfig.js +10 -7
  18. package/dist/lib/cli/config.js +2 -3
  19. package/dist/lib/cli/envAlias.js +11 -9
  20. package/dist/lib/cli/exit.js +4 -7
  21. package/dist/lib/cli/format.js +25 -26
  22. package/dist/lib/cli/progress.js +7 -3
  23. package/dist/lib/cli/prompt.js +3 -2
  24. package/dist/lib/client-file-uploader.js +86 -87
  25. package/dist/lib/config/software.js +18 -12
  26. package/dist/lib/env.js +16 -13
  27. package/dist/lib/envvar/api-delete.js +2 -0
  28. package/dist/lib/envvar/api-get-all.js +4 -1
  29. package/dist/lib/envvar/api-get.js +3 -1
  30. package/dist/lib/envvar/api-list.js +8 -3
  31. package/dist/lib/envvar/api-set.js +2 -0
  32. package/dist/lib/envvar/api.js +2 -5
  33. package/dist/lib/envvar/input.js +7 -8
  34. package/dist/lib/envvar/read-file.js +4 -7
  35. package/dist/lib/http/proxy-agent.js +5 -4
  36. package/dist/lib/read-file.js +13 -14
  37. package/dist/lib/search-and-replace.js +17 -26
  38. package/dist/lib/tracker.js +12 -12
  39. package/dist/lib/user-error.js +6 -5
  40. package/dist/lib/utils.js +18 -22
  41. package/dist/lib/vip-import-validate-files.js +23 -22
  42. package/npm-shrinkwrap.json +37 -1003
  43. package/package.json +4 -4
  44. package/tsconfig.json +4 -2
  45. package/dist/lib/analytics/clients/stub.js +0 -16
  46. package/dist/lib/cli/repo.js +0 -61
  47. package/noImplictAnyImportBypass.d.ts +0 -6
@@ -8,9 +8,12 @@
8
8
  /**
9
9
  * External dependencies
10
10
  */
11
+
12
+ /**
13
+ * Internal dependencies
14
+ */
11
15
  "use strict";
12
16
 
13
- var _chalk = _interopRequireDefault(require("chalk"));
14
17
  var _command = _interopRequireDefault(require("../lib/cli/command"));
15
18
  var _devEnvironmentCore = require("../lib/dev-environment/dev-environment-core");
16
19
  var _devEnvironmentLando = require("../lib/dev-environment/dev-environment-lando");
@@ -19,9 +22,6 @@ var _devEnvSyncSql = require("../commands/dev-env-sync-sql");
19
22
  var _devEnvironment = require("../lib/constants/dev-environment");
20
23
  var _tracker = require("../lib/tracker");
21
24
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
22
- /**
23
- * Internal dependencies
24
- */
25
25
  const examples = [{
26
26
  usage: `${_devEnvironment.DEV_ENVIRONMENT_FULL_COMMAND} sync sql @my-test.develop --slug=my_site`,
27
27
  description: 'Syncs with the `my-test` site\'s `develop` environment database into `my_site`'
@@ -39,6 +39,13 @@ const appQuery = `
39
39
  primaryDomain { name }
40
40
  uniqueLabel
41
41
  isMultisite
42
+ wpSitesSDS(first:500) {
43
+ nodes {
44
+ id
45
+ blogId
46
+ homeUrl
47
+ }
48
+ }
42
49
  }
43
50
  `;
44
51
  (0, _command.default)({
@@ -58,20 +65,6 @@ const appQuery = `
58
65
  slug
59
66
  });
60
67
  await trackerFn('execute');
61
- if (env.isMultisite) {
62
- console.log(_chalk.default.yellow('You seem to be trying to sync a SQL database for a network site.'));
63
- console.log(_chalk.default.yellow('Unfortunately, the current version of our tool does not yet support syncing network sites.\n'));
64
- console.log(_chalk.default.yellow('However, you can manually export the database using the following command:'));
65
- console.log(_chalk.default.yellow(_chalk.default.bold(`vip export sql @${app.id}.${env.uniqueLabel} --output=${app.id}-${env.uniqueLabel}-exported.sql.gz\n`)));
66
- console.log(_chalk.default.yellow('After exporting the database, you\'ll need to perform the necessary search and replace operations on the exported file to update any relevant data or configurations.'));
67
- console.log(_chalk.default.yellow('See: https://docs.wpvip.com/how-tos/dev-env-add-content/#h-3-import-the-sql-file\n'));
68
- console.log(_chalk.default.yellow('Once you\'ve made the required changes, you can import the modified SQL file into your development environment using the following command:'));
69
- console.log(_chalk.default.yellow(_chalk.default.bold(`vip dev-env import sql ${app.id}-${env.uniqueLabel}-exported.sql.gz --slug=${slug}`)));
70
- await trackerFn('aborted', {
71
- error_type: 'multisite_not_supported'
72
- });
73
- process.exit(0);
74
- }
75
68
  const lando = await (0, _devEnvironmentLando.bootstrapLando)();
76
69
  const envPath = (0, _devEnvironmentCore.getEnvironmentPath)(slug);
77
70
  if (!(await (0, _devEnvironmentLando.isEnvUp)(lando, envPath))) {
@@ -26,17 +26,18 @@ const examples = [{
26
26
  description: 'The output file can be specified with the --output flag'
27
27
  }];
28
28
  const appQuery = `
29
- id,
30
- name,
31
- type,
32
- organization { id, name },
33
- environments{
34
- id
35
- appId
36
- type
37
- name
38
- primaryDomain { name }
39
- }
29
+ id,
30
+ name,
31
+ type,
32
+ organization { id, name },
33
+ environments{
34
+ id
35
+ appId
36
+ type
37
+ name
38
+ primaryDomain { name }
39
+ uniqueLabel
40
+ }
40
41
  `;
41
42
  (0, _command.default)({
42
43
  appContext: true,
@@ -317,7 +317,7 @@ const displayPlaybook = ({
317
317
  }
318
318
  }
319
319
  };
320
- (0, _command.default)({
320
+ void (0, _command.default)({
321
321
  appContext: true,
322
322
  appQuery,
323
323
  envContext: true,
@@ -498,7 +498,7 @@ Processing the SQL import for your environment...
498
498
  } catch (uploadError) {
499
499
  await track('import_sql_command_error', {
500
500
  error_type: 'upload_failed',
501
- upload_error: uploadError
501
+ upload_error: uploadError.message
502
502
  });
503
503
  progressTracker.stepFailed('upload');
504
504
  return failWithError(uploadError);
@@ -1,10 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- /**
4
- *
5
- * @format
6
- */
7
-
8
3
  /**
9
4
  * External dependencies
10
5
  */
@@ -26,28 +21,30 @@ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "functio
26
21
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
27
22
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28
23
  async function whoamiCommand() {
24
+ var _currentUser$displayN, _currentUser$id;
29
25
  const trackingParams = {
30
26
  command: 'vip whoami'
31
27
  };
32
28
  await (0, _tracker.trackEvent)('whoami_command_execute', trackingParams);
33
- let currentUser = {};
29
+ let currentUser;
34
30
  try {
35
31
  currentUser = await (0, _user.getCurrentUserInfo)();
36
32
  } catch (err) {
33
+ const error = err instanceof Error ? err : new Error('Unknown error');
37
34
  await (0, _tracker.trackEvent)('whoami_command_error', {
38
35
  ...trackingParams,
39
- error: err.message
36
+ error: error.message
40
37
  });
41
- exit.withError(`Failed to fetch information about the currently logged-in user error: ${err.message}`);
38
+ exit.withError(`Failed to fetch information about the currently logged-in user error: ${error.message}`);
42
39
  }
43
40
  await (0, _tracker.trackEvent)('whoami_command_success', trackingParams);
44
- const output = [`- Howdy ${currentUser.displayName}!`, `- Your user ID is ${currentUser.id}`];
41
+ const output = [`- Howdy ${(_currentUser$displayN = currentUser.displayName) !== null && _currentUser$displayN !== void 0 ? _currentUser$displayN : 'user'}!`, `- Your user ID is ${(_currentUser$id = currentUser.id) !== null && _currentUser$id !== void 0 ? _currentUser$id : ' not found'}`];
45
42
  if (currentUser.isVIP) {
46
43
  output.push('- Your account has VIP Staff permissions');
47
44
  }
48
45
  console.log(output.join('\n'));
49
46
  }
50
- (0, _command.default)({
47
+ void (0, _command.default)({
51
48
  usage: 'vip whoami'
52
49
  }).examples([{
53
50
  usage: 'vip whoami',
@@ -37,13 +37,10 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
37
37
  * @return {string} Site home url. null if not found
38
38
  */
39
39
  function findSiteHomeUrl(sql) {
40
+ var _sql$match;
40
41
  const regex = "'(siteurl|home)',\\s?'(.*?)'";
41
- const results = sql.match(regex);
42
- if (results) {
43
- const url = results[2];
44
- return _url.default.parse(url).hostname;
45
- }
46
- return null;
42
+ const url = ((_sql$match = sql.match(regex)) === null || _sql$match === void 0 ? void 0 : _sql$match[2]) || '';
43
+ return _url.default.parse(url).hostname || null;
47
44
  }
48
45
 
49
46
  /**
@@ -60,11 +57,12 @@ async function extractSiteUrls(sqlFile) {
60
57
  readInterface.on('line', line => {
61
58
  const domain = findSiteHomeUrl(line);
62
59
  if (domain) {
63
- domains.add('//' + domain);
60
+ domains.add(domain);
64
61
  }
65
62
  });
66
63
  readInterface.on('close', () => {
67
- resolve(Array.from(domains));
64
+ // Soring by length so that longest domains are replaced first
65
+ resolve(Array.from(domains).sort((dom1, dom2) => dom2.length - dom1.length));
68
66
  });
69
67
  readInterface.on('error', reject);
70
68
  });
@@ -86,7 +84,7 @@ class DevEnvSyncSQLCommand {
86
84
  this.tmpDir = (0, _utils.makeTempDir)();
87
85
  }
88
86
  get landoDomain() {
89
- return `//${this.slug}.vipdev.lndo.site`;
87
+ return `${this.slug}.vipdev.lndo.site`;
90
88
  }
91
89
  get sqlFile() {
92
90
  return `${this.tmpDir}/sql-export.sql`;
@@ -114,7 +112,7 @@ class DevEnvSyncSQLCommand {
114
112
  * @throws {Error} If there is an error reading the file
115
113
  */
116
114
  async runSearchReplace() {
117
- const replacements = this.siteUrls.reduce((acc, url) => [...acc, url, this.landoDomain], []);
115
+ const replacements = Object.entries(this.searchReplaceMap).flat();
118
116
  const readStream = _fs.default.createReadStream(this.sqlFile);
119
117
  const replacedStream = await (0, _vipSearchReplace.replace)(readStream, replacements);
120
118
  const outputFile = `${this.tmpDir}/sql-export-sr.sql`;
@@ -127,6 +125,20 @@ class DevEnvSyncSQLCommand {
127
125
  replacedStream.on('error', reject);
128
126
  });
129
127
  }
128
+ generateSearchReplaceMap() {
129
+ this.searchReplaceMap = {};
130
+ for (const url of this.siteUrls) {
131
+ this.searchReplaceMap[url] = this.landoDomain;
132
+ }
133
+ const networkSites = this.env.wpSitesSDS.nodes;
134
+ if (!networkSites) return;
135
+ for (const site of networkSites) {
136
+ if (!site.blogId || site.blogId === 1) continue;
137
+ const url = site.homeUrl.replace(/https?:\/\//, '');
138
+ if (!this.searchReplaceMap[url]) return;
139
+ this.searchReplaceMap[url] = `${site.blogId}.${this.landoDomain}`;
140
+ }
141
+ }
130
142
 
131
143
  /**
132
144
  * Runs the SQL import command to import the SQL file
@@ -161,9 +173,9 @@ class DevEnvSyncSQLCommand {
161
173
  console.log(`${_chalk.default.green('✓')} Extracted to ${this.sqlFile}`);
162
174
  } catch (err) {
163
175
  await this.track('archive_extraction_error', {
164
- errorMessage: err === null || err === void 0 ? void 0 : err.message
176
+ errorMessage: err.message
165
177
  });
166
- exit.withError(`Error extracting the SQL export: ${err === null || err === void 0 ? void 0 : err.message}`);
178
+ exit.withError(`Error extracting the SQL export: ${err.message}`);
167
179
  }
168
180
  try {
169
181
  console.log('Extracting site urls from the SQL file...');
@@ -171,11 +183,13 @@ class DevEnvSyncSQLCommand {
171
183
  } catch (err) {
172
184
  exit.withError(`Error extracting site URLs: ${err === null || err === void 0 ? void 0 : err.message}`);
173
185
  }
186
+ console.log('Generating search-replace configuration...');
187
+ this.generateSearchReplaceMap();
174
188
  try {
175
189
  console.log('Running the following search-replace operations on the SQL file:');
176
- this.siteUrls.forEach(domain => {
177
- console.log(` ${domain} -> ${this.landoDomain}`);
178
- });
190
+ for (const [domain, landoDomain] of Object.entries(this.searchReplaceMap)) {
191
+ console.log(` ${domain} -> ${landoDomain}`);
192
+ }
179
193
  await this.runSearchReplace();
180
194
  console.log(`${_chalk.default.green('✓')} Search-replace operation is complete`);
181
195
  } catch (err) {
@@ -353,7 +353,7 @@ class ExportSQLCommand {
353
353
  error_type: 'job_already_running',
354
354
  error_message: err === null || err === void 0 ? void 0 : err.message
355
355
  });
356
- exit.withError('There is an export job already running for this site: ' + `https://dashboard.wpvip.com/apps/${this.app.id}/${this.env.uniqueLabel}/data/database/backups\n` + 'Currently, we allow only one export job at a time, per site. Please try again later.');
356
+ exit.withError('There is an export job already running for this environment: ' + `https://dashboard.wpvip.com/apps/${this.app.id}/${this.env.uniqueLabel}/data/database/backups\n` + 'Currently, we allow only one export job at a time, per site. Please try again later.');
357
357
  }
358
358
  exit.withError(`Error creating export job: ${err === null || err === void 0 ? void 0 : err.message}`);
359
359
  }
@@ -4,36 +4,29 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+ var _debug = _interopRequireDefault(require("debug"));
7
8
  var _http = _interopRequireDefault(require("../../../lib/api/http"));
8
9
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
10
  /**
10
11
  * External dependencies
11
12
  */
12
- const debug = require('debug')('@automattic/vip:analytics:clients:pendo');
13
13
 
14
14
  /**
15
15
  * Internal dependencies
16
16
  */
17
17
 
18
+ const debug = (0, _debug.default)('@automattic/vip:analytics:clients:pendo');
18
19
  /**
19
20
  * Pendo analytics client.
20
21
  */
21
-
22
22
  class Pendo {
23
- context = {};
24
- static get ENDPOINT() {
25
- return '/pendo';
26
- }
27
- constructor({
28
- userId,
29
- eventPrefix,
30
- env
31
- }) {
32
- this.eventPrefix = eventPrefix;
33
- this.userAgent = env.userAgent;
34
- this.userId = userId;
23
+ static ENDPOINT = '/pendo';
24
+ constructor(options) {
25
+ this.eventPrefix = options.eventPrefix;
26
+ this.userAgent = options.env.userAgent;
27
+ this.userId = options.userId;
35
28
  this.context = {
36
- ...env
29
+ ...options.env
37
30
  };
38
31
  }
39
32
  async trackEvent(eventName, eventProps = {}) {
@@ -52,10 +45,8 @@ class Pendo {
52
45
  return await this.send(eventName, eventProps);
53
46
  } catch (error) {
54
47
  debug(error);
48
+ return Promise.resolve(false);
55
49
  }
56
-
57
- // Resolve to false instead of rejecting
58
- return Promise.resolve(false);
59
50
  }
60
51
  async send(eventName, eventProps) {
61
52
  const body = {
@@ -69,11 +60,11 @@ class Pendo {
69
60
  debug('send()', body);
70
61
  const response = await (0, _http.default)(Pendo.ENDPOINT, {
71
62
  method: 'POST',
72
- body
63
+ body: JSON.stringify(body)
73
64
  });
74
65
  const responseText = await response.text();
75
66
  debug('response', responseText);
76
- return responseText;
67
+ return response;
77
68
  }
78
69
  }
79
70
  exports.default = Pendo;
@@ -6,19 +6,19 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.default = void 0;
7
7
  var _nodeFetch = _interopRequireDefault(require("node-fetch"));
8
8
  var _querystring = _interopRequireDefault(require("querystring"));
9
+ var _debug = _interopRequireDefault(require("debug"));
9
10
  var _apiConfig = require("../../cli/apiConfig");
10
11
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
12
  /**
12
13
  * External dependencies
13
14
  */
14
- const debug = require('debug')('@automattic/vip:analytics:clients:tracks');
15
15
 
16
16
  /**
17
17
  * Internal dependencies
18
18
  */
19
19
 
20
+ const debug = (0, _debug.default)('@automattic/vip:analytics:clients:tracks');
20
21
  const validEventOrPropNamePattern = /^[a-z_][a-z0-9_]*$/;
21
-
22
22
  /**
23
23
  * Simple class for tracking using Automattic Tracks.
24
24
  *
@@ -28,9 +28,7 @@ const validEventOrPropNamePattern = /^[a-z_][a-z0-9_]*$/;
28
28
  // TODO: add batch support (can include multiples in `events` array)
29
29
 
30
30
  class Tracks {
31
- static get ENDPOINT() {
32
- return 'https://public-api.wordpress.com/rest/v1.1/tracks/record';
33
- }
31
+ static ENDPOINT = 'https://public-api.wordpress.com/rest/v1.1/tracks/record';
34
32
  constructor(userId, userType, eventPrefix, env) {
35
33
  this.eventPrefix = eventPrefix;
36
34
  this.userAgent = env.userAgent;
@@ -54,9 +52,10 @@ class Tracks {
54
52
  });
55
53
  eventProps.is_vip = await (0, _apiConfig.checkIfUserIsVip)(); // Add `is_vip` flag to every Tracks event recorded
56
54
 
57
- const event = Object.assign({
58
- _en: name
59
- }, eventProps);
55
+ const event = {
56
+ _en: name,
57
+ ...eventProps
58
+ };
60
59
 
61
60
  // For when we want to support batched events
62
61
  const events = [event];
@@ -89,10 +88,13 @@ class Tracks {
89
88
  }
90
89
 
91
90
  // Resolve to false instead of rejecting
92
- return Promise.resolve(false);
91
+ return false;
93
92
  }
94
93
  send(extraParams) {
95
- const params = Object.assign({}, this.baseParams, extraParams);
94
+ const params = {
95
+ ...this.baseParams,
96
+ ...extraParams
97
+ };
96
98
  const method = 'POST';
97
99
  const body = _querystring.default.stringify(params);
98
100
  const headers = {
@@ -100,8 +102,6 @@ class Tracks {
100
102
  'User-Agent': this.userAgent
101
103
  };
102
104
  debug('send()', body);
103
-
104
- // eslint-disable-next-line no-undef
105
105
  return (0, _nodeFetch.default)(Tracks.ENDPOINT, {
106
106
  method,
107
107
  body,
@@ -5,15 +5,16 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _debug = _interopRequireDefault(require("debug"));
8
- var _stub = _interopRequireDefault(require("./clients/stub"));
9
8
  var _env = _interopRequireDefault(require("../env"));
10
9
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
10
  /**
12
11
  * External dependencies
13
12
  */
13
+
14
14
  /**
15
15
  * Internal dependencies
16
16
  */
17
+
17
18
  const debug = (0, _debug.default)('@automattic/vip:analytics');
18
19
 
19
20
  /* eslint-disable camelcase */
@@ -26,23 +27,19 @@ const client_info = {
26
27
  /* eslint-enable camelcase */
27
28
 
28
29
  class Analytics {
29
- constructor({
30
- clients = new _stub.default()
31
- }) {
30
+ constructor(clients) {
32
31
  this.clients = clients;
33
32
  }
34
33
  async trackEvent(name, props = {}) {
35
34
  if (process.env.DO_NOT_TRACK) {
36
35
  debug(`trackEvent() for ${name} => skipping per DO_NOT_TRACK variable`);
37
- return Promise.resolve(`Skipping trackEvent for ${name} (DO_NOT_TRACK)`);
36
+ return [];
38
37
  }
39
- return Promise.all(this.clients.map(client => {
40
- return client.trackEvent(name, {
41
- // eslint-disable-next-line camelcase
42
- ...client_info,
43
- ...props
44
- });
45
- }));
38
+ return Promise.all(this.clients.map(client => client.trackEvent(name, {
39
+ // eslint-disable-next-line camelcase
40
+ ...client_info,
41
+ ...props
42
+ })));
46
43
  }
47
44
  }
48
45
  exports.default = Analytics;
@@ -10,20 +10,16 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
10
10
  /**
11
11
  * External dependencies
12
12
  */
13
+
13
14
  /**
14
15
  * Internal dependencies
15
16
  */
16
- async function _default(app, fields, fragments) {
17
- if (!fields) {
18
- fields = 'id,name';
19
- }
20
- if (!fragments) {
21
- fragments = '';
22
- }
17
+
18
+ async function _default(app, fields = 'id,name', fragments = '') {
23
19
  const api = await (0, _api.default)();
24
- if (isNaN(app)) {
20
+ if (isNaN(+app)) {
21
+ var _res$data$apps, _res$data$apps$edges;
25
22
  const res = await api.query({
26
- // $FlowFixMe: gql template is not supported by flow
27
23
  query: (0, _graphqlTag.default)`query App( $name: String ) {
28
24
  apps( first: 1, name: $name ) {
29
25
  total,
@@ -38,14 +34,15 @@ async function _default(app, fields, fragments) {
38
34
  name: app
39
35
  }
40
36
  });
41
- if (!res || !res.data || !res.data.apps || !res.data.apps.edges || !res.data.apps.edges.length) {
37
+ if (!((_res$data$apps = res.data.apps) !== null && _res$data$apps !== void 0 && (_res$data$apps$edges = _res$data$apps.edges) !== null && _res$data$apps$edges !== void 0 && _res$data$apps$edges.length)) {
42
38
  return {};
43
39
  }
44
40
  return res.data.apps.edges[0];
45
41
  }
46
- app = parseInt(app, 10);
42
+ if (typeof app === 'string') {
43
+ app = parseInt(app, 10);
44
+ }
47
45
  const res = await api.query({
48
- // $FlowFixMe: gql template is not supported by flow
49
46
  query: (0, _graphqlTag.default)`query App( $id: Int ) {
50
47
  app( id: $id ){
51
48
  ${fields}
@@ -56,7 +53,7 @@ async function _default(app, fields, fragments) {
56
53
  id: app
57
54
  }
58
55
  });
59
- if (!res || !res.data || !res.data.app) {
56
+ if (!res.data.app) {
60
57
  return {};
61
58
  }
62
59
  return res.data.app;
@@ -8,10 +8,7 @@ exports.purgeCache = purgeCache;
8
8
  var _graphqlTag = _interopRequireDefault(require("graphql-tag"));
9
9
  var _api = _interopRequireDefault(require("../../lib/api"));
10
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
- /**
12
- *
13
- * @format
14
- */
11
+ // @format
15
12
 
16
13
  /**
17
14
  * External dependencies
@@ -54,6 +51,7 @@ const appQuery = `
54
51
  `;
55
52
  exports.appQuery = appQuery;
56
53
  async function purgeCache(appId, envId, urls) {
54
+ var _response$data$purgeP, _response$data;
57
55
  const api = await (0, _api.default)();
58
56
  const variables = {
59
57
  appId,
@@ -64,10 +62,5 @@ async function purgeCache(appId, envId, urls) {
64
62
  mutation,
65
63
  variables
66
64
  });
67
- const {
68
- data: {
69
- purgePageCache
70
- }
71
- } = response;
72
- return purgePageCache;
65
+ return (_response$data$purgeP = (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.purgePageCache) !== null && _response$data$purgeP !== void 0 ? _response$data$purgeP : null;
73
66
  }
@@ -10,10 +10,13 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
10
10
  /**
11
11
  * External dependencies
12
12
  */
13
+
13
14
  /**
14
15
  * Internal dependencies
15
16
  */
17
+
16
18
  let api;
19
+
17
20
  // If Token.get() fails, we may have an unhandled rejection
18
21
  void (0, _api.default)().then(client => {
19
22
  api = client;
@@ -26,9 +29,8 @@ const isVipQuery = (0, _graphqlTag.default)`
26
29
  }
27
30
  `;
28
31
  async function get() {
29
- const res = await api.query({
32
+ return await api.query({
30
33
  query: isVipQuery,
31
34
  fetchPolicy: 'cache-first'
32
35
  });
33
- return res;
34
36
  }
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _nodeFetch = _interopRequireDefault(require("node-fetch"));
8
+ var _debug = _interopRequireDefault(require("debug"));
8
9
  var _token = _interopRequireDefault(require("../../lib/token"));
9
10
  var _env = _interopRequireDefault(require("../../lib/env"));
10
11
  var _proxyAgent = require("../../lib/http/proxy-agent");
@@ -18,8 +19,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
18
19
  * Internal dependencies
19
20
  */
20
21
 
21
- const debug = require('debug')('@automattic/vip:http');
22
-
22
+ const debug = (0, _debug.default)('@automattic/vip:http');
23
23
  /**
24
24
  * Call the Public API with an arbitrary path (e.g. to connect to REST endpoints).
25
25
  * This will include the token in an Authorization header so requests are "logged-in."
@@ -31,6 +31,7 @@ const debug = require('debug')('@automattic/vip:http');
31
31
  * @return {Promise} Return value of the `fetch` call
32
32
  */
33
33
  var _default = async (path, options = {}) => {
34
+ var _options$headers;
34
35
  let url = path;
35
36
 
36
37
  // For convenience, we support just passing in the path to this function...
@@ -39,27 +40,18 @@ var _default = async (path, options = {}) => {
39
40
  url = `${_api.API_HOST}${path}`;
40
41
  }
41
42
  const authToken = await _token.default.get();
42
- const headers = {
43
- 'User-Agent': _env.default.userAgent,
44
- Authorization: authToken ? `Bearer ${authToken.raw}` : null
45
- };
46
43
  const proxyAgent = (0, _proxyAgent.createProxyAgent)(url);
47
44
  debug('running fetch', url);
48
45
  return (0, _nodeFetch.default)(url, {
49
46
  ...options,
50
- ...{
51
- agent: proxyAgent,
52
- headers: {
53
- ...headers,
54
- ...{
55
- 'Content-Type': 'application/json'
56
- },
57
- ...options.headers
58
- }
47
+ agent: proxyAgent !== null && proxyAgent !== void 0 ? proxyAgent : undefined,
48
+ headers: {
49
+ Authorization: `Bearer ${authToken.raw}`,
50
+ 'User-Agent': _env.default.userAgent,
51
+ 'Content-Type': 'application/json',
52
+ ...((_options$headers = options.headers) !== null && _options$headers !== void 0 ? _options$headers : {})
59
53
  },
60
- ...{
61
- body: typeof options.body === 'object' ? JSON.stringify(options.body) : options.body
62
- }
54
+ body: typeof options.body === 'object' ? JSON.stringify(options.body) : options.body
63
55
  });
64
56
  };
65
57
  exports.default = _default;
@@ -7,10 +7,7 @@ exports.getCurrentUserInfo = getCurrentUserInfo;
7
7
  var _graphqlTag = _interopRequireDefault(require("graphql-tag"));
8
8
  var _api = _interopRequireDefault(require("../../lib/api"));
9
9
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
- /**
11
- *
12
- * @format
13
- */
10
+ // @format
14
11
 
15
12
  /**
16
13
  * External dependencies
@@ -41,10 +38,8 @@ async function getCurrentUserInfo() {
41
38
  query: QUERY_CURRENT_USER
42
39
  });
43
40
  const {
44
- data: {
45
- me
46
- }
47
- } = response;
41
+ me
42
+ } = response.data;
48
43
  if (!me) {
49
44
  throw new Error('The API did not return any information about the user.');
50
45
  }