diff --git a/.github/.dependabot.yml b/.github/.dependabot.yml new file mode 100644 index 00000000..88cb6099 --- /dev/null +++ b/.github/.dependabot.yml @@ -0,0 +1,13 @@ +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + allow: + - dependency-name: "@storyblok/region-helper" + reviewers: + - "storyblok/plugins-team" \ No newline at end of file diff --git a/README.md b/README.md index a79bec83..5ef42a6c 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,10 @@ $ storyblok login **For Both login options you nedd to pass the region** -* `region`: region you would like to work in. Please keep in mind that the region must match the region of your space. You can use `us`, `cn`, `eu`, `ca` and `ap`, if left empty, default is `eu`. This region flag will be used for the other cli's commands. +* `region` (default: `eu`): the region you would like to work in. All the supported regions can be found [here](https://www.storyblok.com/faq/define-specific-region-storyblok-api). + +> [!NOTE] +> Please keep in mind that the region must match the region of your space, and also that it will be used for all future commands you may perform. #### Login with token flag You can also add the token directly from the login’s command, like the example below: diff --git a/__mocks__/axios.js b/__mocks__/axios.js index f9e68297..2b2a0140 100644 --- a/__mocks__/axios.js +++ b/__mocks__/axios.js @@ -1,5 +1,4 @@ -const { USERS_ROUTES } = require('../src/constants') -const { EMAIL_TEST, PASSWORD_TEST, TOKEN_TEST } = require('../tests/constants') +const { USERS_ROUTES, EMAIL_TEST, PASSWORD_TEST, TOKEN_TEST } = require('../tests/constants') const isCredCorrects = (email, pass) => { return email === EMAIL_TEST && pass === PASSWORD_TEST diff --git a/package.json b/package.json index ec4c77ea..06e7b0da 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "author": "Dominik Angerer , Alexander Feiglstorfer ", "license": "MIT", "dependencies": { + "@storyblok/region-helper": "^1.0.0", "axios": "^0.27.2", "chalk": "^4.1.0", "clear": "0.1.0", diff --git a/src/cli.js b/src/cli.js index dafbb9f4..0a64f77b 100755 --- a/src/cli.js +++ b/src/cli.js @@ -7,6 +7,7 @@ const chalk = require('chalk') const clear = require('clear') const figlet = require('figlet') const inquirer = require('inquirer') +const { ALL_REGIONS, EU_CODE, isRegion } = require('@storyblok/region-helper') const updateNotifier = require('update-notifier') const pkg = require('../package.json') @@ -14,6 +15,7 @@ const pkg = require('../package.json') const tasks = require('./tasks') const { getQuestions, lastStep, api, creds } = require('./utils') const { SYNC_TYPES, COMMANDS } = require('./constants') +const allRegionsText = ALL_REGIONS.join(', ') clear() console.log(chalk.cyan(figlet.textSync('storyblok'))) @@ -39,8 +41,8 @@ program program .command(COMMANDS.LOGIN) .description('Login to the Storyblok cli') - .option('-t, --token ', 'Token to login directly without questions, like for CI enviroments') - .option('-r, --region ', 'The region you would like to work in. Please keep in mind that the region must match the region of your space. You can use us, cn or eu, if left empty, default is eu. This region flag will be used for the other cli\'s commands') + .option('-t, --token ', 'Token to login directly without questions, like for CI environments') + .option('-r, --region ', `The region you would like to work in. Please keep in mind that the region must match the region of your space. This region flag will be used for the other cli's commands. You can use the values: ${allRegionsText}.`, EU_CODE) .action(async (options) => { const { token, region } = options @@ -49,6 +51,11 @@ program return } + if (!isRegion(region)) { + console.log(chalk.red('X') + `The provided region ${region} is not valid. Please use one of the following: ${allRegionsText}`) + return + } + try { await api.processLogin(token, region) process.exit(0) @@ -524,7 +531,8 @@ if (program.rawArgs.length <= 2) { function errorHandler (e, command) { if (/404/.test(e.message)) { - console.log(chalk.yellow('/!\\') + ' If your space was created under US, CA, AP or CN region, you must provide the region us, ca, ap or cn upon login.') + const allRegionsButDefault = ALL_REGIONS.filter(region => region !== EU_CODE).join(' ,') + console.log(chalk.yellow('/!\\') + ` If your space was not created under ${EU_CODE} region, you must provide the region (${allRegionsButDefault}) upon login.`) } else { console.log(chalk.red('X') + ' An error occurred when executing the ' + command + ' task: ' + e || e.message) } diff --git a/src/constants.js b/src/constants.js index 720b119f..e73742bc 100644 --- a/src/constants.js +++ b/src/constants.js @@ -1,10 +1,4 @@ -const SYNC_TYPES = [ - 'folders', - 'components', - 'roles', - 'stories', - 'datasources' -] +const SYNC_TYPES = ['folders', 'components', 'roles', 'stories', 'datasources'] const COMMANDS = { GENERATE_MIGRATION: 'generate-migration', @@ -28,43 +22,8 @@ const DEFAULT_AGENT = { SB_Agent_Version: process.env.npm_package_version || '3.0.0' } -const REGIONS = { - cn: { - key: 'cn', - name: 'China', - apiEndpoint: 'https://app.storyblokchina.cn/v1/' - }, - eu: { - key: 'eu', - name: 'Europe', - apiEndpoint: 'https://api.storyblok.com/v1/' - }, - us: { - key: 'us', - name: 'United States', - apiEndpoint: 'https://api-us.storyblok.com/v1/' - }, - ca: { - key: 'ca', - name: 'Canada', - apiEndpoint: 'https://api-ca.storyblok.com/v1/' - }, - ap: { - key: 'ap', - name: 'Australia', - apiEndpoint: 'https://api-ap.storyblok.com/v1/' - } -} - -const USERS_ROUTES = { - LOGIN: `${REGIONS.eu.apiEndpoint}users/login`, - SIGNUP: `${REGIONS.eu.apiEndpoint}users/signup` -} - module.exports = { SYNC_TYPES, - USERS_ROUTES, COMMANDS, - DEFAULT_AGENT, - REGIONS + DEFAULT_AGENT } diff --git a/src/tasks/delete-datasources.js b/src/tasks/delete-datasources.js index 2dd0ac8b..4ff7c023 100644 --- a/src/tasks/delete-datasources.js +++ b/src/tasks/delete-datasources.js @@ -13,26 +13,25 @@ const deleteDatasources = async (api, options) => { let datasources = await api.getDatasources() if (bySlug) { - datasources = datasources.filter(datasource => datasource.slug.toLowerCase().startsWith(bySlug.toLowerCase())); - const filteredSlugs = datasources.map(obj => obj.slug); - const formattedSlugs = filteredSlugs.join(', '); + datasources = datasources.filter(datasource => datasource.slug.toLowerCase().startsWith(bySlug.toLowerCase())) + const filteredSlugs = datasources.map(obj => obj.slug) + const formattedSlugs = filteredSlugs.join(', ') - console.log(`${chalk.blue('-')} Datasources where slug starts with ${bySlug}: ${formattedSlugs}`); + console.log(`${chalk.blue('-')} Datasources where slug starts with ${bySlug}: ${formattedSlugs}`) } if (byName) { - datasources = datasources.filter(datasource => datasource.name.toLowerCase().startsWith(byName.toLowerCase())); - const filteredNames = datasources.map(obj => obj.name); - const formattedNames = filteredNames.join(', '); + datasources = datasources.filter(datasource => datasource.name.toLowerCase().startsWith(byName.toLowerCase())) + const filteredNames = datasources.map(obj => obj.name) + const formattedNames = filteredNames.join(', ') - console.log(`${chalk.blue('-')} Datasources where name starts with ${byName}: ${formattedNames}`); + console.log(`${chalk.blue('-')} Datasources where name starts with ${byName}: ${formattedNames}`) } for (const datasource of datasources) { console.log(`${chalk.blue('-')} Deleting ${datasource.name}`) await api.deleteDatasource(datasource.id) } - } catch (e) { console.error(`${chalk.red('X')} An error ocurred in delete-components task when deleting a datasource`) return Promise.reject(new Error(e)) diff --git a/src/tasks/list-spaces.js b/src/tasks/list-spaces.js index 74a4527d..e76a0539 100644 --- a/src/tasks/list-spaces.js +++ b/src/tasks/list-spaces.js @@ -1,5 +1,5 @@ const chalk = require('chalk') -const { REGIONS } = require('../constants') +const { ALL_REGIONS, getRegionName, CN_CODE } = require('@storyblok/region-helper') /** * @method listSpaces * @param api - Pass the api instance as a parameter @@ -7,7 +7,7 @@ const { REGIONS } = require('../constants') */ const listSpaces = async (api, currentRegion) => { - const isChinaEnv = currentRegion === 'cn' + const isChinaEnv = currentRegion === CN_CODE console.log() console.log(chalk.green('✓') + ' Loading spaces...') @@ -34,8 +34,8 @@ const listSpaces = async (api, currentRegion) => { return spaces } else { const spacesList = [] - for (const key in REGIONS) { - if (key === 'cn') continue + for (const key of ALL_REGIONS) { + if (key === CN_CODE) continue spacesList.push(await api.getAllSpacesByRegion(key) .then((res) => { return { @@ -50,9 +50,8 @@ const listSpaces = async (api, currentRegion) => { return [] } spacesList.forEach(region => { - const regionName = REGIONS[region.key].name console.log() - console.log(`${chalk.blue(' -')} Spaces From ${regionName} region:`) + console.log(`${chalk.blue(' -')} Spaces From ${getRegionName(region.key)} region:`) region.res.forEach((space) => { console.log(` ${space.name} (id: ${space.id})`) }) diff --git a/src/tasks/sync-commands/components.js b/src/tasks/sync-commands/components.js index 7bd0f0e3..34f77580 100644 --- a/src/tasks/sync-commands/components.js +++ b/src/tasks/sync-commands/components.js @@ -73,10 +73,10 @@ class SyncComponents { if (this.componentsGroups && !this.componentsGroups.includes(sourceGroupUuid)) { console.log( - chalk.yellow("-") + + chalk.yellow('-') + ` Component ${component.name} does not belong to the ${this.componentsGroups} group(s).` - ); - continue; + ) + continue } // if the component belongs to a group @@ -112,7 +112,7 @@ class SyncComponents { await this.presetsLib.createPresets(componentPresets, componentCreated.id) } } catch (e) { - if (e.response && e.response.status || e.status === 422) { + if ((e.response && e.response.status) || e.status === 422) { console.log( `${chalk.yellow('-')} Component ${component.name} already exists, updating it...` ) @@ -217,7 +217,10 @@ class SyncComponents { return Object.keys(sourceSchema).reduce((acc, key) => { // handle blocks separately const sourceSchemaItem = sourceSchema[key] - if (sourceSchemaItem?.type === 'bloks' || sourceSchemaItem?.type === 'richtext') { + const isBloksType = sourceSchemaItem && sourceSchemaItem.type === 'bloks' + const isRichtextType = sourceSchemaItem && sourceSchemaItem.type === 'richtext' + + if (isBloksType || isRichtextType) { acc[key] = this.mergeBloksSchema(sourceSchemaItem) return acc } diff --git a/src/utils/api.js b/src/utils/api.js index acf67a22..c9625cfb 100644 --- a/src/utils/api.js +++ b/src/utils/api.js @@ -5,7 +5,9 @@ const inquirer = require('inquirer') const creds = require('./creds') const getQuestions = require('./get-questions') -const { REGIONS, USERS_ROUTES, DEFAULT_AGENT } = require('../constants') +const { DEFAULT_AGENT } = require('../constants') +const { getRegionApiEndpoint } = require('./region') +const { EU_CODE } = require('@storyblok/region-helper') module.exports = { accessToken: '', @@ -39,7 +41,7 @@ module.exports = { }, async login (content) { - const { email, password, region = 'eu' } = content + const { email, password, region = EU_CODE } = content try { const response = await axios.post(`${this.apiSwitcher(region)}users/login`, { email: email, @@ -96,7 +98,7 @@ module.exports = { } }, - persistCredentials (email, token = null, region = 'eu') { + persistCredentials (email, token = null, region = EU_CODE) { if (token) { this.oauthToken = token creds.set(email, token, region) @@ -168,8 +170,8 @@ module.exports = { creds.set(null) }, - signup (email, password, region = 'eu') { - return axios.post(USERS_ROUTES.SIGNUP, { + signup (email, password, region = EU_CODE) { + return axios.post(`${this.apiSwitcher(region)}users/signup`, { email: email, password: password, region @@ -255,7 +257,6 @@ module.exports = { .catch(err => Promise.reject(err)) }, - post (path, props) { return this.sendRequest(path, 'post', props) }, @@ -310,6 +311,6 @@ module.exports = { }, apiSwitcher (region) { - return region ? REGIONS[region].apiEndpoint : REGIONS[this.region].apiEndpoint + return region ? getRegionApiEndpoint(region) : getRegionApiEndpoint(this.region) } } diff --git a/src/utils/get-questions.js b/src/utils/get-questions.js index 594973c5..6c32ff73 100644 --- a/src/utils/get-questions.js +++ b/src/utils/get-questions.js @@ -1,4 +1,5 @@ -const { REGIONS } = require('../constants') +const { ALL_REGIONS, EU_CODE } = require('@storyblok/region-helper') + const getOptions = (subCommand, argv = {}, api = {}) => { let email = '' const moreOptions = [ @@ -7,17 +8,17 @@ const getOptions = (subCommand, argv = {}, api = {}) => { 'push-components', 'scaffold' ] - const regionsPrefixList = Object.keys(REGIONS) const regionInput = { type: 'input', name: 'region', - message: `Please enter the region you would like to work in (${regionsPrefixList}) - if not set, default is eu:`, + message: `Please enter the region you would like to work in (${ALL_REGIONS}):`, + default: EU_CODE, validate: function (value) { - if (regionsPrefixList.indexOf(value) > -1) { + if (ALL_REGIONS.indexOf(value) > -1) { return true } - return `Please enter a valid region: ${regionsPrefixList}` + return `Please enter a valid region: ${ALL_REGIONS}` } } diff --git a/src/utils/index.js b/src/utils/index.js index e92d0c41..ba24f0f5 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -6,5 +6,6 @@ module.exports = { capitalize: require('./capitalize'), findByProperty: require('./find-by-property'), parseError: require('./parse-error'), + region: require('./region'), saveFileFactory: require('./save-file-factory') } diff --git a/src/utils/last-step.js b/src/utils/last-step.js index 6fb6500e..afc92b61 100644 --- a/src/utils/last-step.js +++ b/src/utils/last-step.js @@ -49,7 +49,7 @@ const lastStep = answers => { console.log(chalk.green('✓') + ' - The github repository ' + gitRepo + ' will be cloned now...') ghdownload(gitRepo, outputDir, async (err) => { - if(err) { + if (err) { if (err.code === 'ENOTEMPTY') { console.log(chalk.red(' Oh Snap! It seems that you already have a project with the name: ' + name)) reject(new Error('This repository already has been cloned')) diff --git a/src/utils/region.js b/src/utils/region.js new file mode 100644 index 00000000..3a185217 --- /dev/null +++ b/src/utils/region.js @@ -0,0 +1,7 @@ +const { getRegionBaseUrl } = require('@storyblok/region-helper') + +const getRegionApiEndpoint = (region) => `${getRegionBaseUrl(region)}/v1/` + +module.exports = { + getRegionApiEndpoint +} diff --git a/tests/constants.js b/tests/constants.js index a85388fe..c93d018e 100644 --- a/tests/constants.js +++ b/tests/constants.js @@ -1,7 +1,9 @@ +const { getRegionApiEndpoint } = require('../src/utils/region') +const { EU_CODE } = require('@storyblok/region-helper') const EMAIL_TEST = 'test@storyblok.com' const PASSWORD_TEST = 'test' const TOKEN_TEST = 'storyblok1234' -const REGION_TEST = 'eu' +const REGION_TEST = EU_CODE // use functions to always returns 'new' data const FAKE_COMPONENTS = () => [ @@ -289,9 +291,15 @@ const FAKE_PRESET = () => ({ description: 'page preset' }) +const USERS_ROUTES = { + LOGIN: `${getRegionApiEndpoint(EU_CODE)}users/login`, + SIGNUP: `${getRegionApiEndpoint(EU_CODE)}users/signup` +} + module.exports = { EMAIL_TEST, TOKEN_TEST, + USERS_ROUTES, FAKE_STORIES, PASSWORD_TEST, FAKE_COMPONENTS, diff --git a/tests/units/list-spaces.spec.js b/tests/units/list-spaces.spec.js index b8ed1af2..cea38904 100644 --- a/tests/units/list-spaces.spec.js +++ b/tests/units/list-spaces.spec.js @@ -1,6 +1,6 @@ const { listSpaces } = require('../../src/tasks/') const { FAKE_SPACES } = require('../constants') -const { REGIONS } = require('../../src/constants') +const { EU_CODE, US_CODE, AP_CODE, CA_CODE, CN_CODE } = require('@storyblok/region-helper') describe('Test spaces method', () => { it('Testing list-spaces funtion without api instance', async () => { @@ -17,7 +17,7 @@ describe('Test spaces method', () => { getAllSpacesByRegion: jest.fn(() => Promise.resolve(FAKE_SPACES())) } expect( - await listSpaces(FAKE_API, REGIONS.cn.key) + await listSpaces(FAKE_API, CN_CODE) ).toEqual(FAKE_SPACES()) expect(FAKE_API.getAllSpacesByRegion).toHaveBeenCalled() }) @@ -28,25 +28,25 @@ describe('Test spaces method', () => { } const response = [ { - key: REGIONS.eu.key, + key: EU_CODE, res: [...FAKE_SPACES()] }, { - key: REGIONS.us.key, + key: US_CODE, res: [...FAKE_SPACES()] }, { - key: REGIONS.ca.key, + key: CA_CODE, res: [...FAKE_SPACES()] }, { - key: REGIONS.ap.key, + key: AP_CODE, res: [...FAKE_SPACES()] } ] expect( - await listSpaces(FAKE_API, REGIONS.eu.key) + await listSpaces(FAKE_API, EU_CODE) ).toEqual(response) }) }) diff --git a/tests/units/push-components.spec.js b/tests/units/push-components.spec.js index f745b61d..820efc39 100644 --- a/tests/units/push-components.spec.js +++ b/tests/units/push-components.spec.js @@ -1,7 +1,8 @@ const pushComponents = require('../../src/tasks/push-components') const Storyblok = require('storyblok-js-client') const api = require('../../src/utils/api') -const { REGIONS } = require('../../src/constants') +const { getRegionApiEndpoint } = require('../../src/utils/region') +const { EU_CODE } = require('@storyblok/region-helper') jest.mock('fs') jest.unmock('axios') @@ -10,7 +11,7 @@ const deleteDocComponent = async () => { if (process.env.STORYBLOK_TOKEN) { const client = new Storyblok({ oauthToken: process.env.STORYBLOK_TOKEN - }, REGIONS.eu.apiEndpoint) + }, getRegionApiEndpoint(EU_CODE)) try { const path = `spaces/${process.env.STORYBLOK_SPACE}/components` diff --git a/tests/units/quickstart.spec.js b/tests/units/quickstart.spec.js index bdb9c7b6..adbfb1b8 100644 --- a/tests/units/quickstart.spec.js +++ b/tests/units/quickstart.spec.js @@ -4,7 +4,8 @@ const path = require('path') const quickstart = require('../../src/tasks/quickstart') const Storyblok = require('storyblok-js-client') const api = require('../../src/utils/api') -const { REGIONS } = require('../../src/constants') +const { getRegionApiEndpoint } = require('../../src/utils/region') +const { EU_CODE } = require('@storyblok/region-helper') jest.unmock('fs') jest.unmock('axios') @@ -60,7 +61,7 @@ describe('testing quickstart()', () => { const client = new Storyblok({ oauthToken: process.env.STORYBLOK_TOKEN - }, REGIONS.eu.apiEndpoint) + }, getRegionApiEndpoint(EU_CODE)) const response = await client.get('spaces') const spaces = response.data.spaces diff --git a/tests/units/scaffold.spec.js b/tests/units/scaffold.spec.js index 95f22ade..ecb978f8 100644 --- a/tests/units/scaffold.spec.js +++ b/tests/units/scaffold.spec.js @@ -3,7 +3,8 @@ const fs = require('fs') const scaffold = require('../../src/tasks/scaffold') const Storyblok = require('storyblok-js-client') const api = require('../../src/utils/api') -const { REGIONS } = require('../../src/constants') +const { getRegionApiEndpoint } = require('../../src/utils/region') +const { EU_CODE } = require('@storyblok/region-helper') jest.mock('fs') jest.unmock('axios') @@ -12,7 +13,7 @@ const deleteTestComponent = async () => { if (process.env.STORYBLOK_TOKEN) { const client = new Storyblok({ oauthToken: process.env.STORYBLOK_TOKEN - }, REGIONS.eu.apiEndpoint) + }, getRegionApiEndpoint(EU_CODE)) try { const path = `spaces/${process.env.STORYBLOK_SPACE}/components` diff --git a/tests/units/sync.spec.js b/tests/units/sync.spec.js index ce278698..f2a5f3c4 100644 --- a/tests/units/sync.spec.js +++ b/tests/units/sync.spec.js @@ -1,6 +1,7 @@ const sync = require('../../src/tasks/sync') const Storyblok = require('storyblok-js-client') -const { REGIONS } = require('../../src/constants') +const { getRegionApiEndpoint } = require('../../src/utils/region') +const { EU_CODE } = require('@storyblok/region-helper') jest.unmock('axios') @@ -32,7 +33,7 @@ describe('testing sync function', () => { const client = new Storyblok({ oauthToken: process.env.STORYBLOK_TOKEN - }, REGIONS.eu.apiEndpoint) + }, getRegionApiEndpoint(EU_CODE)) const sourceStories = await getData( client, diff --git a/yarn.lock b/yarn.lock index 7649c3d3..6480aeac 100644 --- a/yarn.lock +++ b/yarn.lock @@ -559,6 +559,11 @@ dependencies: "@sinonjs/commons" "^1.7.0" +"@storyblok/region-helper@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@storyblok/region-helper/-/region-helper-1.0.0.tgz#5a75506a264b728da640b3c2e85680bec6cd6a1a" + integrity sha512-02B4J3XzD6CLK8DAQbK63fSar8oGYqBJxdx+7Ya0C3uJwMU5DzOMix6ShtUo1iDSd9rOl8aA5wDoCC0wh0YHMw== + "@szmarczak/http-timer@^1.1.2": version "1.1.2" resolved "https://registry.yarnpkg.com/@szmarczak/http-timer/-/http-timer-1.1.2.tgz#b1665e2c461a2cd92f4c1bbf50d5454de0d4b421"