powersync 0.7.1 → 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 (133) hide show
  1. package/LICENSE +67 -0
  2. package/README.md +1376 -165
  3. package/bin/dev.cmd +3 -3
  4. package/bin/dev.js +20 -7
  5. package/bin/run.cmd +3 -3
  6. package/bin/run.js +9 -5
  7. package/dist/api/cloud/create-cloud-instance.d.ts +15 -0
  8. package/dist/api/cloud/create-cloud-instance.js +19 -0
  9. package/dist/api/cloud/fetch-cloud-config.d.ts +12 -0
  10. package/dist/api/cloud/fetch-cloud-config.js +18 -0
  11. package/dist/api/cloud/fetch-cloud-sync-rules-content.d.ts +7 -0
  12. package/dist/api/cloud/fetch-cloud-sync-rules-content.js +26 -0
  13. package/dist/api/cloud/test-connection.d.ts +16 -0
  14. package/dist/api/cloud/test-connection.js +36 -0
  15. package/dist/api/cloud/validate-cloud-link-config.d.ts +17 -0
  16. package/dist/api/cloud/validate-cloud-link-config.js +47 -0
  17. package/dist/api/cloud/wait-for-operation.d.ts +16 -0
  18. package/dist/api/cloud/wait-for-operation.js +33 -0
  19. package/dist/api/cloud/write-cloud-link.d.ts +10 -0
  20. package/dist/api/cloud/write-cloud-link.js +21 -0
  21. package/dist/api/display-status.d.ts +4 -0
  22. package/dist/api/display-status.js +80 -0
  23. package/dist/api/ide/configure-vscode-ide.d.ts +14 -0
  24. package/dist/api/ide/configure-vscode-ide.js +62 -0
  25. package/dist/api/login-server.d.ts +26 -0
  26. package/dist/api/login-server.js +137 -0
  27. package/dist/api/run-validation-tests.d.ts +63 -0
  28. package/dist/api/run-validation-tests.js +202 -0
  29. package/dist/api/self-hosted/fetch-self-hosted-sync-rules-content.d.ts +7 -0
  30. package/dist/api/self-hosted/fetch-self-hosted-sync-rules-content.js +26 -0
  31. package/dist/commands/configure/ide.d.ts +8 -0
  32. package/dist/commands/configure/ide.js +58 -0
  33. package/dist/commands/configure/index.d.ts +8 -0
  34. package/dist/commands/configure/index.js +11 -0
  35. package/dist/commands/deploy/index.d.ts +48 -0
  36. package/dist/commands/deploy/index.js +333 -0
  37. package/dist/commands/deploy/service-config.d.ts +14 -0
  38. package/dist/commands/deploy/service-config.js +30 -0
  39. package/dist/commands/deploy/sync-config.d.ts +24 -0
  40. package/dist/commands/deploy/sync-config.js +103 -0
  41. package/dist/commands/destroy.d.ts +14 -0
  42. package/dist/commands/destroy.js +62 -0
  43. package/dist/commands/fetch/config.d.ts +14 -0
  44. package/dist/commands/fetch/config.js +33 -0
  45. package/dist/commands/fetch/index.d.ts +13 -0
  46. package/dist/commands/fetch/index.js +16 -0
  47. package/dist/commands/fetch/instances.d.ts +47 -0
  48. package/dist/commands/fetch/instances.js +177 -0
  49. package/dist/commands/fetch/status.d.ts +18 -0
  50. package/dist/commands/fetch/status.js +60 -0
  51. package/dist/commands/{instance/schema.d.ts → generate/index.d.ts} +3 -1
  52. package/dist/commands/generate/index.js +11 -0
  53. package/dist/commands/generate/schema.d.ts +19 -0
  54. package/dist/commands/generate/schema.js +72 -0
  55. package/dist/commands/generate/token.d.ts +25 -0
  56. package/dist/commands/generate/token.js +124 -0
  57. package/dist/commands/init/cloud.d.ts +11 -0
  58. package/dist/commands/init/cloud.js +64 -0
  59. package/dist/commands/{init.d.ts → init/index.d.ts} +2 -1
  60. package/dist/commands/init/index.js +11 -0
  61. package/dist/commands/init/self-hosted.d.ts +11 -0
  62. package/dist/commands/init/self-hosted.js +60 -0
  63. package/dist/commands/link/cloud.d.ts +15 -0
  64. package/dist/commands/link/cloud.js +111 -0
  65. package/dist/commands/{instance/config.d.ts → link/index.d.ts} +3 -1
  66. package/dist/commands/link/index.js +11 -0
  67. package/dist/commands/link/self-hosted.d.ts +12 -0
  68. package/dist/commands/link/self-hosted.js +54 -0
  69. package/dist/commands/login.d.ts +8 -0
  70. package/dist/commands/login.js +107 -0
  71. package/dist/commands/logout.d.ts +8 -0
  72. package/dist/commands/logout.js +19 -0
  73. package/dist/commands/migrate/index.d.ts +7 -0
  74. package/dist/commands/migrate/index.js +10 -0
  75. package/dist/commands/migrate/sync-rules.d.ts +15 -0
  76. package/dist/commands/migrate/sync-rules.js +51 -0
  77. package/dist/commands/{instances.d.ts → pull/index.d.ts} +3 -1
  78. package/dist/commands/pull/index.js +11 -0
  79. package/dist/commands/pull/instance.d.ts +14 -0
  80. package/dist/commands/pull/instance.js +108 -0
  81. package/dist/commands/status.d.ts +1 -0
  82. package/dist/commands/status.js +2 -0
  83. package/dist/commands/stop.d.ts +14 -0
  84. package/dist/commands/stop.js +62 -0
  85. package/dist/commands/validate.d.ts +16 -0
  86. package/dist/commands/validate.js +165 -0
  87. package/dist/help.d.ts +31 -0
  88. package/dist/help.js +123 -0
  89. package/oclif.manifest.json +1250 -275
  90. package/package.json +104 -75
  91. package/templates/cloud/powersync/cli.yaml +3 -0
  92. package/templates/cloud/powersync/service.yaml +174 -0
  93. package/templates/cloud/powersync/sync-config.yaml +22 -0
  94. package/templates/self-hosted/base/powersync/cli.yaml +3 -0
  95. package/templates/self-hosted/base/powersync/service.yaml +243 -0
  96. package/templates/self-hosted/base/powersync/sync-config.yaml +22 -0
  97. package/templates/vscode/settings.json +3 -0
  98. package/dist/commands/init.js +0 -66
  99. package/dist/commands/instance/config.js +0 -23
  100. package/dist/commands/instance/create.d.ts +0 -20
  101. package/dist/commands/instance/create.js +0 -121
  102. package/dist/commands/instance/deploy.d.ts +0 -18
  103. package/dist/commands/instance/deploy.js +0 -91
  104. package/dist/commands/instance/destroy.d.ts +0 -9
  105. package/dist/commands/instance/destroy.js +0 -46
  106. package/dist/commands/instance/generate-dev-token.d.ts +0 -10
  107. package/dist/commands/instance/generate-dev-token.js +0 -54
  108. package/dist/commands/instance/schema.js +0 -20
  109. package/dist/commands/instance/set.d.ts +0 -9
  110. package/dist/commands/instance/set.js +0 -31
  111. package/dist/commands/instance/status.d.ts +0 -12
  112. package/dist/commands/instance/status.js +0 -50
  113. package/dist/commands/instance/stop.d.ts +0 -9
  114. package/dist/commands/instance/stop.js +0 -42
  115. package/dist/commands/instance/sync-rules/deploy.d.ts +0 -10
  116. package/dist/commands/instance/sync-rules/deploy.js +0 -49
  117. package/dist/commands/instance/sync-rules/generate-schema.d.ts +0 -10
  118. package/dist/commands/instance/sync-rules/generate-schema.js +0 -56
  119. package/dist/commands/instance/sync-rules/validate.d.ts +0 -9
  120. package/dist/commands/instance/sync-rules/validate.js +0 -29
  121. package/dist/commands/instances.js +0 -29
  122. package/dist/commands.utils.d.ts +0 -2
  123. package/dist/commands.utils.js +0 -92
  124. package/dist/constants.d.ts +0 -8
  125. package/dist/constants.js +0 -10
  126. package/dist/instance-command-flags.d.ts +0 -12
  127. package/dist/instance-command-flags.js +0 -13
  128. package/dist/service/accounts.client.js +0 -11307
  129. package/dist/service/powersync.client.js +0 -75510
  130. package/dist/service/types.js +0 -1
  131. package/dist/service/utils.js +0 -153
  132. package/dist/utils.d.ts +0 -14
  133. package/dist/utils.js +0 -68
@@ -0,0 +1,14 @@
1
+ import { CloudInstanceCommand, CommandHelpGroup } from '@powersync/cli-core';
2
+ export default class PullInstance extends CloudInstanceCommand {
3
+ static commandHelpGroup: CommandHelpGroup;
4
+ static description: string;
5
+ static examples: string[];
6
+ static flags: {
7
+ 'instance-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ 'org-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ 'project-id': 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
+ }
@@ -0,0 +1,108 @@
1
+ import { ux } from '@oclif/core';
2
+ import { CLI_FILENAME, CloudInstanceCommand, CommandHelpGroup, ensureServiceTypeMatches, getDefaultOrgId, SERVICE_FILENAME, ServiceType, SYNC_FILENAME } from '@powersync/cli-core';
3
+ import { ServiceCloudConfig } from '@powersync/cli-schemas';
4
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { stringify } from 'yaml';
7
+ import { decodeFetchedCloudConfig } from '../../api/cloud/fetch-cloud-config.js';
8
+ import { validateCloudLinkConfig } from '../../api/cloud/validate-cloud-link-config.js';
9
+ import { writeCloudLink } from '../../api/cloud/write-cloud-link.js';
10
+ const SERVICE_FETCHED_FILENAME = 'service-fetched.yaml';
11
+ const SYNC_FETCHED_FILENAME = 'sync-fetched.yaml';
12
+ const PULL_CONFIG_HEADER = `# PowerSync Cloud config (fetched from cloud)
13
+ # yaml-language-server: $schema=https://unpkg.com/@powersync/cli-schemas@latest/json-schema/service-config.json
14
+ #
15
+ `;
16
+ export default class PullInstance extends CloudInstanceCommand {
17
+ static commandHelpGroup = CommandHelpGroup.PROJECT_SETUP;
18
+ static description = 'Fetch an existing Cloud instance by ID: create the config directory if needed, write cli.yaml, and download service.yaml and sync-config.yaml. Pass --instance-id and --project-id when the directory is not yet linked; --org-id is optional when the token has a single organization. Cloud only.';
19
+ static examples = [
20
+ '<%= config.bin %> <%= command.id %>',
21
+ '<%= config.bin %> <%= command.id %> --instance-id=<id> --project-id=<id>',
22
+ '<%= config.bin %> <%= command.id %> --instance-id=<id> --project-id=<id> --org-id=<org-id>'
23
+ ];
24
+ static flags = {
25
+ ...CloudInstanceCommand.flags
26
+ };
27
+ static summary = '[Cloud only] Pull an existing Cloud instance: link and download config into local service.yaml and sync-config.yaml.';
28
+ async run() {
29
+ const { flags } = await this.parse(PullInstance);
30
+ const { directory, 'instance-id': instanceId, 'org-id': _orgId, 'project-id': projectId } = flags;
31
+ const resolvedOrgId = _orgId ?? (await getDefaultOrgId().catch(() => null));
32
+ /**
33
+ * The pull instance command can be used to create a new powersync project directory
34
+ */
35
+ const projectDir = this.resolveProjectDir(flags);
36
+ if (!existsSync(projectDir)) {
37
+ if (instanceId && resolvedOrgId && projectId) {
38
+ mkdirSync(projectDir, { recursive: true });
39
+ }
40
+ else {
41
+ this.styledError({
42
+ message: `Directory "${directory}" not found. Pass --instance-id, and --project-id to create the config directory and link, or run this command from a directory that already contains a linked PowerSync config.`
43
+ });
44
+ }
45
+ }
46
+ ensureServiceTypeMatches({
47
+ command: this,
48
+ configRequired: false,
49
+ directoryLabel: directory,
50
+ expectedType: ServiceType.CLOUD,
51
+ projectDir
52
+ });
53
+ const linkPath = join(projectDir, CLI_FILENAME);
54
+ if (!existsSync(linkPath)) {
55
+ if (!instanceId || !resolvedOrgId || !projectId) {
56
+ this.styledError({
57
+ message: `Linking is required. Pass --instance-id, --org-id, and --project-id to this command, or run ${ux.colorize('blue', 'powersync link cloud --instance-id=<id> --org-id=<id> --project-id=<id>')} first.`
58
+ });
59
+ }
60
+ writeCloudLink(projectDir, { instanceId, orgId: resolvedOrgId, projectId });
61
+ this.log(`Created ${ux.colorize('blue', `${directory}/${CLI_FILENAME}`)} with Cloud instance link.`);
62
+ }
63
+ const { linked } = await this.loadProject(flags);
64
+ let instanceConfig;
65
+ try {
66
+ const validationResult = await validateCloudLinkConfig({
67
+ cloudClient: this.client,
68
+ input: {
69
+ instanceId: linked.instance_id,
70
+ orgId: linked.org_id,
71
+ projectId: linked.project_id
72
+ },
73
+ validateInstance: true
74
+ });
75
+ instanceConfig = validationResult.instanceConfig;
76
+ }
77
+ catch (error) {
78
+ this.styledError({ message: error instanceof Error ? error.message : String(error) });
79
+ }
80
+ if (!instanceConfig) {
81
+ this.styledError({
82
+ message: `Instance ${linked.instance_id} was not found in project ${linked.project_id} in organization ${linked.org_id}, or is not accessible with the current token.`
83
+ });
84
+ }
85
+ this.log(`Fetching config for instance ${ux.colorize('blue', linked.instance_id)} in project ${ux.colorize('blue', linked.project_id)} in org ${ux.colorize('blue', linked.org_id)}...`);
86
+ const fetched = decodeFetchedCloudConfig(instanceConfig);
87
+ const serviceExists = existsSync(join(projectDir, SERVICE_FILENAME));
88
+ const syncExists = existsSync(join(projectDir, SYNC_FILENAME));
89
+ if (serviceExists) {
90
+ this.warn(`${ux.colorize('blue', SERVICE_FILENAME)} already exists. Writing to ${ux.colorize('blue', 'service-fetched.yaml')} instead. Manually merge the settings into ${ux.colorize('blue', SERVICE_FILENAME)} as needed.`);
91
+ }
92
+ if (syncExists && fetched.syncRules) {
93
+ this.warn(`${ux.colorize('blue', SYNC_FILENAME)} already exists. Writing to ${ux.colorize('blue', 'sync-fetched.yaml')} instead. Manually merge the sync config into ${ux.colorize('blue', SYNC_FILENAME)} as needed.`);
94
+ }
95
+ const serviceYaml = PULL_CONFIG_HEADER + stringify(ServiceCloudConfig.encode(fetched.config));
96
+ const serviceOutputName = serviceExists ? SERVICE_FETCHED_FILENAME : SERVICE_FILENAME;
97
+ const serviceOutputPath = join(projectDir, serviceOutputName);
98
+ this.log('');
99
+ writeFileSync(serviceOutputPath, serviceYaml, 'utf8');
100
+ this.log(`Wrote ${ux.colorize('blue', serviceOutputName)} with config from the cloud.`);
101
+ if (typeof fetched.syncRules === 'string') {
102
+ const syncOutputName = syncExists ? SYNC_FETCHED_FILENAME : SYNC_FILENAME;
103
+ const syncOutputPath = join(projectDir, syncOutputName);
104
+ writeFileSync(syncOutputPath, fetched.syncRules, 'utf8');
105
+ this.log(`Wrote ${ux.colorize('blue', syncOutputName)} with sync config from the cloud.`);
106
+ }
107
+ }
108
+ }
@@ -0,0 +1 @@
1
+ export { default } from './fetch/status.js';
@@ -0,0 +1,2 @@
1
+ // powersync status is an alias of powersync fetch status, so we can reuse the implementation and tests for fetch status. This file exists mainly to provide a more intuitive command for users to check the status of their instance.
2
+ export { default } from './fetch/status.js';
@@ -0,0 +1,14 @@
1
+ import { CloudInstanceCommand } from '@powersync/cli-core';
2
+ export default class Stop extends CloudInstanceCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ 'instance-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ 'org-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ 'project-id': 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
+ confirm: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ };
12
+ static summary: string;
13
+ run(): Promise<void>;
14
+ }
@@ -0,0 +1,62 @@
1
+ import { Flags, ux } from '@oclif/core';
2
+ import { CloudInstanceCommand } from '@powersync/cli-core';
3
+ import ora from 'ora';
4
+ import { waitForOperationStatusChange } from '../api/cloud/wait-for-operation.js';
5
+ export default class Stop extends CloudInstanceCommand {
6
+ static description = 'Deactivate the linked PowerSync Cloud instance. Requires --confirm=yes. Restart later with powersync deploy.';
7
+ static examples = ['<%= config.bin %> <%= command.id %>', '<%= config.bin %> <%= command.id %> --confirm=yes'];
8
+ static flags = {
9
+ confirm: Flags.string({
10
+ description: 'Set to "yes" to confirm stopping the instance.',
11
+ options: ['yes']
12
+ }),
13
+ ...CloudInstanceCommand.flags
14
+ };
15
+ static summary = '[Cloud only] Stop the linked Cloud instance (restart with deploy).';
16
+ async run() {
17
+ const { flags } = await this.parse(Stop);
18
+ if (flags.confirm !== 'yes') {
19
+ this.styledError({ message: 'Stopping requires confirmation. Run with --confirm=yes to confirm.' });
20
+ }
21
+ const { linked } = await this.loadProject(flags);
22
+ const { client } = this;
23
+ const spinner = ora({
24
+ discardStdin: false,
25
+ prefixText: `\nStopping instance ${ux.colorize('blue', linked.instance_id)} in project ${ux.colorize('blue', linked.project_id)} in org ${ux.colorize('blue', linked.org_id)}\n`,
26
+ spinner: 'moon',
27
+ suffixText: '\nThis may take a few minutes.\n'
28
+ });
29
+ spinner.start();
30
+ try {
31
+ const stopResult = await client.deactivateInstance({
32
+ app_id: linked.project_id,
33
+ id: linked.instance_id,
34
+ org_id: linked.org_id
35
+ });
36
+ const status = await waitForOperationStatusChange({
37
+ client,
38
+ instanceId: linked.instance_id,
39
+ linked,
40
+ operationId: stopResult.operation_id,
41
+ timeoutMs: 10 * 60 * 1000 // Stopping may take longer than deploying, so use a longer timeout
42
+ });
43
+ spinner.stop();
44
+ if (status === 'completed') {
45
+ this.log(ux.colorize('green', 'Instance stopped successfully.'));
46
+ }
47
+ else {
48
+ this.styledError({
49
+ message: `Operation failed. Check instance diagnostics for details, for example: ${ux.colorize('blue', 'powersync status')}`
50
+ });
51
+ }
52
+ }
53
+ catch (error) {
54
+ spinner.stop();
55
+ this.styledError({
56
+ error,
57
+ message: `Failed to stop instance ${linked.instance_id} in project ${linked.project_id} in org ${linked.org_id}`,
58
+ suggestions: ['Check your network connection and try again.', 'If the problem persists, contact support.']
59
+ });
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,16 @@
1
+ import { CloudProject, SharedInstanceCommand, ValidationTestRunResult } from '@powersync/cli-core';
2
+ export default class Validate extends SharedInstanceCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
7
+ 'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ 'instance-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ 'org-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ 'project-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ output: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
12
+ };
13
+ static summary: string;
14
+ run(): Promise<void>;
15
+ runConnectionTestCloud(project: CloudProject): Promise<ValidationTestRunResult>;
16
+ }
@@ -0,0 +1,165 @@
1
+ import { Flags, ux } from '@oclif/core';
2
+ import { createCloudClient, SharedInstanceCommand } from '@powersync/cli-core';
3
+ import ora from 'ora';
4
+ import { testCloudConnections } from '../api/cloud/test-connection.js';
5
+ import { BULLET, formatOraMessage, formatValidationHuman, formatValidationJson, formatValidationYaml, INDENT, renderWarningForHumanOutput, runConfigTest, runSyncRulesTestCloud, runSyncRulesTestSelfHosted, Tests } from '../api/run-validation-tests.js';
6
+ export default class Validate extends SharedInstanceCommand {
7
+ static description = 'Run validation checks on local config: config schema, database connections, and sync config. Requires a linked instance. Works with Cloud and self-hosted.';
8
+ static examples = [
9
+ '<%= config.bin %> <%= command.id %>',
10
+ '<%= config.bin %> <%= command.id %> --output=json',
11
+ '<%= config.bin %> <%= command.id %> --api-url=https://powersync.example.com'
12
+ ];
13
+ static flags = {
14
+ output: Flags.string({
15
+ default: 'human',
16
+ description: 'Output format: human-readable, json, or yaml.',
17
+ options: ['human', 'json', 'yaml']
18
+ }),
19
+ ...SharedInstanceCommand.flags
20
+ };
21
+ static summary = 'Validate config schema, connections, and sync config before deploy.';
22
+ async run() {
23
+ const { flags } = await this.parse(Validate);
24
+ const project = await this.loadProject(flags, {
25
+ configFileRequired: true
26
+ });
27
+ const isCloud = project.linked.type === 'cloud';
28
+ const testDefs = [
29
+ { name: Tests.CONFIGURATION_SCHEMA, run: () => runConfigTest(project.projectDirectory, isCloud) },
30
+ ...(isCloud
31
+ ? [
32
+ { name: Tests.TEST_CONNECTIONS, run: () => this.runConnectionTestCloud(project) },
33
+ {
34
+ name: Tests.SYNC_RULES,
35
+ async run() {
36
+ // We can only validate sync rules against a provisioned instance, so ensure that's the case before running the test.
37
+ const client = createCloudClient();
38
+ const cloudProject = project;
39
+ const status = await client.getInstanceStatus({
40
+ app_id: cloudProject.linked.project_id,
41
+ id: cloudProject.linked.instance_id,
42
+ org_id: cloudProject.linked.org_id
43
+ });
44
+ if (!status.provisioned) {
45
+ return {
46
+ errors: [
47
+ `Linked instance is not provisioned. Sync config validation requires a provisioned instance.`,
48
+ `Deploy the instance, with ${ux.colorize('blue', 'powersync deploy')}, before validating sync config.`
49
+ ],
50
+ passed: false
51
+ };
52
+ }
53
+ return runSyncRulesTestCloud(project);
54
+ }
55
+ }
56
+ ]
57
+ : [{ name: Tests.SYNC_RULES, run: () => runSyncRulesTestSelfHosted(project) }])
58
+ ];
59
+ const testEntries = testDefs.map((def) => ({
60
+ name: def.name,
61
+ promise: def.run()
62
+ }));
63
+ let result;
64
+ switch (flags.output) {
65
+ case 'human': {
66
+ this.log('Running validation tests...');
67
+ const spinner = ora({ discardStdin: false, text: formatOraMessage(testEntries) }).start();
68
+ const promises = testEntries.map((entry, i) => entry.promise
69
+ .then((res) => {
70
+ testEntries[i].result = res;
71
+ return res;
72
+ })
73
+ .catch((error) => {
74
+ // Capture the failure so the spinner can complete and we can report all results together.
75
+ testEntries[i].result = { errors: [String(error)], passed: false };
76
+ return testEntries[i].result;
77
+ })
78
+ .finally(() => {
79
+ spinner.text = formatOraMessage(testEntries);
80
+ }));
81
+ await Promise.all(promises);
82
+ const tests = testEntries.map((e) => ({ name: e.name, ...e.result }));
83
+ result = { passed: tests.every((t) => t.passed), tests };
84
+ spinner.stop();
85
+ this.log(result.passed
86
+ ? ux.colorize('green', 'All validation tests passed.')
87
+ : ux.colorize('red', 'Some validation tests failed:\n'));
88
+ for (const test of result.tests) {
89
+ const status = test.passed ? '✓' : '✗';
90
+ this.log(`${status} ${ux.colorize('blue', test.name)}`);
91
+ const warnings = test.warnings ?? [];
92
+ for (const [index, warning] of warnings.entries()) {
93
+ const warningLines = renderWarningForHumanOutput(warning);
94
+ for (const line of warningLines) {
95
+ this.log(line);
96
+ }
97
+ if (index < warnings.length - 1) {
98
+ this.log('');
99
+ }
100
+ }
101
+ for (const error of test.errors ?? []) {
102
+ this.log(ux.colorize('red', `${INDENT}${BULLET} ${error}`));
103
+ }
104
+ if ((test.warnings?.length ?? 0) > 0 || (test.errors?.length ?? 0) > 0) {
105
+ this.log('');
106
+ }
107
+ }
108
+ break;
109
+ }
110
+ case 'json': {
111
+ const runResults = await Promise.all(testEntries.map((e) => e.promise.catch((error) => ({ errors: [String(error)], passed: false }))));
112
+ const tests = testEntries.map((e, i) => ({ name: e.name, ...runResults[i] }));
113
+ result = { passed: tests.every((t) => t.passed), tests };
114
+ this.log(formatValidationJson(result));
115
+ break;
116
+ }
117
+ case 'yaml': {
118
+ const runResults = await Promise.all(testEntries.map((e) => e.promise.catch((error) => ({ errors: [String(error)], passed: false }))));
119
+ const tests = testEntries.map((e, i) => ({ name: e.name, ...runResults[i] }));
120
+ result = { passed: tests.every((t) => t.passed), tests };
121
+ this.log(formatValidationYaml(result));
122
+ break;
123
+ }
124
+ default: {
125
+ const runResults = await Promise.all(testEntries.map((e) => e.promise.catch((error) => ({ errors: [String(error)], passed: false }))));
126
+ const tests = testEntries.map((e, i) => ({ name: e.name, ...runResults[i] }));
127
+ result = { passed: tests.every((t) => t.passed), tests };
128
+ this.log(formatValidationHuman(result));
129
+ }
130
+ }
131
+ if (!result.passed) {
132
+ this.exit(1);
133
+ }
134
+ }
135
+ async runConnectionTestCloud(project) {
136
+ const client = createCloudClient();
137
+ let config;
138
+ try {
139
+ config = this.parseCloudConfig(project.projectDirectory);
140
+ }
141
+ catch (error) {
142
+ return {
143
+ errors: [`Could not parse config: ${error}`],
144
+ passed: false
145
+ };
146
+ }
147
+ const connections = config.replication?.connections ?? [];
148
+ if (connections.length === 0) {
149
+ return { errors: ['No connections defined in config.'], passed: false };
150
+ }
151
+ try {
152
+ const results = await testCloudConnections(client, project.linked, connections);
153
+ const failed = results.filter((r) => r.response.success !== true);
154
+ if (failed.length === 0) {
155
+ return { passed: true };
156
+ }
157
+ const errors = failed.map((f) => `${f.connectionName}: ${f.response.error ?? 'Connection test failed'}`);
158
+ return { errors, passed: false };
159
+ }
160
+ catch (error) {
161
+ const message = error instanceof Error ? error.message : String(error);
162
+ return { errors: [message], passed: false };
163
+ }
164
+ }
165
+ }
package/dist/help.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { Help } from '@oclif/core';
2
+ /**
3
+ * Custom help implementation for the `powersync help` and `powersync --help` commands.
4
+ *
5
+ * This override:
6
+ * - Displays a flat list of commands at the root level instead of nested topic trees.
7
+ * - Formats command IDs using the configured `topicSeparator` (for example, "deploy:instance" → "deploy instance"
8
+ * when the separator is a space).
9
+ * - Groups commands into sections defined by the `commandHelpGroup` static property on each command class.
10
+ * Commands without a `commandHelpGroup` are shown under ADDITIONAL COMMANDS.
11
+ */
12
+ export default class PowerSyncHelp extends Help {
13
+ protected commandRows(commands: typeof this.sortedCommands, idPadding: number): [string, string | undefined][];
14
+ /**
15
+ * Commands IDs use a `:` separator, but we allow ` ` spaces.
16
+ * This method converts command IDs to the display format based on the config topicSeparator (e.g. "deploy:instance" → "deploy instance" if topicSeparator is " ").
17
+ */
18
+ protected displayId(commandId: string): string;
19
+ /**
20
+ * Formats a section of commands for display in the help output.
21
+ * Groups commands by their top-level key and renders them with proper indentation and spacing.
22
+ */
23
+ protected formatCommandsSection(title: string, commands: typeof this.sortedCommands): string;
24
+ /**
25
+ * Commands are grouped by the first segment of their ID (e.g. "deploy" for "deploy:instance", "deploy:service-config", etc.)
26
+ * to create a flat command list at the root level, while still allowing for nested commands.
27
+ */
28
+ protected groupKeyForCommand(commandId: string): string;
29
+ protected renderCommandsBody(commands: typeof this.sortedCommands, idPadding: number): string;
30
+ protected showRootHelp(): Promise<void>;
31
+ }
package/dist/help.js ADDED
@@ -0,0 +1,123 @@
1
+ import { Help } from '@oclif/core';
2
+ import { CommandHelpGroup } from '@powersync/cli-core';
3
+ /** Order in which sections appear in the root help output. */
4
+ const SECTION_ORDER = [
5
+ CommandHelpGroup.AUTHENTICATION,
6
+ CommandHelpGroup.PROJECT_SETUP,
7
+ CommandHelpGroup.CLOUD,
8
+ CommandHelpGroup.INSTANCE,
9
+ CommandHelpGroup.LOCAL_DEVELOPMENT,
10
+ CommandHelpGroup.ADDITIONAL
11
+ ];
12
+ /**
13
+ * Custom help implementation for the `powersync help` and `powersync --help` commands.
14
+ *
15
+ * This override:
16
+ * - Displays a flat list of commands at the root level instead of nested topic trees.
17
+ * - Formats command IDs using the configured `topicSeparator` (for example, "deploy:instance" → "deploy instance"
18
+ * when the separator is a space).
19
+ * - Groups commands into sections defined by the `commandHelpGroup` static property on each command class.
20
+ * Commands without a `commandHelpGroup` are shown under ADDITIONAL COMMANDS.
21
+ */
22
+ export default class PowerSyncHelp extends Help {
23
+ commandRows(commands, idPadding) {
24
+ return commands
25
+ .filter((command) => (this.opts.hideAliasesFromRoot ? !command.aliases?.includes(command.id) : true))
26
+ .map((command) => {
27
+ const id = this.displayId(command.id);
28
+ // Strip type prefixes (e.g. "[Cloud only]", "[Self-hosted only]") since the section grouping already conveys this.
29
+ const summary = this.summary(command)?.replace(/^\[(Cloud|Self-hosted) only\]\s*/i, '');
30
+ // We add some padding to align the command name to the description
31
+ return [id.padEnd(idPadding), summary];
32
+ });
33
+ }
34
+ /**
35
+ * Commands IDs use a `:` separator, but we allow ` ` spaces.
36
+ * This method converts command IDs to the display format based on the config topicSeparator (e.g. "deploy:instance" → "deploy instance" if topicSeparator is " ").
37
+ */
38
+ displayId(commandId) {
39
+ if (this.config.topicSeparator === ':') {
40
+ return commandId;
41
+ }
42
+ return commandId.replaceAll(':', this.config.topicSeparator);
43
+ }
44
+ /**
45
+ * Formats a section of commands for display in the help output.
46
+ * Groups commands by their top-level key and renders them with proper indentation and spacing.
47
+ */
48
+ formatCommandsSection(title, commands) {
49
+ const groupedCommands = [];
50
+ let currentGroup = [];
51
+ let currentKey;
52
+ for (const command of commands) {
53
+ const key = this.groupKeyForCommand(command.id);
54
+ if (currentKey === undefined || key === currentKey) {
55
+ currentGroup.push(command);
56
+ currentKey = key;
57
+ continue;
58
+ }
59
+ groupedCommands.push(currentGroup);
60
+ currentGroup = [command];
61
+ currentKey = key;
62
+ }
63
+ if (currentGroup.length > 0) {
64
+ groupedCommands.push(currentGroup);
65
+ }
66
+ let idPadding = 0;
67
+ for (const command of commands) {
68
+ idPadding = Math.max(idPadding, this.displayId(command.id).length);
69
+ }
70
+ const body = groupedCommands.map((group) => this.renderCommandsBody(group, idPadding)).join('\n\n');
71
+ return this.section(title, body);
72
+ }
73
+ /**
74
+ * Commands are grouped by the first segment of their ID (e.g. "deploy" for "deploy:instance", "deploy:service-config", etc.)
75
+ * to create a flat command list at the root level, while still allowing for nested commands.
76
+ */
77
+ groupKeyForCommand(commandId) {
78
+ const separator = this.config.topicSeparator ?? ':';
79
+ // Prefer the configured topic separator when deriving the top-level key
80
+ if (separator && commandId.includes(separator)) {
81
+ const topLevel = commandId.split(separator)[0];
82
+ return topLevel || commandId;
83
+ }
84
+ // If the configured separator is not ":" but the ID still uses ":", fall back to ":"-based grouping
85
+ if (separator !== ':' && commandId.includes(':')) {
86
+ const topLevel = commandId.split(':')[0];
87
+ return topLevel || commandId;
88
+ }
89
+ // No known separator found; treat the whole ID as the group key
90
+ return commandId;
91
+ }
92
+ renderCommandsBody(commands, idPadding) {
93
+ return this.renderList(this.commandRows(commands, idPadding), {
94
+ indentation: 2,
95
+ spacer: '\n',
96
+ stripAnsi: this.opts.stripAnsi
97
+ });
98
+ }
99
+ async showRootHelp() {
100
+ const state = this.config.pjson?.oclif?.state;
101
+ if (state) {
102
+ this.log(state === 'deprecated' ? `${this.config.bin} is deprecated` : `${this.config.bin} is in ${state}.\n`);
103
+ }
104
+ this.log(this.formatRoot());
105
+ this.log('');
106
+ const commandsByGroup = new Map();
107
+ for (const command of this.sortedCommands.filter((c) => c.id)) {
108
+ const CommandClass = await command.load();
109
+ const group = CommandClass.commandHelpGroup ?? CommandHelpGroup.ADDITIONAL;
110
+ if (!commandsByGroup.has(group)) {
111
+ commandsByGroup.set(group, []);
112
+ }
113
+ commandsByGroup.get(group).push(command);
114
+ }
115
+ for (const group of SECTION_ORDER) {
116
+ const groupCommands = commandsByGroup.get(group);
117
+ if (groupCommands && groupCommands.length > 0) {
118
+ this.log(this.formatCommandsSection(`${group} COMMANDS`, groupCommands));
119
+ this.log('');
120
+ }
121
+ }
122
+ }
123
+ }