@vkontakte/vk-miniapps-deploy 0.1.8 → 0.1.9-rc.1

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/.eslintrc.js ADDED
@@ -0,0 +1,14 @@
1
+ module.exports = {
2
+ extends: ['plugin:@vkontakte/eslint-plugin/default', 'prettier'],
3
+ parserOptions: {
4
+ requireConfigFile: false,
5
+ },
6
+ rules: {
7
+ 'import/no-duplicates': 'off',
8
+ 'no-undef': 'off',
9
+ 'no-shadow': 'off',
10
+ 'no-var': 'off',
11
+ 'camelcase': 'off',
12
+ 'valid-jsdoc': 'off',
13
+ },
14
+ };
@@ -1,2 +1,2 @@
1
1
  * @VKCOM/vk-miniapp
2
- .github @VKCOM/vk-sec
2
+ .github/ @VKCOM/vk-sec
@@ -13,7 +13,7 @@ runs:
13
13
  registry-url: 'https://registry.npmjs.org'
14
14
 
15
15
  - name: Install dependencies
16
- run: yarn install --frozen-lockfile --ignore-scripts
16
+ run: yarn install --ignore-scripts
17
17
  shell: bash
18
18
 
19
19
  - name: Set Git credentials
@@ -0,0 +1,9 @@
1
+ name: 'Validation'
2
+ description: It runs linter and prettier checks
3
+
4
+ runs:
5
+ using: composite
6
+ steps:
7
+ - name: Run linters
8
+ run: yarn lint:ci
9
+ shell: bash
@@ -33,6 +33,9 @@ jobs:
33
33
  with:
34
34
  version: ${{ github.event.inputs.new_version }}
35
35
 
36
+ - name: Validation
37
+ uses: ./.github/actions/validation
38
+
36
39
  - name: Complete publish
37
40
  uses: ./.github/actions/complete-publish
38
41
  with:
@@ -47,6 +47,9 @@ jobs:
47
47
  version: ${{ github.event.inputs.custom_version || github.event.inputs.new_version }}
48
48
  npm_tag: ${{ github.event.inputs.npm_tag }}
49
49
 
50
+ - name: Validation
51
+ uses: ./.github/actions/validation
52
+
50
53
  - name: Complete publish
51
54
  uses: ./.github/actions/complete-publish
52
55
  with:
@@ -0,0 +1,19 @@
1
+ name: 'Pull Request'
2
+
3
+ on:
4
+ pull_request:
5
+
6
+ jobs:
7
+ lint:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - name: Checkout
11
+ uses: actions/checkout@v4
12
+ with:
13
+ token: ${{ secrets.DEVTOOLS_GITHUB_TOKEN }}
14
+
15
+ - name: Setting up the repository environment
16
+ uses: ./.github/actions/setup
17
+
18
+ - name: Validation
19
+ uses: ./.github/actions/validation
@@ -0,0 +1,34 @@
1
+ name: Set Pay attention label for ignored issues
2
+ on:
3
+ schedule:
4
+ - cron: '0 10 * * 1-5'
5
+
6
+ jobs:
7
+ set-label-for-issues:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - name: Set Pay attention label for ignored issues
11
+ uses: actions/github-script@v7
12
+ with:
13
+ github-token: ${{ secrets.DEVTOOLS_GITHUB_TOKEN }}
14
+ script: |
15
+ const issuesList = await github.rest.issues.listForRepo({
16
+ owner: context.repo.owner,
17
+ repo: context.repo.repo,
18
+ })
19
+ if (issuesList.data && issuesList.status === 200) {
20
+ for (const issue of issuesList.data) {
21
+ const createdDaysDelta = (new Date() - new Date(issue.created_at)) / (1000 * 60 * 60 * 24);
22
+
23
+ if (!issue.labels.length && (
24
+ (!issue.pull_request && createdDaysDelta > 2) || (issue.pull_request && createdDaysDelta > 7)
25
+ )) {
26
+ await github.rest.issues.addLabels({
27
+ owner: context.repo.owner,
28
+ repo: context.repo.repo,
29
+ issue_number: issue.number,
30
+ labels: ['pay attention']
31
+ });
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,30 @@
1
+ # OS
2
+ .DS_Store
3
+
4
+ # IDE
5
+ .idea/
6
+ .vscode/
7
+
8
+ # Dependencices
9
+ node_modules/
10
+
11
+ # Caches
12
+ .cache
13
+ tmp/
14
+
15
+ # Logs
16
+ test-results.json
17
+ lint-results.json
18
+ yarn-error.log
19
+
20
+ # Caches
21
+ .cache
22
+
23
+ # Coverage directories used by tools like istanbul
24
+ coverage
25
+ .nyc_output
26
+
27
+ # GitHub
28
+ .github/*
29
+
30
+ /bin
package/.prettierrc.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('@vkontakte/prettier-config').createConfig();
@@ -0,0 +1,48 @@
1
+ ## Установка
2
+
3
+ 1. Склонировать репозиторий и перейти в созданную директорию.
4
+ 2. Установить зависимости:
5
+ ```sh
6
+ yarn install
7
+ ```
8
+
9
+ ## Запуск и тестирование изменений
10
+
11
+ vk-miniapps-deploy является вспомогательной утилитой, поэтому изменения функционала этой библиотеки следует проверять в связке с вашими мини-приложениями. Для локальной проверки ваших изменений мы предлагаем механизм линковки пакетов через symlink.
12
+
13
+ 1. В корне данного проекта выполните команду:
14
+ ```sh
15
+ yarn link
16
+ ```
17
+ 2. В корне приложения, использующего vk-miniapps-deploy выполните команду:
18
+ ```sh
19
+ yarn link "@vkontakte/vk-miniapps-deploy"
20
+ ```
21
+
22
+ ## Проверка кода
23
+
24
+ Любые изменения в репозитории, должны проходить проверку линтерами. Для этого выполните команду:
25
+ ```sh
26
+ yarn lint:ci
27
+ ```
28
+
29
+ ## Создание pull request
30
+
31
+ - Создайте и перейдите в отдельную ветку. Название ветки должно начинаться с указания типа изменения feat для нового функционала или fix для исправления бага и краткой информации о ваших изменениях, например:
32
+ ```sh
33
+ git checkout -b fix/fix_token_restrictions
34
+ ```
35
+ - Добавьте файлы, которые хотите зафиксировать:
36
+ ```sh
37
+ git add <file_name>
38
+ ```
39
+ - Commit message должен начинаться с указания типа изменения feat для нового функционала или fix для исправления бага, а так же содержать описание изменения, которое вы вносите.
40
+ ```sh
41
+ git commit -m "[feat/fix]: commit message"
42
+ ```
43
+ - Выполните пуш ваших изменений в новую ветку:
44
+ ```sh
45
+ git push
46
+ ```
47
+ - Перейдите в раздел [Pull requests](https://github.com/VKCOM/vk-miniapps-deploy/pulls) и создайте новый pull request, используя наш шаблон.
48
+
package/index.js CHANGED
@@ -11,8 +11,8 @@ const vault = new Configstore(packageJson.name, {});
11
11
 
12
12
  var configJSON = require('require-module')('./vk-hosting-config.json');
13
13
  var cfg = configJSON || {};
14
- prompt.message = "vk-mini-apps-deploy".grey;
15
- prompt.delimiter = "=>".grey;
14
+ prompt.message = 'vk-mini-apps-deploy'.grey;
15
+ prompt.delimiter = '=>'.grey;
16
16
 
17
17
  const DEBUG_MODE = !!cfg.debug;
18
18
 
@@ -40,14 +40,14 @@ const ERROR_TEST_GROUP_UPDATE = 109;
40
40
  const TYPE_SUCCESS = 'success';
41
41
 
42
42
  const URL_NAMES = {
43
- DESKTOP_DEV : 'vk_app_desktop_dev_url',
43
+ DESKTOP_DEV: 'vk_app_desktop_dev_url',
44
44
  MOBILE_DEV: 'vk_app_dev_url',
45
45
  MOBILE_WEB_DEV: 'vk_mini_app_mvk_dev_url',
46
46
  WEB_LEGACY: 'iframe_url',
47
47
  WEB: 'iframe_secure_url',
48
48
  MOBILE: 'm_iframe_secure_url',
49
49
  MOBILE_WEB: 'vk_mini_app_mvk_url',
50
- }
50
+ };
51
51
 
52
52
  const PLATFORMS = {
53
53
  WEB: 'vk.com',
@@ -66,11 +66,11 @@ const URL_NAMES_MAP = {
66
66
  };
67
67
 
68
68
  function getTraceId() {
69
- return crypto.randomBytes(4).toString("hex");
69
+ return crypto.randomBytes(4).toString('hex');
70
70
  }
71
71
 
72
72
  /**
73
- * @param {nodeFetch.RequestInfo} url
73
+ * @param {nodeFetch.RequestInfo} url
74
74
  * @param {nodeFetch.RequestInit} options
75
75
  * @returns {Promise<nodeFetch.Response>}
76
76
  */
@@ -79,7 +79,7 @@ async function fetch(url, options) {
79
79
  return nodeFetch(url, options);
80
80
  }
81
81
 
82
- const traceId = chalk.hex(`#${(Math.random() * 0xFFFFFF << 0).toString(16)}`)(getTraceId());
82
+ const traceId = chalk.hex(`#${((Math.random() * 0xffffff) << 0).toString(16)}`)(getTraceId());
83
83
  const logLine = (line, type) => console.log(`[${traceId}][${type}]`, chalk.cyan(line));
84
84
  const logError = (error) => console.error(`[${traceId}][ERROR]`, chalk.red(error));
85
85
 
@@ -93,7 +93,7 @@ async function fetch(url, options) {
93
93
  logLine(`${response.status} ${response.statusText}`, 'RESP');
94
94
  logLine(body, 'RESP');
95
95
 
96
- return response
96
+ return response;
97
97
  } catch (e) {
98
98
  logError(e);
99
99
  throw e;
@@ -119,7 +119,7 @@ async function auth(app_id) {
119
119
  }
120
120
 
121
121
  if (get_auth_code_res.auth_code) {
122
- const {auth_code, device_id} = get_auth_code_res;
122
+ const { auth_code, device_id } = get_auth_code_res;
123
123
 
124
124
  const code_auth_url = `${OAUTH_HOST}code_auth?stage=check&code=${auth_code}&revoke=1`;
125
125
 
@@ -129,11 +129,11 @@ async function auth(app_id) {
129
129
  type: 'confirm',
130
130
  name: 'result',
131
131
  initial: true,
132
- message: chalk.yellow('Please open this url in browser', code_auth_url)
132
+ message: chalk.yellow('Please open this url in browser', code_auth_url),
133
133
  });
134
134
 
135
135
  if (!prompt_question.result) {
136
- return Promise.reject("empty response " + prompt_question.result);
136
+ return Promise.reject('empty response ' + prompt_question.result);
137
137
  }
138
138
 
139
139
  const code_auth_token_url = `${OAUTH_HOST}code_auth_token?device_id=${device_id}&client_id=${DEPLOY_APP_ID}&mini_app_id=${app_id}`;
@@ -145,7 +145,7 @@ async function auth(app_id) {
145
145
  continue;
146
146
  }
147
147
 
148
- const {access_token, expires_in} = code_auth_token_json;
148
+ const { access_token, expires_in } = code_auth_token_json;
149
149
  if (access_token || access_token === null) {
150
150
  handled = true;
151
151
  }
@@ -153,7 +153,6 @@ async function auth(app_id) {
153
153
  access_token,
154
154
  expires_in,
155
155
  });
156
-
157
156
  } while (handled === false);
158
157
  }
159
158
  }
@@ -168,12 +167,39 @@ async function api(method, params) {
168
167
  return false;
169
168
  }
170
169
 
171
- const queryParams = Object.keys(params).map((k) => { return k + "=" + encodeURIComponent(params[k]) }).join('&');
170
+ const queryParams = Object.keys(params)
171
+ .map((k) => {
172
+ return k + '=' + encodeURIComponent(params[k]);
173
+ })
174
+ .join('&');
172
175
  try {
173
176
  const query = await fetch(API_HOST + method + '?' + queryParams);
174
177
  const res = await query.json();
175
178
  if (res.error !== void 0) {
176
- throw new Error(chalk.red(res.error.error_code + ': ' + res.error.error_msg));
179
+ const errorCode = res.error.error_code;
180
+ const errorMessage = chalk.red(errorCode + ': ' + res.error.error_msg);
181
+ if (errorCode === 5 && !process.env.MINI_APPS_ACCESS_TOKEN && !cfg.noprompt) {
182
+ console.error(errorMessage);
183
+
184
+ const questions = [
185
+ {
186
+ type: 'confirm',
187
+ initial: true,
188
+ name: 'updateToken',
189
+ message: chalk.yellow('Would you like to try to retrieve a new token?'),
190
+ },
191
+ ];
192
+
193
+ const { updateToken } = await prompt(questions);
194
+ if (updateToken) {
195
+ await retrieveAndSaveAccessToken(cfg);
196
+ return api(method, params);
197
+ } else {
198
+ throw new Error(errorMessage);
199
+ }
200
+ } else {
201
+ throw new Error(errorMessage);
202
+ }
177
203
  }
178
204
 
179
205
  if (res.response !== void 0) {
@@ -186,12 +212,12 @@ async function api(method, params) {
186
212
 
187
213
  async function upload(uploadUrl, bundleFile) {
188
214
  const formData = new FormData();
189
- formData.append('file', fs.createReadStream(bundleFile), {contentType: 'application/zip'});
215
+ formData.append('file', fs.createReadStream(bundleFile), { contentType: 'application/zip' });
190
216
  try {
191
217
  const upload = await fetch(uploadUrl, {
192
218
  method: 'POST',
193
219
  headers: formData.getHeaders(),
194
- body: formData
220
+ body: formData,
195
221
  });
196
222
  return await upload.json();
197
223
  } catch (e) {
@@ -243,14 +269,14 @@ async function handleQueue(user_id, base_url, key, ts, version, handled, cfg) {
243
269
  const result = await prompt({
244
270
  type: 'text',
245
271
  name: 'code',
246
- message: chalk.yellow('Please, enter code from Administration: ')
272
+ message: chalk.yellow('Please, enter code from Administration: '),
247
273
  });
248
274
 
249
275
  if (result.code) {
250
276
  const r = await api('apps.confirmDeploy', {
251
277
  app_id: cfg.app_id,
252
278
  version: version,
253
- code: result.code
279
+ code: result.code,
254
280
  });
255
281
  if (r.error) {
256
282
  console.error('Invalid confirm code');
@@ -322,7 +348,7 @@ async function handleQueue(user_id, base_url, key, ts, version, handled, cfg) {
322
348
  if (event.code === CODE_UPDATE_TEST_GROUP_URL) {
323
349
  if (event.message && event.message.url) {
324
350
  console.info(chalk.green('URL changed for test group "' + cfg.test_group_name + '":'));
325
- console.info(event.message.url)
351
+ console.info(event.message.url);
326
352
  }
327
353
  }
328
354
  }
@@ -333,7 +359,7 @@ async function handleQueue(user_id, base_url, key, ts, version, handled, cfg) {
333
359
  }
334
360
 
335
361
  async function getQueue(version, cfg) {
336
- const r = await api('apps.subscribeToHostingQueue', {app_id: cfg.app_id, version: version});
362
+ const r = await api('apps.subscribeToHostingQueue', { app_id: cfg.app_id, version: version });
337
363
  if (!r.base_url || !r.key || !r.ts || !r.app_id) {
338
364
  throw new Error(JSON.stringify(r));
339
365
  }
@@ -341,8 +367,23 @@ async function getQueue(version, cfg) {
341
367
  return handleQueue(r.app_id, r.base_url, r.key, r.ts, version, false, cfg);
342
368
  }
343
369
 
344
- async function run(cfg) {
370
+ async function retrieveAndSaveAccessToken(cfg) {
371
+ console.log('Try to retrieve access token...');
372
+ const { access_token, expires_in } = await auth(cfg.app_id);
373
+ cfg.access_token = access_token;
374
+ vault.set('access_token', access_token);
375
+ vault.set('expires_in', expires_in);
376
+ console.log(chalk.cyan('Token is saved in config store!'));
377
+ console.log(
378
+ chalk.cyan(
379
+ '\nFor your CI, you can use \n > $ env MINI_APPS_ACCESS_TOKEN=' +
380
+ access_token +
381
+ ' yarn deploy',
382
+ ),
383
+ );
384
+ }
345
385
 
386
+ async function run(cfg) {
346
387
  if (!configJSON) {
347
388
  throw new Error('For deploy you need to create config file "vk-hosting-config.json"');
348
389
  }
@@ -352,11 +393,11 @@ async function run(cfg) {
352
393
  const defaultEnvironment = APPLICATION_ENV_DEV | APPLICATION_ENV_PRODUCTION;
353
394
  const environmentMapping = {
354
395
  dev: APPLICATION_ENV_DEV,
355
- production: APPLICATION_ENV_PRODUCTION
396
+ production: APPLICATION_ENV_PRODUCTION,
356
397
  };
357
398
 
358
399
  const environment = process.env.MINI_APPS_ENVIRONMENT
359
- ? (environmentMapping[process.env.MINI_APPS_ENVIRONMENT] || defaultEnvironment)
400
+ ? environmentMapping[process.env.MINI_APPS_ENVIRONMENT] || defaultEnvironment
360
401
  : defaultEnvironment;
361
402
 
362
403
  if (process.env.MINI_APPS_APP_ID) {
@@ -381,24 +422,18 @@ async function run(cfg) {
381
422
  }
382
423
 
383
424
  if (!cfg.access_token || (cfg.expires_in > 0 && cfg.expires_in * 1000 < Date.now())) {
384
- console.log('Try to retrieve access token...');
385
- const { access_token, expires_in } = await auth(cfg.app_id);
386
- cfg.access_token = access_token;
387
- vault.set('access_token', access_token);
388
- vault.set('expires_in', expires_in);
389
- console.log(chalk.cyan('Token is saved in config store!'));
390
- console.log(chalk.cyan('\nFor your CI, you can use \n > $ env MINI_APPS_ACCESS_TOKEN=' + access_token + ' yarn deploy'));
425
+ await retrieveAndSaveAccessToken(cfg);
391
426
  }
392
427
 
393
428
  const params = {
394
429
  app_id: cfg.app_id,
395
430
  environment: environment,
396
- update_prod: + cfg.update_prod,
397
- update_dev: + cfg.update_dev
431
+ update_prod: +cfg.update_prod,
432
+ update_dev: +cfg.update_dev,
398
433
  };
399
434
 
400
435
  if ('test_group_name' in cfg) {
401
- params.test_group_name = cfg.test_group_name
436
+ params.test_group_name = cfg.test_group_name;
402
437
  }
403
438
 
404
439
  const endpointPlatformKeys = Object.keys(cfg.endpoints);
@@ -425,10 +460,9 @@ async function run(cfg) {
425
460
 
426
461
  if (!cfg.bundleFile) {
427
462
  if (await fs.pathExists(bundleFile)) {
428
- fs.removeSync(bundleFile)
463
+ fs.removeSync(bundleFile);
429
464
  }
430
465
 
431
-
432
466
  await zip('./' + staticPath, bundleFile);
433
467
  }
434
468
 
@@ -442,11 +476,10 @@ async function run(cfg) {
442
476
  console.log('Uploaded version ' + r.version + '!');
443
477
  return getQueue(r.version, cfg);
444
478
  } else {
445
- console.error('Upload error:', r)
479
+ console.error('Upload error:', r);
446
480
  process.exit(1);
447
481
  }
448
482
  });
449
-
450
483
  } catch (e) {
451
484
  console.error(chalk.red(e));
452
485
  process.exit(1);
@@ -454,5 +487,5 @@ async function run(cfg) {
454
487
  }
455
488
 
456
489
  module.exports = {
457
- run: run
490
+ run: run,
458
491
  };
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@vkontakte/vk-miniapps-deploy",
3
- "version": "0.1.8",
3
+ "version": "0.1.9-rc.1",
4
4
  "description": "Deploy to VK Mini Apps hosting with one simple command",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "test": "echo \"Error: no test specified\" && exit 1",
8
- "deploy": "./bin/vk-miniapps-deploy"
8
+ "deploy": "./bin/vk-miniapps-deploy",
9
+ "lint:eslint": "eslint ./index.js",
10
+ "lint:prettier": "prettier --check ./index.js",
11
+ "lint:fix": "eslint ./index.js --fix",
12
+ "lint:ci": "yarn lint:eslint && yarn lint:prettier"
9
13
  },
10
14
  "license": "MIT",
11
15
  "engines": {
@@ -42,5 +46,12 @@
42
46
  "prompts": "^2.1.0",
43
47
  "require-module": "^0.1.0",
44
48
  "zip-a-folder": "0.0.12"
49
+ },
50
+ "devDependencies": {
51
+ "@vkontakte/eslint-plugin": "^2.0.0",
52
+ "@vkontakte/prettier-config": "^0.1.0",
53
+ "eslint": "^8.0.0",
54
+ "eslint-config-prettier": "^9.1.0",
55
+ "prettier": "^2.7.1"
45
56
  }
46
57
  }