@powersync/cli-plugin-docker 0.9.0

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 (36) hide show
  1. package/LICENSE +67 -0
  2. package/README.md +75 -0
  3. package/dist/DockerCommand.d.ts +7 -0
  4. package/dist/DockerCommand.js +7 -0
  5. package/dist/api/docker.d.ts +47 -0
  6. package/dist/api/docker.js +109 -0
  7. package/dist/commands/docker/configure.d.ts +13 -0
  8. package/dist/commands/docker/configure.js +182 -0
  9. package/dist/commands/docker/index.d.ts +12 -0
  10. package/dist/commands/docker/index.js +13 -0
  11. package/dist/commands/docker/reset.d.ts +11 -0
  12. package/dist/commands/docker/reset.js +37 -0
  13. package/dist/commands/docker/start.d.ts +11 -0
  14. package/dist/commands/docker/start.js +26 -0
  15. package/dist/commands/docker/stop.d.ts +14 -0
  16. package/dist/commands/docker/stop.js +44 -0
  17. package/dist/constants.d.ts +4 -0
  18. package/dist/constants.js +4 -0
  19. package/dist/docker.d.ts +1 -0
  20. package/dist/docker.js +1 -0
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.js +1 -0
  23. package/dist/templates/bucket-storage/external/ExternalBucketStorageModule.d.ts +3 -0
  24. package/dist/templates/bucket-storage/external/ExternalBucketStorageModule.js +24 -0
  25. package/dist/templates/bucket-storage/postgres/PostgresBucketStorageModule.d.ts +3 -0
  26. package/dist/templates/bucket-storage/postgres/PostgresBucketStorageModule.js +58 -0
  27. package/dist/templates/source-database/external/ExternalSourceDatabaseModule.d.ts +3 -0
  28. package/dist/templates/source-database/external/ExternalSourceDatabaseModule.js +30 -0
  29. package/dist/templates/source-database/postgres/PostgresSourceDatabaseModule.d.ts +3 -0
  30. package/dist/templates/source-database/postgres/PostgresSourceDatabaseModule.js +73 -0
  31. package/dist/templates/templates-index.d.ts +2 -0
  32. package/dist/templates/templates-index.js +10 -0
  33. package/dist/types.d.ts +26 -0
  34. package/dist/types.js +6 -0
  35. package/oclif.manifest.json +278 -0
  36. package/package.json +55 -0
package/LICENSE ADDED
@@ -0,0 +1,67 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-ALv2
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Journey Mobile, Inc.
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under these Terms and Conditions, as indicated by our inclusion of these Terms and Conditions with the Software.
20
+
21
+ ### License Grant
22
+
23
+ Subject to your compliance with this License Grant and the Patents, Redistribution and Trademark clauses below, we hereby grant you the right to use, copy, modify, create derivative works, publicly perform, publicly display and redistribute the Software for any Permitted Purpose identified below.
24
+
25
+ ### Permitted Purpose
26
+
27
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use means making the Software available to others in a commercial product or service that:
28
+
29
+ 1. substitutes for the Software;
30
+ 2. substitutes for any other product or service we offer using the Software that exists as of the date we make the Software available; or
31
+ 3. offers the same or substantially similar functionality as the Software.
32
+
33
+ Permitted Purposes specifically include using the Software:
34
+
35
+ 1. for your internal use and access;
36
+ 2. for non-commercial education;
37
+ 3. for non-commercial research; and
38
+ 4. in connection with professional services that you provide to a licensee using the Software in accordance with these Terms and Conditions.
39
+
40
+ ### Patents
41
+
42
+ To the extent your use for a Permitted Purpose would necessarily infringe our patents, the license grant above includes a license under our patents. If you make a claim against any party that the Software infringes or contributes to the infringement of any patent, then your patent license to the Software ends immediately.
43
+
44
+ ### Redistribution
45
+
46
+ The Terms and Conditions apply to all copies, modifications and derivatives of the Software.
47
+ If you redistribute any copies, modifications or derivatives of the Software, you must include a copy of or a link to these Terms and Conditions and not remove any copyright notices provided in or with the Software.
48
+
49
+ ### Disclaimer
50
+
51
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
52
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
53
+
54
+ ### Trademarks
55
+
56
+ Except for displaying the License Details and identifying us as the origin of the Software, you have no right under these Terms and Conditions to use our trademarks, trade names, service marks or product names.
57
+
58
+ ## Grant of Future License
59
+
60
+ We hereby irrevocably grant you an additional license to use the Software under the Apache License, Version 2.0 that is effective on the second anniversary of the date we make the Software available. On or after that date, you may use the Software under the Apache License, Version 2.0, in which case the following will apply:
61
+
62
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
63
+ You may obtain a copy of the License at
64
+
65
+ http://www.apache.org/licenses/LICENSE-2.0
66
+
67
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # @powersync/cli-plugin-docker
2
+
3
+ > **Bundled plugin:** This plugin is automatically included in the `powersync` package. You do not need to install it separately — all `powersync docker` commands are available out of the box when you install `powersync`.
4
+
5
+ PowerSync CLI plugin that adds a **docker** topic for self-hosted instances: **configure**, **reset**, **start**, and **stop** using Docker Compose.
6
+
7
+ ## Commands
8
+
9
+ All commands live under **`powersync docker`**:
10
+
11
+ - **`powersync docker configure`** – Create **powersync/docker/** with database and storage modules (see **Templates** below). Requires **`--database`** and **`--storage`**. Creates **docker-compose.yaml**, **.env** (with defaults), and merges service snippets into **service.yaml** (preserving `!env` so the container resolves vars from **.env**). Writes **cli.yaml** with `plugins.docker.project_name` for reset/start/stop.
12
+ - **`powersync docker start`** – Start the stack (`docker compose up -d --wait`). **Use this after configure** to bring up the stack.
13
+ - **`powersync docker reset`** – Start from a clean state: stop and remove containers (`docker compose down`), then start (`docker compose up -d --wait`). Use **only when you need a clean state** (e.g. after config changes).
14
+ - **`powersync docker stop`** – Stop the stack (`docker compose stop` by default; use `--remove` for `down`, `--remove-volumes` for `down -v`).
15
+
16
+ Run **`powersync docker`** with no subcommand to see help.
17
+
18
+ All commands use the same project and directory resolution as the main CLI (e.g. `--directory powersync`). They require a self-hosted PowerSync project (**service.yaml** with `_type: self-hosted`). Linking (**cli.yaml** / API_URL / PS_ADMIN_TOKEN) is optional.
19
+
20
+ ## Templates (composable modules)
21
+
22
+ Templates are organized by **category** and **implementation**:
23
+
24
+ - **`templates/source-database/`** – Replication source (e.g. **postgres**). Used by **`--database`**.
25
+ - **`templates/bucket-storage/`** – PowerSync bucket metadata (e.g. **postgres**). Used by **`--storage`**.
26
+ - **`templates/backend/`** – (Reserved for future use.)
27
+
28
+ Each implementation provides:
29
+
30
+ - A **compose partial** **`<impl>.<category>.compose.yaml`** (e.g. `postgres.database.compose.yaml`, `postgres.storage.compose.yaml`). Storage modules define their own service(s) (e.g. `pg-storage`).
31
+ - A **service snippet** **`<impl>.<category>.service.yaml`** – YAML merged into the project **service.yaml** (replication and storage sections). Snippets use the **`!env`** custom tag (e.g. `uri: !env PS_DATA_SOURCE_URI`) so the PowerSync container resolves values from **docker/.env** at runtime.
32
+ - **`template.env`** – Env vars for that module. Init merges these into **powersync/docker/.env**.
33
+
34
+ **`powersync docker configure`** copies the selected modules into **powersync/docker/modules/**, generates **docker-compose.yaml** (include of both partials + PowerSync service with **env_file: .env**), writes **.env** (merged from template.env snippets + PowerSync vars), and merges the service snippets into **service.yaml** (preserving `!env` tags).
35
+
36
+ ### Example
37
+
38
+ ```bash
39
+ powersync docker configure --database postgres --storage postgres
40
+ ```
41
+
42
+ Creates **powersync/docker/** with:
43
+
44
+ - **modules/database-postgres/** – `postgres.database.compose.yaml` (pg-db), `postgres.database.service.yaml` snippet, **template.env**.
45
+ - **modules/storage-postgres/** – `postgres.storage.compose.yaml` (pg-storage), `postgres.storage.service.yaml` snippet, **template.env**.
46
+ - **docker-compose.yaml** – `include:` of both partials + PowerSync service (depends on pg-db and pg-storage; uses **env_file: .env**).
47
+ - **.env** – Merged from template.env snippets and PowerSync vars (defaults; no manual setup required for basic use).
48
+
49
+ Also merges the database and storage snippets into **powersync/service.yaml** (replication and storage with `!env` preserved) and creates/updates **cli.yaml** with `plugins.docker.project_name` (derived from the config directory name). When running **docker stop**, use **`--project-name`** to target a specific project or run from another directory.
50
+
51
+ ## Usage
52
+
53
+ 1. From the repo root, run **`powersync docker configure --database postgres --storage postgres`** to create **powersync/docker/**.
54
+ 2. Run **`powersync docker start`** to bring up the stack. Use **`powersync docker reset`** only when you need to start from a clean state (stop and remove, then start). Use **`powersync docker stop`** to stop.
55
+
56
+ No need to edit **.env** for default setups; the PowerSync service reads **docker/.env** via **env_file** and resolves **!env** in **service.yaml** at runtime.
57
+
58
+ ## Flags
59
+
60
+ - **`--directory`** – Config directory (default: `powersync`).
61
+ - **`--database`** – Database module for **docker configure** (e.g. `postgres`). Required for configure.
62
+ - **`--storage`** – Storage module for **docker configure** (e.g. `postgres`). Required for configure.
63
+ - **`--project-name`** – For **stop** only: Docker Compose project name (e.g. `powersync_myapp`). Default: `plugins.docker.project_name` from `cli.yaml` when run from the project directory. Use to stop from any directory or target a specific project.
64
+ - **`--api-url`** – PowerSync API URL (optional; for consistency with other self-hosted commands).
65
+
66
+ ## Building blocks
67
+
68
+ This plugin uses **@powersync/cli-core**, which provides:
69
+
70
+ - **`SelfHostedInstanceCommand`** – Base class with `loadProject()` and `parseConfig()` for project dir, link config, and **service.yaml**.
71
+ - Types: **`SelfHostedProject`**, **`SelfHostedInstanceCommandFlags`**, **`EnsureConfigOptions`**.
72
+ - **`HelpGroup`**, **`InstanceCommand`**, **`PowerSyncCommand`**.
73
+ - YAML helpers: **`parseYamlFile`**, **`parseYamlDocumentPreserveTags`**, **`stringifyYaml`** (for `!env`-aware parsing).
74
+
75
+ Import from **`@powersync/cli-core`** when authoring your own self-hosted plugins.
@@ -0,0 +1,7 @@
1
+ import { CommandHelpGroup, SelfHostedInstanceCommand } from '@powersync/cli-core';
2
+ /**
3
+ * Base command for Docker-related operations. Groups all docker subcommands under LOCAL DEVELOPMENT in the root help output.
4
+ */
5
+ export declare abstract class DockerCommand extends SelfHostedInstanceCommand {
6
+ static commandHelpGroup: CommandHelpGroup;
7
+ }
@@ -0,0 +1,7 @@
1
+ import { CommandHelpGroup, SelfHostedInstanceCommand } from '@powersync/cli-core';
2
+ /**
3
+ * Base command for Docker-related operations. Groups all docker subcommands under LOCAL DEVELOPMENT in the root help output.
4
+ */
5
+ export class DockerCommand extends SelfHostedInstanceCommand {
6
+ static commandHelpGroup = CommandHelpGroup.LOCAL_DEVELOPMENT;
7
+ }
@@ -0,0 +1,47 @@
1
+ export type DockerComposeOptions = {
2
+ projectDirectory: string;
3
+ /** Docker Compose project name (e.g. from cli.yaml plugins.docker.project_name). When set, passed as -p. */
4
+ projectName?: string;
5
+ };
6
+ /**
7
+ * Read Docker Compose project name from cli.yaml (plugins.docker.project_name). Returns undefined if missing.
8
+ */
9
+ export declare function getDockerProjectName(projectDirectory: string): string | undefined;
10
+ /**
11
+ * Resolve the compose file path: {projectDirectory}/docker/docker-compose.yaml.
12
+ */
13
+ export declare function resolveComposePath(options: DockerComposeOptions): string;
14
+ /**
15
+ * List Docker Compose project names that start with powersync_ and have running containers.
16
+ * Runs `docker compose ls -q` (no -a) so only projects with running containers are returned.
17
+ * Returns [] if the command fails or no matches.
18
+ */
19
+ export declare function listPowersyncProjectNames(): string[];
20
+ /**
21
+ * Log active PowerSync project names and how to stop them. Use after a failed reset or start.
22
+ */
23
+ export declare function logPowersyncProjectsStopHelp(command: {
24
+ log: (msg: string) => void;
25
+ }, excludeProjectName?: string): void;
26
+ /**
27
+ * Run `docker compose -p <projectName> stop`. Stops containers but does not remove them.
28
+ * Does not require a compose file or project directory.
29
+ */
30
+ export declare function runDockerComposeStop(projectName: string, execOptions?: {
31
+ stdio?: 'inherit' | 'pipe';
32
+ }): void;
33
+ /**
34
+ * Run `docker compose -p <projectName> down` (optionally with `-v` to remove volumes).
35
+ * Stops and removes containers and networks. Does not require a compose file or project directory.
36
+ */
37
+ export declare function runDockerComposeDown(projectName: string, execOptions?: {
38
+ removeVolumes?: boolean;
39
+ stdio?: 'inherit' | 'pipe';
40
+ }): void;
41
+ /**
42
+ * Run docker compose with the given args. Uses execSync; throws if the process exits non-zero.
43
+ * Runs with cwd = compose file directory so relative paths in the compose file (e.g. ..:/config) resolve correctly.
44
+ */
45
+ export declare function runDockerCompose(options: DockerComposeOptions, args: string[], execOptions?: {
46
+ stdio?: 'inherit' | 'pipe';
47
+ }): void;
@@ -0,0 +1,109 @@
1
+ import { ux } from '@oclif/core';
2
+ import { CLI_FILENAME, parseYamlDocumentPreserveTags } from '@powersync/cli-core';
3
+ import { execFileSync, execSync } from 'node:child_process';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ const COMPOSE_FILENAME = 'docker-compose.yaml';
7
+ const POWERSYNC_PROJECT_PREFIX = 'powersync_';
8
+ /**
9
+ * Read Docker Compose project name from cli.yaml (plugins.docker.project_name). Returns undefined if missing.
10
+ */
11
+ export function getDockerProjectName(projectDirectory) {
12
+ const linkPath = join(projectDirectory, CLI_FILENAME);
13
+ if (!existsSync(linkPath))
14
+ return undefined;
15
+ try {
16
+ const obj = parseYamlDocumentPreserveTags(readFileSync(linkPath, 'utf8'));
17
+ const jsonContent = obj.contents?.toJSON();
18
+ return jsonContent?.plugins?.docker?.project_name;
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /**
25
+ * Resolve the compose file path: {projectDirectory}/docker/docker-compose.yaml.
26
+ */
27
+ export function resolveComposePath(options) {
28
+ return join(options.projectDirectory, 'docker', COMPOSE_FILENAME);
29
+ }
30
+ /**
31
+ * List Docker Compose project names that start with powersync_ and have running containers.
32
+ * Runs `docker compose ls -q` (no -a) so only projects with running containers are returned.
33
+ * Returns [] if the command fails or no matches.
34
+ */
35
+ export function listPowersyncProjectNames() {
36
+ try {
37
+ const out = execSync('docker compose ls -q', {
38
+ encoding: 'utf8',
39
+ stdio: ['pipe', 'pipe', 'pipe']
40
+ });
41
+ const names = out
42
+ .split(/\r?\n/)
43
+ .map((s) => s.trim())
44
+ .filter(Boolean);
45
+ return names.filter((n) => n.startsWith(POWERSYNC_PROJECT_PREFIX));
46
+ }
47
+ catch {
48
+ return [];
49
+ }
50
+ }
51
+ /**
52
+ * Log active PowerSync project names and how to stop them. Use after a failed reset or start.
53
+ */
54
+ export function logPowersyncProjectsStopHelp(command, excludeProjectName) {
55
+ const projectNames = listPowersyncProjectNames().filter((name) => !excludeProjectName || name !== excludeProjectName);
56
+ if (projectNames.length > 0) {
57
+ command.log('');
58
+ command.log('Other PowerSync Docker project(s) that are running:');
59
+ for (const name of projectNames)
60
+ command.log(` - ${name}`);
61
+ command.log('');
62
+ command.log('To stop a project: ' + ux.colorize('blue', 'powersync docker stop --project-name=<name>'));
63
+ command.log('Example: ' + ux.colorize('blue', `powersync docker stop --project-name=${projectNames[0]}`));
64
+ }
65
+ }
66
+ /**
67
+ * Run `docker compose -p <projectName> stop`. Stops containers but does not remove them.
68
+ * Does not require a compose file or project directory.
69
+ */
70
+ export function runDockerComposeStop(projectName, execOptions) {
71
+ execFileSync('docker', ['compose', '-p', projectName, 'stop'], {
72
+ cwd: process.cwd(),
73
+ stdio: execOptions?.stdio ?? 'inherit'
74
+ });
75
+ }
76
+ /**
77
+ * Run `docker compose -p <projectName> down` (optionally with `-v` to remove volumes).
78
+ * Stops and removes containers and networks. Does not require a compose file or project directory.
79
+ */
80
+ export function runDockerComposeDown(projectName, execOptions) {
81
+ const downArgs = ['compose', '-p', projectName, 'down'];
82
+ if (execOptions?.removeVolumes) {
83
+ downArgs.push('-v');
84
+ }
85
+ execFileSync('docker', downArgs, {
86
+ cwd: process.cwd(),
87
+ stdio: execOptions?.stdio ?? 'inherit'
88
+ });
89
+ }
90
+ /**
91
+ * Run docker compose with the given args. Uses execSync; throws if the process exits non-zero.
92
+ * Runs with cwd = compose file directory so relative paths in the compose file (e.g. ..:/config) resolve correctly.
93
+ */
94
+ export function runDockerCompose(options, args, execOptions) {
95
+ const composePath = resolveComposePath(options);
96
+ if (!existsSync(composePath)) {
97
+ throw new Error(`Compose file not found: ${composePath}. Run ${ux.colorize('blue', 'powersync docker configure')} to create the docker/ compose dir.`);
98
+ }
99
+ const composeDir = dirname(composePath);
100
+ const composeArgs = ['compose'];
101
+ if (options.projectName) {
102
+ composeArgs.push('-p', options.projectName);
103
+ }
104
+ composeArgs.push('-f', composePath, ...args);
105
+ execFileSync('docker', composeArgs, {
106
+ cwd: composeDir,
107
+ stdio: execOptions?.stdio ?? 'inherit'
108
+ });
109
+ }
@@ -0,0 +1,13 @@
1
+ import { DockerCommand } from '../../DockerCommand.js';
2
+ export default class DockerConfigure extends DockerCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ database: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ storage: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ 'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
10
+ };
11
+ static summary: string;
12
+ run(): Promise<void>;
13
+ }
@@ -0,0 +1,182 @@
1
+ import { select } from '@inquirer/prompts';
2
+ import { Flags, ux } from '@oclif/core';
3
+ import { CLI_FILENAME, parseYamlDocumentPreserveTags, SERVICE_FILENAME } from '@powersync/cli-core';
4
+ import fs, { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { Document, isMap, isSeq, stringify } from 'yaml';
8
+ import { DEV_TOKEN } from '../../constants.js';
9
+ import { DockerCommand } from '../../DockerCommand.js';
10
+ import { TEMPLATES } from '../../templates/templates-index.js';
11
+ import { DockerModuleType } from '../../types.js';
12
+ const NONE_OPTION = 'none';
13
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
+ const MAIN_COMPOSE_TEMPLATE_PATH = path.join(__dirname, '../../templates/main-compose.yaml');
15
+ const DOCKER_DEV_API_URL = 'http://localhost:8080';
16
+ /**
17
+ * Docker Compose project name: [a-z0-9][a-z0-9_.-]*. Derived from the project directory name.
18
+ */
19
+ function composeProjectName(projectDirectory) {
20
+ // The project name is the directory name of the parent directory.
21
+ const raw = path.basename(path.resolve(projectDirectory, '../'));
22
+ const sanitized = raw
23
+ .toLowerCase()
24
+ .replaceAll(/[^a-z0-9_.-]+/g, '-')
25
+ .replaceAll(/-+/g, '-')
26
+ .replaceAll(/^-|-$/g, '');
27
+ return `powersync_${sanitized}`;
28
+ }
29
+ export default class DockerConfigure extends DockerCommand {
30
+ static description = [
31
+ 'Configures a self hosted project with Docker Compose services.',
32
+ 'Docker configuration is located in ./powersync/docker/.',
33
+ 'Configured projects can be started with "powersync docker start".'
34
+ ].join('\n');
35
+ static examples = [
36
+ '<%= config.bin %> <%= command.id %>',
37
+ '<%= config.bin %> <%= command.id %> --database=postgres --storage=postgres'
38
+ ];
39
+ static flags = {
40
+ ...DockerCommand.flags,
41
+ database: Flags.string({
42
+ description: 'Database module for replication source. Omit to be prompted.',
43
+ options: [...TEMPLATES[DockerModuleType.SOURCE_DATABASE].map((t) => t.name), NONE_OPTION],
44
+ required: false
45
+ }),
46
+ storage: Flags.string({
47
+ description: 'Storage module for PowerSync bucket metadata. Omit to be prompted.',
48
+ options: [...TEMPLATES[DockerModuleType.STORAGE].map((t) => t.name), NONE_OPTION],
49
+ required: false
50
+ })
51
+ };
52
+ static summary = 'Configures a self hosted project with Docker Compose services.';
53
+ async run() {
54
+ const { flags } = await this.parse(DockerConfigure);
55
+ const projectDirectory = this.ensureProjectDirectory(flags);
56
+ const targetDockerDir = path.join(projectDirectory, 'docker');
57
+ const modulesDir = path.join(targetDockerDir, 'modules');
58
+ const dockerEnvFilePath = path.join(targetDockerDir, '.env');
59
+ if (existsSync(targetDockerDir)) {
60
+ this.error(ux.colorize('red', [`Directory ${targetDockerDir} already exists.`, 'Remove it to re-configure.'].join('\n')), {
61
+ exit: 1
62
+ });
63
+ }
64
+ const databaseChoices = [
65
+ ...TEMPLATES[DockerModuleType.SOURCE_DATABASE].map((t) => ({ name: t.name, value: t.name })),
66
+ { name: 'None (do not configure)', value: NONE_OPTION }
67
+ ];
68
+ const storageChoices = [
69
+ ...TEMPLATES[DockerModuleType.STORAGE].map((t) => ({ name: t.name, value: t.name })),
70
+ { name: 'None (do not configure)', value: NONE_OPTION }
71
+ ];
72
+ let { database } = flags;
73
+ if (database === undefined) {
74
+ database = await select({
75
+ choices: databaseChoices,
76
+ message: 'Select a database module for a replication source. Use external to configure an existing database.'
77
+ });
78
+ if (database === NONE_OPTION)
79
+ database = undefined;
80
+ }
81
+ else if (database === NONE_OPTION) {
82
+ database = undefined;
83
+ }
84
+ let { storage } = flags;
85
+ if (storage === undefined) {
86
+ storage = await select({
87
+ choices: storageChoices,
88
+ message: 'Select a storage module for PowerSync bucket metadata. Use external to configure an existing database.'
89
+ });
90
+ if (storage === NONE_OPTION)
91
+ storage = undefined;
92
+ }
93
+ else if (storage === NONE_OPTION) {
94
+ storage = undefined;
95
+ }
96
+ mkdirSync(targetDockerDir, { recursive: true });
97
+ mkdirSync(modulesDir, { recursive: true });
98
+ const serviceConfigDocument = parseYamlDocumentPreserveTags(fs.readFileSync(path.join(projectDirectory, SERVICE_FILENAME), 'utf8'));
99
+ const mainComposeDocument = parseYamlDocumentPreserveTags(readFileSync(MAIN_COMPOSE_TEMPLATE_PATH, 'utf8'));
100
+ const moduleContext = {
101
+ command: this,
102
+ composeOutputDirectory: targetDockerDir,
103
+ mainComposeDocument,
104
+ modulesOutputDirectory: modulesDir,
105
+ projectDirectory,
106
+ serviceConfig: serviceConfigDocument
107
+ };
108
+ // Starting from scratch every time
109
+ let envFileContents = '';
110
+ if (database) {
111
+ const databaseTemplate = TEMPLATES[DockerModuleType.SOURCE_DATABASE].find((template) => template.type === DockerModuleType.SOURCE_DATABASE && template.name === database);
112
+ if (!databaseTemplate) {
113
+ this.error(ux.colorize('red', `Database template ${database} not found.`), { exit: 1 });
114
+ }
115
+ const databaseModuleResponse = await databaseTemplate.apply(moduleContext);
116
+ envFileContents += [
117
+ `# ${databaseTemplate.name} Database Config`,
118
+ ...Object.entries(databaseModuleResponse.additionalEnvironment ?? {}).map(([key, value]) => `${key}=${value}`)
119
+ ].join('\n');
120
+ }
121
+ if (storage) {
122
+ const storageTemplate = TEMPLATES[DockerModuleType.STORAGE].find((template) => template.type === DockerModuleType.STORAGE && template.name === storage);
123
+ if (!storageTemplate) {
124
+ this.error(`Storage template ${storage} not found.`, { exit: 1 });
125
+ }
126
+ const storageModuleResponse = await storageTemplate.apply(moduleContext);
127
+ envFileContents +=
128
+ (envFileContents ? '\n\n' : '') +
129
+ [
130
+ `# ${storageTemplate.name} Storage Config`,
131
+ ...Object.entries(storageModuleResponse.additionalEnvironment ?? {}).map(([key, value]) => `${key}=${value}`)
132
+ ].join('\n');
133
+ }
134
+ const projectName = composeProjectName(projectDirectory);
135
+ mainComposeDocument.set('name', projectName);
136
+ writeFileSync(path.join(targetDockerDir, 'docker-compose.yaml'), stringify(mainComposeDocument), 'utf8');
137
+ // Persist environment config
138
+ writeFileSync(dockerEnvFilePath, envFileContents, 'utf8');
139
+ // Set api.tokens in service.yaml for local dev (same token as in link) without clobbering existing settings.
140
+ const apiNode = serviceConfigDocument.get('api');
141
+ if (isMap(apiNode)) {
142
+ const existingTokensNode = apiNode.get('tokens');
143
+ const existingTokens = isSeq(existingTokensNode)
144
+ ? existingTokensNode.toJSON()
145
+ : Array.isArray(existingTokensNode)
146
+ ? existingTokensNode
147
+ : [];
148
+ const mergedTokens = [...new Set([DEV_TOKEN, ...existingTokens])];
149
+ apiNode.set('tokens', mergedTokens);
150
+ }
151
+ else {
152
+ serviceConfigDocument.set('api', { tokens: [DEV_TOKEN] });
153
+ }
154
+ writeFileSync(path.join(projectDirectory, SERVICE_FILENAME), stringify(serviceConfigDocument), 'utf8');
155
+ updateLinkPluginsDocker(projectDirectory, projectName);
156
+ this.log(ux.colorize('green', `Configured ${targetDockerDir}`));
157
+ this.log(ux.colorize('gray', ' - docker-compose.yaml (includes modules, adds PowerSync service)'));
158
+ this.log(ux.colorize('gray', ' - .env'));
159
+ this.log(ux.colorize('gray', ` - Merged config into ${SERVICE_FILENAME}`));
160
+ this.log(ux.colorize('gray', ` - ${CLI_FILENAME} (plugins.docker.project_name: ${projectName})`));
161
+ this.log('');
162
+ this.log(`Next: run "${ux.colorize('blue', 'powersync docker start')}" to start the stack.`);
163
+ }
164
+ }
165
+ /** Create or update cli.yaml with type: self-hosted, api_url, api_key, and plugins.docker.project_name. */
166
+ function updateLinkPluginsDocker(projectDirectory, projectName) {
167
+ const linkPath = path.join(projectDirectory, CLI_FILENAME);
168
+ const linkDocument = existsSync(linkPath)
169
+ ? parseYamlDocumentPreserveTags(readFileSync(linkPath, 'utf8'))
170
+ : new Document({});
171
+ linkDocument.set('type', 'self-hosted');
172
+ linkDocument.set('api_url', DOCKER_DEV_API_URL);
173
+ linkDocument.set('api_key', DEV_TOKEN);
174
+ const rawNode = linkDocument.get('plugins');
175
+ if (isMap(rawNode)) {
176
+ rawNode.set('docker', { project_name: projectName });
177
+ }
178
+ else {
179
+ linkDocument.set('plugins', { docker: { project_name: projectName } });
180
+ }
181
+ writeFileSync(linkPath, stringify(linkDocument), 'utf8');
182
+ }
@@ -0,0 +1,12 @@
1
+ import { DockerCommand } from '../../DockerCommand.js';
2
+ export default class Docker extends DockerCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ 'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
8
+ };
9
+ static hidden: boolean;
10
+ static summary: string;
11
+ run(): Promise<void>;
12
+ }
@@ -0,0 +1,13 @@
1
+ import { DockerCommand } from '../../DockerCommand.js';
2
+ export default class Docker extends DockerCommand {
3
+ static description = 'Scaffold and run a self-hosted PowerSync stack via Docker. Use `docker configure` to create powersync/docker/, then `docker reset` (stop+remove then start) or `docker start` / `docker stop`.';
4
+ static examples = ['<%= config.bin %> <%= command.id %>'];
5
+ static flags = {
6
+ ...DockerCommand.flags
7
+ };
8
+ static hidden = true;
9
+ static summary = '[Self-hosted only] Manage self-hosted PowerSync with Docker Compose (configure, reset, start, stop).';
10
+ async run() {
11
+ await this.config.runCommand('help', ['docker']);
12
+ }
13
+ }
@@ -0,0 +1,11 @@
1
+ import { DockerCommand } from '../../DockerCommand.js';
2
+ export default class DockerReset extends DockerCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ 'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
8
+ };
9
+ static summary: string;
10
+ run(): Promise<void>;
11
+ }
@@ -0,0 +1,37 @@
1
+ import { ux } from '@oclif/core';
2
+ import { getDockerProjectName, logPowersyncProjectsStopHelp, runDockerCompose, runDockerComposeDown } from '../../docker.js';
3
+ import { DockerCommand } from '../../DockerCommand.js';
4
+ export default class DockerReset extends DockerCommand {
5
+ static description = 'Run `docker compose down` then `docker compose up -d --wait`: stops and removes containers, then starts the stack and waits for services (including PowerSync) to be healthy. Use when you want a clean bring-up (e.g. after config changes). Use `powersync status` to debug running instances.';
6
+ static examples = ['<%= config.bin %> <%= command.id %>'];
7
+ static flags = {
8
+ ...DockerCommand.flags
9
+ };
10
+ static summary = 'Reset the self-hosted PowerSync stack (stop and remove, then start).';
11
+ async run() {
12
+ const { flags } = await this.parse(DockerReset);
13
+ const { projectDirectory } = this.loadProject(flags, {
14
+ configFileRequired: true
15
+ });
16
+ const projectName = getDockerProjectName(projectDirectory);
17
+ const opts = { projectDirectory, projectName };
18
+ if (projectName) {
19
+ this.log('Stopping and removing containers...');
20
+ try {
21
+ runDockerComposeDown(projectName, { stdio: 'inherit' });
22
+ }
23
+ catch {
24
+ // down can fail if no containers exist; continue to up
25
+ }
26
+ }
27
+ this.log('Starting containers...');
28
+ try {
29
+ runDockerCompose(opts, ['up', '-d', '--wait']);
30
+ }
31
+ catch (error) {
32
+ logPowersyncProjectsStopHelp(this, opts.projectName);
33
+ throw error;
34
+ }
35
+ this.log(`\n\nTip: use "${ux.colorize('blue', 'powersync status')}" to debug the running instance.`);
36
+ }
37
+ }
@@ -0,0 +1,11 @@
1
+ import { DockerCommand } from '../../DockerCommand.js';
2
+ export default class DockerStart extends DockerCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ 'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
8
+ };
9
+ static summary: string;
10
+ run(): Promise<void>;
11
+ }
@@ -0,0 +1,26 @@
1
+ import { ux } from '@oclif/core';
2
+ import { getDockerProjectName, logPowersyncProjectsStopHelp, runDockerCompose } from '../../docker.js';
3
+ import { DockerCommand } from '../../DockerCommand.js';
4
+ export default class DockerStart extends DockerCommand {
5
+ static description = 'Runs `docker compose up -d --wait` for the project docker/ compose file; waits for services (including PowerSync) to be healthy. Use `powersync status` to debug running instances.';
6
+ static examples = ['<%= config.bin %> <%= command.id %>'];
7
+ static flags = {
8
+ ...DockerCommand.flags
9
+ };
10
+ static summary = 'Start the self-hosted PowerSync stack via Docker Compose.';
11
+ async run() {
12
+ const { flags } = await this.parse(DockerStart);
13
+ const { projectDirectory } = this.loadProject(flags, {
14
+ configFileRequired: true
15
+ });
16
+ const projectName = getDockerProjectName(projectDirectory);
17
+ try {
18
+ runDockerCompose({ projectDirectory, projectName }, ['up', '-d', '--wait']);
19
+ }
20
+ catch (error) {
21
+ logPowersyncProjectsStopHelp(this, projectName);
22
+ throw error;
23
+ }
24
+ this.log(`\n\nTip: use "${ux.colorize('blue', 'powersync status')}" to debug the running instance.`);
25
+ }
26
+ }
@@ -0,0 +1,14 @@
1
+ import { DockerCommand } from '../../DockerCommand.js';
2
+ export default class DockerStop extends DockerCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ 'project-name': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ remove: import("@oclif/core/interfaces").BooleanFlag<boolean>;
8
+ 'remove-volumes': import("@oclif/core/interfaces").BooleanFlag<boolean>;
9
+ 'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
11
+ };
12
+ static summary: string;
13
+ run(): Promise<void>;
14
+ }