### quickstart(api, answers, spaceId) - configure or create space Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Runs the quickstart flow. With `spaceId`, sets a dev environment via `PUT spaces/{id}/`, creates a quickstart login token via `POST tokens`, finds a theme access token via `GET api_keys` (throws 'There is no theme token in this space' if none), then calls `lastStep(answers)`. Without `spaceId`, creates a space via `POST spaces`, posts tokens, opens `http://{spaceDomain}/_quickstart?quickstart={loginToken}` in the browser after 2 s, then calls `process.exit(0)`. Rejects with `new Error(e.message)` on error. ```javascript const quickstart = async (api, answers, spaceId) => { answers.type = 'quickstart' if (hasSpaceId(spaceId)) { ... } // hasSpaceId = typeof spaceId !== 'undefined' // else: create space via POST spaces, ... open browser } ``` -------------------------------- ### storyblok quickstart command definition Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/cli.md Defines the 'quickstart' command with a description. It prompts the user with questions and calls the quickstart task. ```typescript program .command(COMMANDS.QUICKSTART) // "quickstart" .description("Start a project quickly") ``` -------------------------------- ### quickstart(api, answers, spaceId) Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Configures an existing space or creates a new one, sets up a login token, and opens the quickstart in the browser. ```APIDOC ## quickstart(api, answers, spaceId) ### Description Configures an existing space (when `spaceId` is provided) or creates a new space and opens the quickstart in the browser. ### Parameters - `api` (Object) - Required - `api` singleton. - `answers` (Object) - Required - Inquirer answers (`name`, `type`, theme choices, …); mutated with `loginToken`, `spaceId`, `spaceDomain`, `themeToken`. - `spaceId` (string | undefined) - Optional - Existing space ID to configure instead of creating a space. ### Returns `Promise` — resolves with `lastStep(answers)` on the `spaceId` path; **rejects** with `new Error(e.message)` on error. ``` -------------------------------- ### storyblok quickstart command Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Runs `storyblok quickstart` to create a Storyblok space and select a boilerplate to use. ```sh $ storyblok quickstart ``` -------------------------------- ### Install markdown to richtext converter Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Installs the storyblok-markdown-richtext converter library globally. ```sh $ npm install storyblok-markdown-richtext -g ``` -------------------------------- ### storyblok quickstart Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Create a space in Storyblok and select the boilerplate to use. ```APIDOC ## [CLI] storyblok quickstart ### Description Create a space in Storyblok and select the boilerplate to use. ### Command `storyblok quickstart` ### Example ```sh $ storyblok quickstart ``` ``` -------------------------------- ### Install Storyblok CLI Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Installs the Storyblok CLI globally. Requires Node >= 18.0.0. ```sh $ npm i storyblok -g ``` -------------------------------- ### POST tokens Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/endpoints.md Creates a quickstart login token for the Storyblok CLI. ```APIDOC ## POST tokens ### Description Creates a quickstart login token. The response contains the token key in the `data.key` field. ### Method POST ### Endpoint tokens ### Parameters #### Request Body - **{}** (object) - Empty object. ### Response #### Success Response (200) - **data.key** (string) - The quickstart login token. ``` -------------------------------- ### storyblok sync --help Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Displays help for a specific command, using the sync command as an example. ```APIDOC ## [CLI] storyblok sync --help ### Description Displays help for a specific command, using the sync command as an example. ### Command `storyblok sync --help` ### Request Example ```sh $ storyblok sync --help ``` ``` -------------------------------- ### Example usage of pushComponents Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Shows how to import the api and pushComponents, set the space ID, and call pushComponents with a source URL and a local presets path. ```javascript import api from './utils/api' import pushComponents from './tasks/push-components' api.setSpaceId(67819) await pushComponents(api, { source: 'https://raw.githubusercontent.com/storyblok/nuxtdoc/master/seed.components.json', presetsSource: '/local/path/presets.json' }) ``` -------------------------------- ### SyncComponents usage example Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Shows how to instantiate SyncComponents with source and target space IDs, an OAuth token, and optional componentsGroups and componentsFullSync options, then call sync(). ```javascript import SyncComponents from './tasks/sync-commands/components' const syncer = new SyncComponents({ sourceSpaceId: '10001', targetSpaceId: '10002', oauthToken: 'your-token', componentsGroups: ['529cc32a-1d97-4b4a-b0b6-28e33dc56c0d'], componentsFullSync: false }) await syncer.sync() ``` -------------------------------- ### Generated migration file example Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-migrations.md Example of a generated/edited migration file. It transforms the `price` field to a number. The function receives `block` and `storyFullSlug` parameters. ```javascript // migrations/change_product_price.mjs export default function (block, storyFullSlug) { block.price = Number(block.price) // transform field value } ``` -------------------------------- ### Programmatic import example Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Programmatic example of importing a CSV file using importFiles. Sets the space ID, calls importFiles with file, type, folder, and delimiter options, and catches errors logging 'import failed:' with the error message. ```javascript import api from './utils/api' import importFiles from './tasks/import/import' api.setSpaceId(67819) try { await importFiles(api, { file: './data.csv', type: 'press', folder: '42', delimiter: ';' }) } catch (e) { console.error('import failed:', e.message) } ``` -------------------------------- ### JSONSchemaToTSOptions example (additionalProperties false) Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Example JSON file to pass to JSONSchemaToTSOptionsPath, disabling additionalProperties in the generated typedefs. Defaults for bannerComment ("") and unknownAny (false) override the library defaults. ```json { "additionalProperties": false, } ``` -------------------------------- ### buildFilterQuery usage example Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/utils.md Example usage of buildFilterQuery with two keys, operations, and values. The resulting filterQuery object is shown in the comment. ```javascript import { buildFilterQuery } from './utils' const filterQuery = buildFilterQuery('category,name', 'like,not_like', 'reference,demo') // { category: { like: 'reference' }, name: { not_like: 'demo' } } ``` -------------------------------- ### generateMigration usage example Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-migrations.md Shows how to import and call generateMigration with a specific space ID, component, and field, and the expected result. ```javascript import api from '../utils/api' import generateMigration from './generate' api.setSpaceId(1234) await generateMigration(api, 'product', 'price') // → { fileName: 'change_product_price.mjs', created: true } ``` -------------------------------- ### storyblok sync usage examples Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Five examples of `storyblok sync` with various options. The first two show syncing components and combined `components,stories` types. The next three demonstrate filtering stories with `--starts-with` and the `--filter` option using `--keys`, `--operations`, and `--values`. ```sh # Sync components from `00001` space to `00002` space $ storyblok sync --type components --source 00001 --target 00002 ``` ```sh # Sync components and stories from `00001` space to `00002` space $ storyblok sync --type components,stories --source 00001 --target 00002 ``` ```sh # Sync only stories that starts with `myStartsWithString` from `00001` space to `00002` space $ storyblok sync --type stories --source 00001 --target 00002 --starts-with myStartsWithString ``` ```sh # Sync only stories with a category field like `reference` from `00001` space to `00002` space $ storyblok sync --type stories --source 00001 --target 00002 --filter --keys category --operations like --values reference ``` ```sh # Sync only stories with a category field like `reference` and a name field not like `demo` from `00001` space to `00002` space $ storyblok sync --type stories --source 00001 --target 00002 --filter --keys category,name --operations like,not_like --values reference,demo ``` -------------------------------- ### Get global node modules path Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Shows the global node modules folder path, needed to require the globally installed converter in the migration file. ```sh $ npm root -g ``` -------------------------------- ### Generate TypeScript typedefs (examples) Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Example commands for the generate-typescript-typedefs command, covering single/multiple sources, custom destination, JSONSchemaToTS options, and a custom parser. ```sh # Generate typedefs for the components retrieved for the space `12345` via the `storyblok pull-components` command $ storyblok generate-typescript-typedefs --sourceFilePaths ./components.12345.json # Generate typedefs for multiple components sources $ storyblok generate-typescript-typedefs --sourceFilePaths ./fooComponent-12345.json,./barComponent-12345.json # Custom path for the typedefs file $ storyblok generate-typescript-typedefs --sourceFilePaths ./components.12345.json --destinationFilePath ./types/my-custom-type-file.d.ts # Provide customized options for the JSON-schema-to-typescript lib $ storyblok generate-typescript-typedefs --sourceFilePaths ./components.12345.json --JSONSchemaToTSOptionsPath ./PathToJSONFileWithCustomOptions.json # Provide a custom field types parser $ storyblok generate-typescript-typedefs --sourceFilePaths ./components.12345.json --customFieldTypesParserPath ./customFieldTypesParser.js ``` -------------------------------- ### SyncComponentGroups usage example Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Example of importing and using SyncComponentGroups to sync component groups between spaces. It creates an instance with sourceSpaceId '1', targetSpaceId '2', and oauthToken 'token', then calls sync() and destructures the returned source and target component groups. ```javascript import SyncComponentGroups from './tasks/sync-commands/component-groups' const groups = new SyncComponentGroups({ sourceSpaceId: '1', targetSpaceId: '2', oauthToken: 'token' }) const { source, target } = await groups.sync() ``` -------------------------------- ### push-components with URL source Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Push components using a URL as the source. The example uses a raw GitHub URL for the components JSON file and targets space ID 67819. ```sh $ storyblok push-components https://raw.githubusercontent.com/storyblok/nuxtdoc/master/seed.components.json --space 67819 ``` -------------------------------- ### Usage example for PresetsLib Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/presets-lib.md Shows how to use the PresetsLib class to copy presets from a source space to a target component. It sets the API space ID, creates a PresetsLib instance with the OAuth token and target space ID, fetches source presets, filters them against the target component's existing presets, and creates or updates them via POST and PUT requests. ```javascript import PresetsLib from './utils/presets-lib' import api from './utils/api' api.setSpaceId(10002) const presetsLib = new PresetsLib({ oauthToken: api.oauthToken, targetSpaceId: 10002 }) const sourcePresets = await presetsLib.getPresets(10001) const componentPresets = presetsLib.getComponentPresets(component, sourcePresets) const { newPresets, updatePresets } = presetsLib.filterPresetsFromTargetComponent( componentPresets, targetComponent.all_presets || [] ) await presetsLib.createPresets(newPresets, targetComponent.id, 'post') await presetsLib.createPresets(updatePresets, targetComponent.id, 'put') ``` -------------------------------- ### loginWithToken(content) Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/api.md Validates a token via `GET users/me` and persists credentials. ```APIDOC ## `loginWithToken(content)` ### Description Validates a token via `GET users/me` and persists credentials. Returns the user object. ### Method `loginWithToken` ### Parameters - `content.token` (string) - Required - Personal access token. - `content.region` (string) - Required - Region code. ### Returns `Promise` (user). Rejects with the axios error when the token is invalid. ### Example ```js await loginWithToken({ token, region }) ``` ``` -------------------------------- ### deleteComponent usage example Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Shows how to import and use deleteComponent with a space ID. The first call deletes the 'teaser' component; the second call demonstrates the rejection when the component does not exist. ```javascript import api from './utils/api' import deleteComponent from './tasks/delete-component' api.setSpaceId(67819) await deleteComponent(api, { comp: 'teaser', dryrun: false }) // deletes; logs ✓ Component teaser deleted. try { await deleteComponent(api, { comp: 'does-not-exist' }) } catch (e) { // Error: Component does-not-exist not found. } ``` -------------------------------- ### Use getQuestions with inquirer for select command Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/utils.md Example usage for the `select` command: prompts the user with the question set built by `getQuestions('select')` and then passes the answers to `lastStep`. ```javascript import inquirer from 'inquirer' import { getQuestions } from './utils' const answers = await inquirer.prompt(getQuestions('select')) await lastStep(answers) ``` -------------------------------- ### Get current user Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Displays the currently logged-in user. ```sh $ storyblok user ``` -------------------------------- ### Example invocation of pullComponents Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Shows how the CLI invokes pullComponents with a space ID and options. It sets the space ID, calls the function with separateFiles, prefixPresetsNames, and resolveDatasources enabled, and logs an error on failure. ```javascript import api from './utils/api' import pullComponents from './tasks/pull-components' api.setSpaceId(67819) try { await pullComponents(api, { fileName: '67819', separateFiles: true, prefixPresetsNames: true, resolveDatasources: true }) // files: hero-67819.json, presetname-67819.json, ... } catch (e) { console.error('pull failed', e) } ``` -------------------------------- ### GET api_keys Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/endpoints.md Retrieves API keys, filtering for theme access to obtain the token. ```APIDOC ## GET api_keys ### Description Retrieves API keys. The response contains a list of API keys, which are filtered for those with `access === 'theme'` to obtain the token. ### Method GET ### Endpoint api_keys ### Parameters No parameters. ### Response #### Success Response (200) - **data.api_keys** (array) - List of API keys. Filter for `access === 'theme'` to get the token. ``` -------------------------------- ### Generate migration for image field Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Generates a migration file for the 'image' field of the product component. This is the first step in the example that replaces the image URL. ```sh $ storyblok generate-migration --space 00000 --component product --field image ``` -------------------------------- ### Define getQuestions function in src/utils/get-questions.js Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/utils.md Function that builds an array of inquirer question definitions based on the `subCommand` argument. Supports values like `'select'`, `'login-strategy'`, `'login-with-email'`, `'login-with-token'`, `'delete-templates'`, `'pull-components'`, `'push-components'`, `'scaffold'`, and a default used by `quickstart`. The `api` parameter is used for async password validation, and the region input defaults to `EU_CODE`. ```javascript const getOptions = (subCommand, argv = {}, api = {}) => { ... } export default getOptions ``` -------------------------------- ### Migration file template with {{fieldname}} placeholder Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-migrations.md Template string exported from `src/tasks/templates/migration-file.js`. It is interpolated with `{{fieldname}}` to generate a migration file. The template includes commented examples for changing a string to boolean and transferring content from another field. ```javascript export default `export default function (block) { // Example to change a string to boolean // block.{{ fieldname }} = !!(block.{{ fieldname }}) // Example to transfer content from other field // block.{{ fieldname }} = block.other_field } ` ``` -------------------------------- ### lastStep(answers) function Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/utils.md Defines the lastStep function that takes Inquirer answers and returns a Promise. It resolves the git repository URL based on the type, clones it into ./{name}, and handles post-clone setup. On ENOTEMPTY error, it prints a hint and rejects with 'This repository already has been cloned'. ```javascript const lastStep = answers => { return new Promise((resolve, reject) => { ... }) } export default lastStep ``` -------------------------------- ### Select a boilerplate or fieldtype Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Kickstart a boilerplate, fieldtype, or theme. ```sh $ storyblok select ``` -------------------------------- ### init() Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Loads source and target component groups. Rejects on failure. ```APIDOC ## init() ### Description Loads source and target component groups using the Storyblok API. ### Method GET ### Endpoint `spaces/{id}/component_groups` ### Parameters - **id** (string) - Required - The space ID. ### Response - **data.component_groups** (array) - List of component groups. ### Errors Rejects on failure. ``` -------------------------------- ### signup(email, password, region) Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/api.md Creates a new account via `POST users/signup` and persists the token on success. ```APIDOC ## `signup(email, password, region = EU_CODE)` ### Description Creates a new account via `POST users/signup` and persists the token on success. ### Method `signup` ### Parameters - `email` (string) - Required - New account email. - `password` (string) - Required - New account password. - `region` (string) - Optional - Account region (default: `EU_CODE`). ### Returns `Promise` on success (token persisted via `extractToken(response)`). Rejects with the axios error. ### Example ```js await signup(email, password, region) ``` ``` -------------------------------- ### push-components with local file and presets-source Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Push components from a local file and provide presets from a local JSON file via the --presets-source option. ```sh $ storyblok push-components ./components.json --presets-source ./presets.json --space 67819 ``` -------------------------------- ### storyblok user Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Get the currently logged in user. ```APIDOC ## storyblok user ### Description Get the currently logged in user. ### Method CLI command ### Command `storyblok user` ### Parameters None ``` -------------------------------- ### storyblok select Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Kickstart a boilerplate, fieldtype, or theme. ```APIDOC ## storyblok select ### Description Usage to kickstart a boilerplate, fieldtype or theme. ### Method CLI command ### Command `storyblok select` ### Parameters None ``` -------------------------------- ### static async init(componentsJSONSchemas, options) Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/generate-typescript-typedefs.md Async-constructor proxy that loads the custom type parser and returns a new GenerateTypesFromJSONSchemas instance. ```APIDOC ## static async init(componentsJSONSchemas, options) ### Description Async-constructor proxy that loads the custom type parser and returns a new GenerateTypesFromJSONSchemas instance. ### Method static async init ### Parameters - **componentsJSONSchemas** (JSONSchema[]) - Required - Array of component JSON Schemas for which types are generated. - **options** (GenerateTSTypedefsFromComponentsJSONSchemasOptions) - Required - See types.md. ### Returns Promise ``` -------------------------------- ### sync() Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Loads datasources from both source and target spaces, then adds missing datasources and updates existing ones. ```APIDOC ## sync() ### Description Loads target and source datasources using `client.getAll`, then calls `addDatasources()` and `updateDatasources()`. ### Method async ### Parameters None ### Returns Promise that resolves when synchronization is complete. ``` -------------------------------- ### Custom Field Types parser example Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Parser function for Custom Field Types, exported as default export knows how to render a JSONSchema Node for each custom field type. This example maps a custom field type to an object with a color property. The file should be passed via customFieldTypesParserPath. ```js export default function (key, obj) { switch (obj.field_type) { case 'my-custom-field-type-name': return { [key]: { type: 'object', properties: { color: { type: 'string' } }, required: ['color'] } } default: return {} } } ``` -------------------------------- ### push-components with URL and presets-source URL Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Push components from a URL and provide presets from a remote JSON file via the --presets-source option. ```sh $ storyblok push-components https://raw.githubusercontent.com/storyblok/nuxtdoc/master/seed.components.json --presets-source https://url-to-your-presets-file.json --space 67819 ``` -------------------------------- ### GET spaces/{spaceId}/datasources Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/endpoints.md Retrieves a list of datasources from a specific space. ```APIDOC ## GET spaces/{spaceId}/datasources ### Description Retrieves a list of datasources from a specific space. ### Method GET ### Endpoint spaces/{spaceId}/datasources ### Response #### Success Response (200) - **data.datasources** - Array of datasource objects. #### Response Example ```json { "data": { "datasources": [] } } ``` ``` -------------------------------- ### scaffold(api, name, space) - create component or local files Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Scaffolds a component. If `space` is provided, requires `api.accessToken` (rejects with 'The user is not logged' otherwise), sets the space ID, and creates the component via `POST components`. Otherwise writes local `_.liquid` (teaser template) and `_.scss` files, then resolves with `true`. ```javascript export default async function (api, name, space) { if (space) { if (!api.accessToken) { return Promise.reject(new Error('The user is not logged')) } api.setSpaceId(space) return api.post('components', { component: { name } }) } var liquid = './views/components/_' + name + '.liquid' fs.writeFileSync(liquid, await import('./templates/teaser')) var scss = './source/scss/components/below/_' + name + '.scss' fs.writeFileSync(scss, '// Generated by the Storyblok cli') return Promise.resolve(true) } ``` -------------------------------- ### GET spaces/{spaceId}/stories/{storyId} Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/endpoints.md Retrieves a single story by its ID from a specific space. ```APIDOC ## GET spaces/{spaceId}/stories/{storyId} ### Description Retrieves a single story by its ID from a specific space. ### Method GET ### Endpoint spaces/{spaceId}/stories/{storyId} ### Parameters #### Path Parameters - **storyId** - Required - The ID of the story to retrieve. ### Response #### Success Response (200) - **data.story** - The story object. #### Response Example ```json { "data": { "story": {} } } ``` ``` -------------------------------- ### Export credentials object Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/creds.md Exports the credentials module's public API with set and get functions. ```javascript export default { set: set, get: get } ``` -------------------------------- ### storyblok --help Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Displays global help for the Storyblok CLI. ```APIDOC ## [CLI] storyblok --help ### Description Displays global help for the Storyblok CLI. ### Command `storyblok --help` ### Request Example ```sh $ storyblok --help ``` ``` -------------------------------- ### push-components with multiple file paths Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Push components from multiple local JSON files. The source is a comma-separated list of file paths. ```sh $ storyblok push-components ./page.json,../grid.json,./feature.json --space 67819 ``` -------------------------------- ### GET spaces/{spaceId}/stories Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/endpoints.md Retrieves a list of stories from a specific space with support for pagination, filtering, and sorting. ```APIDOC ## GET spaces/{spaceId}/stories ### Description Retrieves a list of stories from a specific space. Supports pagination via the `client.getAll` method and various query parameters for filtering and sorting. ### Method GET ### Endpoint spaces/{spaceId}/stories ### Parameters #### Query Parameters - **story_only** - Optional - Filter to return only stories. - **folder_only** - Optional - Filter to return only folders. - **sort_by** - Optional - Sort the results by a specific field. - **starts_with** - Optional - Filter stories by a path prefix. - **filter_query** - Optional - Apply a filter query. - **with_slug** - Optional - Include the slug in the response. - **contain_component** - Optional - Filter stories that contain a specific component. ### Response #### Success Response (200) - **data.stories** - Array of story items. #### Response Example ```json { "data": { "stories": [] } } ``` ``` -------------------------------- ### GET spaces/{spaceId}/datasource_entries?datasource_id={id} Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/endpoints.md Retrieves datasource entries for a specific datasource with pagination and dimension filtering. ```APIDOC ## GET spaces/{spaceId}/datasource_entries?datasource_id={id} ### Description Retrieves datasource entries for a specific datasource. Supports pagination and dimension filtering. ### Method GET ### Endpoint spaces/{spaceId}/datasource_entries?datasource_id={id} ### Parameters #### Query Parameters - **datasource_id** (integer) - Required - The ID of the datasource. - **page** (integer) - Optional - Page number for pagination (25 entries per page). - **dimension** (string) - Optional - Dimension ID to filter entries. ### Response #### Success Response (200) - **data.datasource_entries** - Array of datasource entries, including `total` for pagination. #### Response Example ```json { "data": { "datasource_entries": { "total": 0 } } } ``` ``` -------------------------------- ### signup: Create account via users/signup Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/api.md Creates a new account via POST users/signup. On success, persists the token via extractToken(response) and resolves with true. Rejects with the axios error on failure. ```javascript signup (email, password, region = EU_CODE) { return axios.post(`${this.apiSwitcher(region)}users/signup`, { email: email, password: password, region }) ... } ``` -------------------------------- ### Define StoryblokProvidedPropertyType union Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/types.md Defines the union type for field types Storyblok provides out of the box, each getting a predefined shared JSON Schema. ```typescript export type StoryblokProvidedPropertyType = "asset" | "multiasset" | "multilink" | "table" | "richtext"; ``` -------------------------------- ### Run migration and publish content with --publish Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Runs the migration and publishes the updates. The --publish flag requires one of: 'all', 'published', or 'published-with-changes'. ```sh $ storyblok run-migration --space 00000 --component product --field price --publish all ``` -------------------------------- ### PresetsLib class imports and constructor Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/presets-lib.md Imports chalk, form-data, axios, lodash and the shared api client, then defines the PresetsLib constructor that stores oauthToken and targetSpaceId and obtains the shared client via api.getClient(). The oauthToken must match the token cached in the api object, otherwise a new client is created. ```javascript import chalk from 'chalk' import FormData from 'form-data' import axios from 'axios' import lodash from 'lodash' import api from './api' const { last } = lodash class PresetsLib { /** * @param {{ oauthToken: string, targetSpaceId: int }} options */ constructor (options) { this.oauthToken = options.oauthToken this.client = api.getClient() this.targetSpaceId = options.targetSpaceId } ``` -------------------------------- ### push-components with single file path Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Push components from a single local JSON file. The source path is given as a relative path to the components file. ```sh $ storyblok push-components ./components.json --space 67819 ``` -------------------------------- ### SyncComponents constructor Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Initializes the SyncComponents instance with source and target space IDs, OAuth token, and optional componentsGroups and componentsFullSync options. Sets up the API client and PresetsLib. ```javascript class SyncComponents { /** * @param {{ sourceSpaceId: string, targetSpaceId: string, oauthToken: string }} options */ constructor (options) { this.sourcePresets = [] this.targetComponents = [] this.sourceComponents = [] this.sourceSpaceId = options.sourceSpaceId this.targetSpaceId = options.targetSpaceId this.oauthToken = options.oauthToken this.client = api.getClient() this.presetsLib = new PresetsLib({ oauthToken: options.oauthToken, targetSpaceId: this.targetSpaceId }) this.componentsGroups = options.componentsGroups this.componentsFullSync = options.componentsFullSync } ``` -------------------------------- ### apiSwitcher(region) - get region API endpoint Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/api.md Returns the API endpoint for the given region, falling back to this.region if not provided. Returns a string like {getRegionBaseUrl(region)}/v1/. ```javascript apiSwitcher (region) { return region ? getRegionApiEndpoint(region) : getRegionApiEndpoint(this.region) } ``` -------------------------------- ### sync(types, options) function Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md The sync function initializes SyncSpaces with options, sorts the types array to place 'folders' first, maps each type to a sync method on SyncSpaces, and runs them sequentially with p-series. It returns a Promise that resolves to the last task result or rejects if any sync method rejects. ```javascript const sync = (types, options) => { SyncSpaces.init(options) const tasks = types.sort((a, b) => { if (a === 'folders') return -1 if (b === 'folders') return 1 return 0 }).map(_type => { const command = `sync${capitalize(_type)}` return () => SyncSpaces[command]() }) return pSeries(tasks) } ``` -------------------------------- ### Generic request methods: post, put, get, delete, sendRequest Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/api.md Generic request methods that delegate to sendRequest, which uses the memoized client and resolves the path. Returns a Promise from the storyblok-js-client. ```javascript post (path, props) { return this.sendRequest(path, 'post', props) } put (path, props) { return this.sendRequest(path, 'put', props) } get (path, options = {}) { return this.sendRequest(path, 'get', options) } delete (path) { return this.sendRequest(path, 'delete') } sendRequest (path, method, props = {}) { const client = this.getClient() const _path = this.getPath(path) return client[method](_path, props) } ``` -------------------------------- ### storyblok run-migration Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Execute a specific migration file. ```APIDOC ## [CLI] storyblok run-migration ### Description Execute a specific migration file. Check **Migrations** section for more details. ### Command `storyblok run-migration` ### Options - **space** (string) - Required - The space you get from the space settings area. - **component** (string) - Required - Component name. It needs to be a valid component. - **field** (string) - Required - Name of field. - **dryrun** (flag) - Optional - When passed as an argument, does not perform the migration. - **publish** (string) - Optional - Publish the content when update. Possible values: `all`, `published`, `published-with-changes`. - **publish-languages** (string) - Optional - Publish specific languages. You can publish more than one language at a time by separating the languages by `,`. ### Examples ```sh $ storyblok run-migration --space --component --field --dryrun $ storyblok run-migration --publish published --space 1234 --component article --field image ``` ``` -------------------------------- ### Generated migration file stub Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Default content of a generated migration file. Shows an empty module.exports function with commented examples for changing a field type or transferring content from another field. ```js // here, 'subtitle' is the name of the field defined when you execute the generate command module.exports = function (block) { // Example to change a string to boolean // block.subtitle = !!(block.subtitle) // Example to transfer content from other field // block.subtitle = block.other_field } ``` -------------------------------- ### runMigration(api, component, field, options) Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-migrations.md Runs a migration on stories of a given component and field. It fetches stories, applies the migration function to each story's content, and optionally publishes the changes. Supports dry-run mode and rollback file creation. ```APIDOC ## `runMigration(api, component, field, options)` ### Description Runs a migration on stories of a given component and field. It fetches stories, applies the migration function to each story's content, and optionally publishes the changes. Supports dry-run mode and rollback file creation. ### Method FUNCTION ### Endpoint `runMigration(api, component, field, options)` ### Parameters #### Path Parameters - **api** (Object) - Required - The API singleton object. - **component** (string) - Required - Component name. - **field** (string) - Required - Field name. #### Options Object - **options.isDryrun** (boolean) - Optional - When truthy, stories are processed but not sent to the API. - **options.migrationPath** (string) - Optional - Override for the migration file directory. Defaults to `process.cwd()/migrations`. - **options.publish** (PublishOptions) - Optional - Publish behavior: 'all', 'published', or 'published-with-changes'. - **options.publishLanguages** (string) - Optional - Language codes sent as the `lang` payload property. ### Returns - **Promise<{ executed: boolean, motive?: string }>** - Resolves with `{ executed: false, motive: 'NO_STORIES' }` if no stories found, otherwise `{ executed: true }`. ### Behavior 1. Checks if the migration file exists; throws if not. 2. Dynamically imports the migration file and validates it exports a function. 3. Fetches all stories for the component. 4. If no stories, resolves with `{ executed: false, motive: 'NO_STORIES' }`. 5. For each story, fetches the single story, deep-clones content, and applies the migration function recursively. If content changed and not dry-run, updates the story via PUT and optionally publishes. 6. Creates a rollback file after processing all stories. ### Example ```js import api from '../utils/api' import runMigration from './run' api.setSpaceId(1234) await runMigration(api, 'product', 'price', { isDryrun: true }) // inspect console output, then: await runMigration(api, 'product', 'price', { publish: 'all', publishLanguages: 'de,pt' }) ``` ``` -------------------------------- ### creds.set() - write or remove credentials Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/creds.md Sets or removes credentials in the .netrc file. If email is null, removes the api.storyblok.com entry and returns null; otherwise writes the entry and returns the result of get(). ```javascript const set = function (email, token, region) { const file = getFile() let obj = {} try { obj = netrc(file) } catch (e) { obj = {} } if (email === null) { delete obj[host] fs.writeFileSync(file, netrc.format(obj) + os.EOL) return null } else { obj[host] = { login: email, password: token, region } fs.writeFileSync(file, netrc.format(obj) + os.EOL) return get() } } ``` -------------------------------- ### scaffold(api, name, space) Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Creates a new component either remotely in Storyblok or locally as liquid and scss files. ```APIDOC ## scaffold(api, name, space) ### Description Creates a new component either remotely in Storyblok (when `space` is provided) or locally as liquid and scss files. ### Parameters - `api` (Object) - Required - `api` singleton. - `name` (string) - Required - Component name — used for the component, the liquid file name and the scss file name. - `space` (string | undefined) - Optional - When provided, creates the component remotely (`POST components`); otherwise writes local `_.liquid` (teaser template) and `_.scss` files. ### Returns `Promise` — `api.post(...)` response when `space` is given, else `Promise.resolve(true)`. ### Rejects `new Error('The user is not logged')` when `space` is given but `api.accessToken` is empty. ``` -------------------------------- ### loginWithToken: Validate token via users/me Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/api.md Validates a personal access token by calling GET users/me with the token in the Authorization header. On success, persists credentials and returns the user object. Rejects with the axios error if the token is invalid. ```javascript async loginWithToken (content) { const { token, region } = content const { data } = await axios.get(`${this.apiSwitcher(region)}users/me`, { headers: { Authorization: token } }) this.persistCredentials(data.user.email, token, region) return data.user } ``` -------------------------------- ### Login to Storyblok CLI Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Initiates the login process for the Storyblok CLI. Requires region and credentials (email/password or token). ```sh $ storyblok login ``` -------------------------------- ### SyncDatasources constructor Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Initializes a new SyncDatasources instance with source and target space IDs and an OAuth token. ```APIDOC ## SyncDatasources constructor ### Description Creates a new SyncDatasources instance with the provided options. ### Constructor `new SyncDatasources(options)` ### Parameters - **options** (object) - Required - An object containing: - **sourceSpaceId** (string) - Required - The ID of the source space. - **targetSpaceId** (string) - Required - The ID of the target space. - **oauthToken** (string) - Required - The OAuth token for authentication. ### Behavior Initializes `this.client = api.getClient()`. ``` -------------------------------- ### push-components command syntax Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Push a local or remote JSON components file to a Storyblok space, with optional presets source. The source can be a URL or a comma-separated list of paths to JSON files. ```sh $ storyblok push-components --space --presets-source ``` -------------------------------- ### storyblok run-migration command Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Two invocations of `storyblok run-migration` to execute migration files. The first shows the generic template with the optional `--dryrun` flag, which does not perform the migration. The second shows the `--publish published` flag to publish content after saving, using a concrete space, component, and field. ```sh $ storyblok run-migration --space --component --field --dryrun ``` ```sh $ storyblok run-migration --publish published --space 1234 --component article --field image ``` -------------------------------- ### sync() Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Creates groups missing on the target (matched by name) and returns the loaded component groups. ```APIDOC ## sync() ### Description Synchronizes component groups from source to target. Creates groups that are missing on the target. ### Method POST ### Endpoint `spaces/{id}/component_groups` ### Parameters - **id** (string) - Required - The target space ID. - **name** (string) - Required - The name of the component group to create. ### Request Body ```json { "component_group": { "name": "string" } } ``` ### Response - **data.component_group** (object) - The created component group. ### Returns Returns `loadComponentsGroups()` which provides `{ source, target }`. ``` -------------------------------- ### pushComponents(api, { source, presetsSource }) Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks.md Pushes components, component groups, and presets from a source file or URL to the target Storyblok space. It loads the data, creates missing component groups, handles internal tags, and creates or updates components and presets. ```APIDOC ## pushComponents(api, { source, presetsSource }) ### Description Pushes components, component groups, and presets from a source file or URL to the target Storyblok space. It loads the data, creates missing component groups, handles internal tags, and creates or updates components and presets. ### Parameters - **api** (Object) - Required - The `api` singleton; `api.spaceId` must be set (target space). - **source** (string) - Required - URL, or path to JSON file; comma-separated paths create a list payload. - **presetsSource** (string) - Optional - URL or path to a presets JSON file. ### Behavior Loads components/presets/component_groups; `buildComponentsGroupsTree` reconstructs the group hierarchy and `pushComponentsGroups` creates missing groups (`POST component_groups`); then, per component, handles internal tags (`getSpaceInternalTags` + `createComponentInternalTag`), rewrites `component_group_whitelist` UUIDs to target-space UUIDs, and either `PUT components/{id}` (existing, matched by name) or `POST components` (new). Presets are pushed via `PresetsLib` (`createPresets` for new/updated, `getSamePresetFromTarget` for default preset resolution). ### Returns `Promise` on success. ### Rejects `Promise.reject(e.message)` when loading fails; `Promise.reject(new Error('Can not push invalid json - please provide a valid json file'))` for invalid input. ### Example ```js import api from './utils/api' import pushComponents from './tasks/push-components' api.setSpaceId(67819) await pushComponents(api, { source: 'https://raw.githubusercontent.com/storyblok/nuxtdoc/master/seed.components.json', presetsSource: '/local/path/presets.json' }) ``` ``` -------------------------------- ### Pull components schema Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md Downloads your space's components schema as JSON. The first command saves a combined file named with the space ID. The second command uses --separate-files to create individual component files and prefixes preset names. The third command resolves datasources for option fields. ```sh $ storyblok pull-components --space # Will save files like components-1234.json ``` ```sh $ storyblok pull-components --space --separate-files --prefix-presets-names --file-name production # Will save files like feature-production.json grid-production.json ``` ```sh $ storyblok pull-components --space --resolve-datasources # Will resolve datasources for single/multiple option field ``` -------------------------------- ### storyblok sync command template Source: https://github.com/storyblok/storyblok-cli/blob/main/README.md The generic `storyblok sync` command template. Substitute the `--type`, `--source`, and `--target` options to sync components, folders, roles, datasources, or stories between spaces. Multiple types can be passed comma-separated. ```sh $ storyblok sync --type --source --target ``` -------------------------------- ### SyncDatasources class constructor Source: https://github.com/storyblok/storyblok-cli/blob/main/_autodocs/api-reference/tasks-sync.md Constructor for SyncDatasources. Requires sourceSpaceId, targetSpaceId, and oauthToken. Initializes this.client = api.getClient(). ```javascript class SyncDatasources { /** * @param {{ sourceSpaceId: string, targetSpaceId: string, oauthToken: string }} options */ constructor (options) { ... } ```