powersync 0.0.0-dev-20260305082615

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 (99) hide show
  1. package/LICENSE +67 -0
  2. package/README.md +1596 -0
  3. package/bin/dev.cmd +3 -0
  4. package/bin/dev.js +22 -0
  5. package/bin/run.cmd +3 -0
  6. package/bin/run.js +12 -0
  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/generate/index.d.ts +8 -0
  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/index.d.ts +8 -0
  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/link/index.d.ts +8 -0
  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/pull/index.d.ts +8 -0
  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/dist/index.d.ts +1 -0
  90. package/dist/index.js +1 -0
  91. package/oclif.manifest.json +1629 -0
  92. package/package.json +131 -0
  93. package/templates/cloud/powersync/cli.yaml +3 -0
  94. package/templates/cloud/powersync/service.yaml +174 -0
  95. package/templates/cloud/powersync/sync-config.yaml +22 -0
  96. package/templates/self-hosted/base/powersync/cli.yaml +3 -0
  97. package/templates/self-hosted/base/powersync/service.yaml +243 -0
  98. package/templates/self-hosted/base/powersync/sync-config.yaml +22 -0
  99. package/templates/vscode/settings.json +3 -0
@@ -0,0 +1,137 @@
1
+ import cors from '@fastify/cors';
2
+ import { env } from '@powersync/cli-core';
3
+ import { fastify } from 'fastify';
4
+ import { createDecipheriv, createPrivateKey, createPublicKey, generateKeyPairSync, privateDecrypt } from 'node:crypto';
5
+ import open from 'open';
6
+ /** Hybrid encryption format from dashboard: [encrypted_cek (256)] [iv (12)] [ciphertext] [tag (16)]. */
7
+ const RSA_ENCRYPTED_KEY_BYTES = 256;
8
+ const IV_BYTES = 12;
9
+ const GCM_TAG_BYTES = 16;
10
+ /** Decode base64 or base64url (URL-safe) to bytes. Accepts standard base64 or base64url from query params. */
11
+ function decodeBase64Payload(payload) {
12
+ const base64 = payload.replaceAll('-', '+').replaceAll('_', '/');
13
+ const pad = base64.length % 4;
14
+ const padded = pad === 0 ? base64 : base64 + '='.repeat(4 - pad);
15
+ return Buffer.from(padded, 'base64');
16
+ }
17
+ /**
18
+ * Decrypt a token encrypted by the dashboard with the hybrid scheme (RSA-OAEP-wrapped CEK + AES-256-GCM).
19
+ * Payload is base64 or base64url: decoded = encrypted_cek (256 bytes) || iv (12) || ciphertext || auth_tag (16).
20
+ * Uses Node crypto for RSA-OAEP and AES-GCM decryption.
21
+ */
22
+ function decryptTokenFromDashboard(base64Payload, privateKeyPem) {
23
+ const raw = decodeBase64Payload(base64Payload.trim());
24
+ if (raw.length < RSA_ENCRYPTED_KEY_BYTES + IV_BYTES + GCM_TAG_BYTES) {
25
+ throw new Error('Payload too short');
26
+ }
27
+ const encryptedCek = raw.subarray(0, RSA_ENCRYPTED_KEY_BYTES);
28
+ const iv = raw.subarray(RSA_ENCRYPTED_KEY_BYTES, RSA_ENCRYPTED_KEY_BYTES + IV_BYTES);
29
+ const ciphertextWithTag = raw.subarray(RSA_ENCRYPTED_KEY_BYTES + IV_BYTES);
30
+ const ciphertext = ciphertextWithTag.subarray(0, ciphertextWithTag.length - GCM_TAG_BYTES);
31
+ const tag = ciphertextWithTag.subarray(-GCM_TAG_BYTES);
32
+ const keyObject = createPrivateKey({ format: 'pem', key: privateKeyPem });
33
+ const cek = privateDecrypt({ key: keyObject, oaepHash: 'sha256' }, encryptedCek);
34
+ const decipher = createDecipheriv('aes-256-gcm', cek, iv);
35
+ decipher.setAuthTag(tag);
36
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
37
+ }
38
+ /**
39
+ * Server login handshake (asymmetric encryption)
40
+ *
41
+ * Flow:
42
+ * 1. CLI starts a local HTTP server and generates an ephemeral RSA keypair.
43
+ * 2. CLI opens the dashboard with a base64-encoded `request` param containing
44
+ * { redirect_url, public_key }. The dashboard learns where to send the token
45
+ * and how to encrypt it.
46
+ * 3. User creates a token in the dashboard. The dashboard encrypts the token
47
+ * with the CLI's public key and redirects the browser to redirect_url with
48
+ * the encrypted token in the query string (GET), so the secret never appears in history.
49
+ * 4. CLI receives GET /response?token=<base64> (see decryptTokenFromDashboard), decrypts it,
50
+ * and stores the plaintext token.
51
+ *
52
+ * Why encryption:
53
+ * In some cases the dashboard needs to hand the token back via a URL (e.g.
54
+ * redirect or opening the CLI callback URL in the browser). If we sent the
55
+ * token in the query string or fragment, it would appear in browser history,
56
+ * logs, and referrers. Encrypting with the CLI's public key ensures only this
57
+ * CLI instance can decrypt the token; the value that might appear in a URL or
58
+ * in transit is ciphertext, not the secret.
59
+ */
60
+ export async function startPATLoginServer(signal) {
61
+ const { privateKey: privateKeyPem, publicKey: publicKeyPem } = generateKeyPairSync('rsa', {
62
+ modulusLength: 2048,
63
+ privateKeyEncoding: { format: 'pem', type: 'pkcs8' },
64
+ publicKeyEncoding: { format: 'pem', type: 'spki' }
65
+ });
66
+ const publicKeyJwk = createPublicKey(publicKeyPem).export({ format: 'jwk' });
67
+ let settled = false;
68
+ let resolveToken;
69
+ let rejectToken;
70
+ const tokenPromise = new Promise((resolve, reject) => {
71
+ resolveToken = resolve;
72
+ rejectToken = reject;
73
+ });
74
+ signal.addEventListener('abort', () => {
75
+ if (!settled) {
76
+ settled = true;
77
+ rejectToken(new Error('Login aborted'));
78
+ }
79
+ app.close().catch(() => { });
80
+ });
81
+ const app = fastify({ logger: false });
82
+ const allowOrigin = env._PS_DASHBOARD_URL.replace(/\/$/, '');
83
+ await app.register(cors, { origin: allowOrigin });
84
+ app.get('/response', async (request, reply) => {
85
+ const rawToken = typeof request.query?.token === 'string' ? request.query.token.trim() : null;
86
+ if (!rawToken) {
87
+ await reply.status(400).send({ error: 'Missing or empty "token" query parameter' });
88
+ if (!settled) {
89
+ settled = true;
90
+ rejectToken(new Error('Invalid request: GET /response must include a non-empty "token" query parameter'));
91
+ }
92
+ return;
93
+ }
94
+ let tokenValue;
95
+ try {
96
+ tokenValue = decryptTokenFromDashboard(rawToken, privateKeyPem);
97
+ }
98
+ catch {
99
+ await reply.status(400).send({ error: 'Failed to decrypt token from dashboard' });
100
+ if (!settled) {
101
+ settled = true;
102
+ rejectToken(new Error('Failed to decrypt token from dashboard'));
103
+ }
104
+ return;
105
+ }
106
+ if (settled)
107
+ return;
108
+ settled = true;
109
+ const html = `<!DOCTYPE html>
110
+ <html>
111
+ <head><meta charset="utf-8"><title>Token accepted</title></head>
112
+ <body>
113
+ <p>Token was accepted.</p>
114
+ <p>Check the CLI output for further results.</p>
115
+ </body>
116
+ </html>`;
117
+ await reply.type('text/html').status(200).send(html);
118
+ resolveToken(tokenValue);
119
+ await app.close();
120
+ });
121
+ app.setErrorHandler((err, _request, reply) => {
122
+ if (!settled) {
123
+ settled = true;
124
+ rejectToken(err instanceof Error ? err : new Error(String(err)));
125
+ }
126
+ reply.status(500).send({ error: 'Internal server error' });
127
+ });
128
+ const address = await app.listen({ host: '127.0.0.1', port: 0 });
129
+ const responseUrl = `${address}/response`;
130
+ const requestPayload = {
131
+ public_key: publicKeyJwk,
132
+ redirect_url: responseUrl
133
+ };
134
+ const requestBase64 = Buffer.from(JSON.stringify(requestPayload), 'utf8').toString('base64');
135
+ open(`${env._PS_DASHBOARD_URL}/account/access-tokens/create?cliRequest=${encodeURIComponent(requestBase64)}`);
136
+ return { address, tokenPromise };
137
+ }
@@ -0,0 +1,63 @@
1
+ import { CloudProject, SelfHostedProject, SyncValidationTestRunResult, ValidationResult, ValidationTestRunResult } from '@powersync/cli-core';
2
+ /** Indentation used for nested human-readable output rows. */
3
+ export declare const INDENT = " ";
4
+ /** Bullet character used for list rows in human-readable output. */
5
+ export declare const BULLET = "\u2022";
6
+ /**
7
+ * Definition of a test: display name and async runner function.
8
+ */
9
+ export type ValidationTestDef = {
10
+ name: string;
11
+ run: () => Promise<ValidationTestRunResult>;
12
+ };
13
+ /**
14
+ * Runtime test entry, storing the in-flight promise and optional settled result.
15
+ */
16
+ export type ValidationTestEntry = {
17
+ name: string;
18
+ promise: Promise<ValidationTestRunResult>;
19
+ result?: ValidationTestRunResult;
20
+ };
21
+ /**
22
+ * Named test buckets used by the validate command.
23
+ */
24
+ export declare enum Tests {
25
+ CONFIGURATION_SCHEMA = "Validate Configuration Schema",
26
+ SYNC_RULES = "Validate Sync Config",
27
+ TEST_CONNECTIONS = "Test Connections"
28
+ }
29
+ /**
30
+ * Formats spinner text showing per-test progress while tests are running.
31
+ * These logs are indeted with bullets for readability, and update in-place as each test settles to show pass/fail status.
32
+ */
33
+ export declare function formatOraMessage(entries: ValidationTestEntry[]): string;
34
+ /**
35
+ * Formats suite output for `--output=human`.
36
+ */
37
+ export declare function formatValidationHuman(result: ValidationResult): string;
38
+ /**
39
+ * Formats suite output for `--output=json`.
40
+ */
41
+ export declare function formatValidationJson(result: ValidationResult): string;
42
+ /**
43
+ * Formats suite output for `--output=yaml`.
44
+ */
45
+ export declare function formatValidationYaml(result: ValidationResult): string;
46
+ /**
47
+ * Renders a warning into two lines for human output:
48
+ * 1) gray source fragment
49
+ * 2) yellow `[warning] line:column` prefix followed by plain message text
50
+ */
51
+ export declare function renderWarningForHumanOutput(warning: string): string[];
52
+ /**
53
+ * Validates `service.yaml` against the cloud or self-hosted schema, depending on project type.
54
+ */
55
+ export declare function runConfigTest(projectDir: string, isCloud: boolean): Promise<ValidationTestRunResult>;
56
+ /**
57
+ * Runs cloud sync-rules validation and maps diagnostics into warning/error message arrays.
58
+ */
59
+ export declare function runSyncRulesTestCloud(project: CloudProject): Promise<SyncValidationTestRunResult>;
60
+ /**
61
+ * Runs self-hosted sync-rules validation and maps diagnostics into warning/error message arrays.
62
+ */
63
+ export declare function runSyncRulesTestSelfHosted(project: SelfHostedProject): Promise<SyncValidationTestRunResult>;
@@ -0,0 +1,202 @@
1
+ import { ux } from '@oclif/core';
2
+ import { parseYamlFile, SERVICE_FILENAME, SYNC_FILENAME, validateCloudSyncRules, validateSelfHostedSyncRules } from '@powersync/cli-core';
3
+ import { ServiceCloudConfig, ServiceSelfHostedConfig } from '@powersync/cli-schemas';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { Document } from 'yaml';
7
+ /** Indentation used for nested human-readable output rows. */
8
+ export const INDENT = ' ';
9
+ /** Bullet character used for list rows in human-readable output. */
10
+ export const BULLET = '•';
11
+ /**
12
+ * Named test buckets used by the validate command.
13
+ */
14
+ export var Tests;
15
+ (function (Tests) {
16
+ Tests["CONFIGURATION_SCHEMA"] = "Validate Configuration Schema";
17
+ Tests["SYNC_RULES"] = "Validate Sync Config";
18
+ Tests["TEST_CONNECTIONS"] = "Test Connections";
19
+ })(Tests || (Tests = {}));
20
+ /**
21
+ * Formats spinner text showing per-test progress while tests are running.
22
+ * These logs are indeted with bullets for readability, and update in-place as each test settles to show pass/fail status.
23
+ */
24
+ export function formatOraMessage(entries) {
25
+ return entries
26
+ .map((e) => (e.result === undefined ? `\t... ${e.name}` : e.result.passed ? `\t✓ ${e.name}` : `\t✗ ${e.name}`))
27
+ .join('\n');
28
+ }
29
+ /**
30
+ * Formats one test result into human-readable plain text.
31
+ */
32
+ function formatTestResultHuman(test) {
33
+ const status = test.passed ? '✓' : '✗';
34
+ const name = `${status} ${test.name}`;
35
+ const warningLines = (test.warnings ?? []).map((warning) => `${INDENT}${BULLET} [warning] ${warning}`);
36
+ if (test.passed && warningLines.length === 0)
37
+ return name;
38
+ const errorLines = (test.errors ?? []).map((e) => `${INDENT}${BULLET} ${e}`);
39
+ return [name, ...warningLines, ...errorLines].join('\n');
40
+ }
41
+ /**
42
+ * Formats suite output for `--output=human`.
43
+ */
44
+ export function formatValidationHuman(result) {
45
+ const header = result.passed ? 'All validation tests passed.' : 'Some validation tests failed.';
46
+ const lines = [header, '', ...result.tests.map((test) => formatTestResultHuman(test))];
47
+ return lines.join('\n');
48
+ }
49
+ /**
50
+ * Formats suite output for `--output=json`.
51
+ */
52
+ export function formatValidationJson(result) {
53
+ return JSON.stringify(result, null, 2);
54
+ }
55
+ /**
56
+ * Formats suite output for `--output=yaml`.
57
+ */
58
+ export function formatValidationYaml(result) {
59
+ return new Document(result).toString();
60
+ }
61
+ /**
62
+ * Builds a two-line diagnostic message containing a source fragment and location-prefixed message.
63
+ */
64
+ function formatSyncDiagnosticMessage(diagnostic, syncRulesContent) {
65
+ const lineText = getLineAt(syncRulesContent, diagnostic.startLine);
66
+ const fragment = getLineFragment(lineText, diagnostic.startColumn);
67
+ return `${fragment}\n${diagnostic.startLine}:${diagnostic.startColumn} ${diagnostic.message}`;
68
+ }
69
+ /**
70
+ * Retrieves a specific 1-based line from text content.
71
+ */
72
+ function getLineAt(content, lineNumber) {
73
+ if (!content) {
74
+ return '';
75
+ }
76
+ const lines = content.split(/\r?\n/);
77
+ return lines[Math.max(0, lineNumber - 1)] ?? '';
78
+ }
79
+ /**
80
+ * Extracts a nearby fragment around `startColumn`, clipping to a fixed width for readability.
81
+ */
82
+ function getLineFragment(lineText, startColumn) {
83
+ if (!lineText) {
84
+ return '(line unavailable)';
85
+ }
86
+ const maxWidth = 120;
87
+ if (lineText.length <= maxWidth) {
88
+ return lineText;
89
+ }
90
+ const centerIndex = Math.max(0, startColumn - 1);
91
+ let start = Math.max(0, centerIndex - Math.floor(maxWidth / 2));
92
+ const end = Math.min(lineText.length, start + maxWidth);
93
+ if (end - start < maxWidth) {
94
+ start = Math.max(0, end - maxWidth);
95
+ }
96
+ const prefix = start > 0 ? '…' : '';
97
+ const suffix = end < lineText.length ? '…' : '';
98
+ return `${prefix}${lineText.slice(start, end)}${suffix}`;
99
+ }
100
+ /**
101
+ * Renders a warning into two lines for human output:
102
+ * 1) gray source fragment
103
+ * 2) yellow `[warning] line:column` prefix followed by plain message text
104
+ */
105
+ export function renderWarningForHumanOutput(warning) {
106
+ const [fragmentRaw, locationAndMessageRaw] = warning.split('\n', 2);
107
+ const fragment = fragmentRaw ?? '';
108
+ const locationAndMessage = locationAndMessageRaw ?? '';
109
+ const parsed = locationAndMessage.match(/^(\d+:\d+)\s+([\s\S]+)$/);
110
+ const location = parsed?.[1] ?? '';
111
+ const message = parsed?.[2] ?? locationAndMessage;
112
+ const lines = [ux.colorize('gray', `${INDENT}${BULLET} ${fragment}`)];
113
+ if (location) {
114
+ lines.push(`${INDENT}${ux.colorize('yellow', '[warning]')} ${ux.colorize('yellow', location)} ${message}`);
115
+ }
116
+ else {
117
+ lines.push(`${INDENT}${ux.colorize('yellow', '[warning]')} ${message}`);
118
+ }
119
+ return lines;
120
+ }
121
+ /**
122
+ * Validates `service.yaml` against the cloud or self-hosted schema, depending on project type.
123
+ */
124
+ export async function runConfigTest(projectDir, isCloud) {
125
+ const servicePath = join(projectDir, SERVICE_FILENAME);
126
+ try {
127
+ const doc = parseYamlFile(servicePath);
128
+ const raw = doc.contents?.toJSON();
129
+ if (isCloud) {
130
+ ServiceCloudConfig.decode(raw);
131
+ }
132
+ else {
133
+ ServiceSelfHostedConfig.decode(raw);
134
+ }
135
+ return { passed: true };
136
+ }
137
+ catch (error) {
138
+ const message = error instanceof Error ? error.message : String(error);
139
+ return { errors: [message], passed: false };
140
+ }
141
+ }
142
+ /**
143
+ * Runs cloud sync-rules validation and maps diagnostics into warning/error message arrays.
144
+ */
145
+ export async function runSyncRulesTestCloud(project) {
146
+ const syncRulesPath = join(project.projectDirectory, SYNC_FILENAME);
147
+ const syncRulesContent = project.syncRulesContent ?? (existsSync(syncRulesPath) ? readFileSync(syncRulesPath, 'utf8') : undefined);
148
+ const syncText = syncRulesContent ?? '';
149
+ try {
150
+ const result = await validateCloudSyncRules({
151
+ linked: project.linked,
152
+ syncRulesContent: syncText
153
+ });
154
+ const errors = result.diagnostics
155
+ .filter((diagnostic) => diagnostic.level === 'fatal')
156
+ .map((diagnostic) => formatSyncDiagnosticMessage(diagnostic, syncText));
157
+ const warnings = result.diagnostics
158
+ .filter((diagnostic) => diagnostic.level === 'warning')
159
+ .map((diagnostic) => formatSyncDiagnosticMessage(diagnostic, syncText));
160
+ return {
161
+ // Add detailed diagnostics for errors and warnings.
162
+ diagnostics: result.diagnostics,
163
+ errors: errors.length > 0 ? errors : undefined,
164
+ passed: errors.length === 0,
165
+ warnings: warnings.length > 0 ? warnings : undefined
166
+ };
167
+ }
168
+ catch (error) {
169
+ const message = error instanceof Error ? error.message : String(error);
170
+ return { diagnostics: [], errors: [message], passed: false };
171
+ }
172
+ }
173
+ /**
174
+ * Runs self-hosted sync-rules validation and maps diagnostics into warning/error message arrays.
175
+ */
176
+ export async function runSyncRulesTestSelfHosted(project) {
177
+ const syncRulesPath = join(project.projectDirectory, SYNC_FILENAME);
178
+ const syncRulesContent = existsSync(syncRulesPath) ? readFileSync(syncRulesPath, 'utf8') : undefined;
179
+ const syncText = syncRulesContent ?? '';
180
+ try {
181
+ const result = await validateSelfHostedSyncRules({
182
+ linked: project.linked,
183
+ syncRulesContent: syncText
184
+ });
185
+ const errors = result.diagnostics
186
+ .filter((diagnostic) => diagnostic.level === 'fatal')
187
+ .map((diagnostic) => formatSyncDiagnosticMessage(diagnostic, syncText));
188
+ const warnings = result.diagnostics
189
+ .filter((diagnostic) => diagnostic.level === 'warning')
190
+ .map((diagnostic) => formatSyncDiagnosticMessage(diagnostic, syncText));
191
+ return {
192
+ diagnostics: result.diagnostics,
193
+ errors: errors.length > 0 ? errors : undefined,
194
+ passed: errors.length === 0,
195
+ warnings: warnings.length > 0 ? warnings : undefined
196
+ };
197
+ }
198
+ catch (error) {
199
+ const message = error instanceof Error ? error.message : String(error);
200
+ return { diagnostics: [], errors: [message], passed: false };
201
+ }
202
+ }
@@ -0,0 +1,7 @@
1
+ import { SelfHostedProject } from '@powersync/cli-core';
2
+ /**
3
+ * Fetches the sync config content for a self-hosted project.
4
+ * @param project - The project to fetch the sync config content for.
5
+ * @returns The sync config content.
6
+ */
7
+ export declare function fetchSelfHostedSyncRulesContent(project: SelfHostedProject): Promise<string>;
@@ -0,0 +1,26 @@
1
+ import { createSelfHostedClient, SYNC_FILENAME } from '@powersync/cli-core';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ /**
5
+ * Fetches the sync config content for a self-hosted project.
6
+ * @param project - The project to fetch the sync config content for.
7
+ * @returns The sync config content.
8
+ */
9
+ export async function fetchSelfHostedSyncRulesContent(project) {
10
+ const { linked } = project;
11
+ const client = createSelfHostedClient({
12
+ apiKey: linked.api_key,
13
+ apiUrl: linked.api_url
14
+ });
15
+ // First try and use the local file
16
+ if (existsSync(join(project.projectDirectory, SYNC_FILENAME))) {
17
+ return readFileSync(join(project.projectDirectory, SYNC_FILENAME), 'utf8');
18
+ }
19
+ // Try and fetch from the cloud config
20
+ const instanceConfig = await client.diagnostics({});
21
+ const content = instanceConfig.active_sync_rules?.content;
22
+ if (!content) {
23
+ throw new Error('No active sync config found');
24
+ }
25
+ return content;
26
+ }
@@ -0,0 +1,8 @@
1
+ import { CommandHelpGroup, PowerSyncCommand } from '@powersync/cli-core';
2
+ export default class ConfigureIde extends PowerSyncCommand {
3
+ static commandHelpGroup: CommandHelpGroup;
4
+ static description: string;
5
+ static examples: string[];
6
+ static summary: string;
7
+ run(): Promise<void>;
8
+ }
@@ -0,0 +1,58 @@
1
+ import { select } from '@inquirer/prompts';
2
+ import { ux } from '@oclif/core';
3
+ import { CLI_FILENAME, CommandHelpGroup, parseYamlFile, PowerSyncCommand } from '@powersync/cli-core';
4
+ import { CLIConfig } from '@powersync/cli-schemas';
5
+ import { readdirSync, statSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { configureVscodeIde } from '../../api/ide/configure-vscode-ide.js';
8
+ const IDE_CONFIGURATORS = {
9
+ vscode: configureVscodeIde
10
+ };
11
+ /**
12
+ * Scans the current working directory for subdirectories that contain a valid
13
+ * PowerSync cli.yaml. Returns their absolute paths.
14
+ */
15
+ function findLinkedProjectDirs(cwd) {
16
+ const projectDirs = [];
17
+ for (const entry of readdirSync(cwd)) {
18
+ const entryPath = join(cwd, entry);
19
+ try {
20
+ if (!statSync(entryPath).isDirectory())
21
+ continue;
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ try {
27
+ const doc = parseYamlFile(join(entryPath, CLI_FILENAME));
28
+ CLIConfig.decode(doc.contents?.toJSON());
29
+ projectDirs.push(entryPath);
30
+ }
31
+ catch {
32
+ // Not a valid PowerSync project — skip.
33
+ }
34
+ }
35
+ return projectDirs;
36
+ }
37
+ export default class ConfigureIde extends PowerSyncCommand {
38
+ static commandHelpGroup = CommandHelpGroup.PROJECT_SETUP;
39
+ static description = 'Configure or guide your IDE setup for the best PowerSync CLI developer experience. Enables YAML schema validation and autocompletion, sets up !env custom tag support, and patches existing config files with language server directives.';
40
+ static examples = ['<%= config.bin %> <%= command.id %>'];
41
+ static summary = 'Configure your IDE for the best PowerSync CLI developer experience.';
42
+ async run() {
43
+ await this.parse(ConfigureIde);
44
+ this.log(`Tip: use ${ux.colorize('blue', 'powersync edit config')} for a complete in-browser editing experience.\n`);
45
+ const ide = await select({
46
+ choices: [
47
+ { name: 'VSCode', value: 'vscode' },
48
+ { name: 'Exit', value: 'exit' }
49
+ ],
50
+ message: 'Select your IDE to configure (only VSCode is supported for now):'
51
+ });
52
+ if (ide === 'exit')
53
+ return;
54
+ const projectDirs = findLinkedProjectDirs(process.cwd());
55
+ const configurator = IDE_CONFIGURATORS[ide];
56
+ configurator(process.cwd(), projectDirs, (msg) => this.log(msg));
57
+ }
58
+ }
@@ -0,0 +1,8 @@
1
+ import { Command } from '@oclif/core';
2
+ export default class Configure extends Command {
3
+ static description: string;
4
+ static examples: string[];
5
+ static hidden: boolean;
6
+ static summary: string;
7
+ run(): Promise<void>;
8
+ }
@@ -0,0 +1,11 @@
1
+ import { Command } from '@oclif/core';
2
+ export default class Configure extends Command {
3
+ static description = 'Configure your workspace or IDE for PowerSync development.';
4
+ static examples = ['<%= config.bin %> <%= command.id %>'];
5
+ static hidden = true;
6
+ static summary = 'Configure your workspace or IDE for PowerSync development.';
7
+ async run() {
8
+ await this.parse(Configure);
9
+ this.log('Use a subcommand: configure ide');
10
+ }
11
+ }
@@ -0,0 +1,48 @@
1
+ import { CloudInstanceCommand } from '@powersync/cli-core';
2
+ import { ServiceCloudConfigDecoded } from '@powersync/cli-schemas';
3
+ import { routes } from '@powersync/management-types';
4
+ /**
5
+ * Deploys the sync config and service configuration
6
+ */
7
+ export default class DeployAll extends CloudInstanceCommand {
8
+ static description: string;
9
+ static examples: string[];
10
+ static flags: {
11
+ 'instance-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ 'org-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ 'project-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
14
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
15
+ 'deploy-timeout': import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
16
+ };
17
+ static summary: string;
18
+ protected deployAll(params: {
19
+ cloudConfigState: routes.InstanceConfigResponse;
20
+ deployTimeoutMs: number;
21
+ updateSyncConfig: boolean;
22
+ }): Promise<void>;
23
+ protected deployInstanceConfig(params: {
24
+ cloudConfigState: routes.InstanceConfigResponse;
25
+ updateSyncConfig: boolean;
26
+ }): Promise<routes.DeployInstanceResponse>;
27
+ protected loadCloudConfigState(): Promise<routes.InstanceConfigResponse>;
28
+ parseLocalConfig(projectDirectory: string): ServiceCloudConfigDecoded;
29
+ protected provision(params: {
30
+ cloudConfigState: routes.InstanceConfigResponse;
31
+ deployTimeoutMs: number;
32
+ indentationLevel: number;
33
+ }): Promise<void>;
34
+ run(): Promise<void>;
35
+ protected testConnections(): Promise<void>;
36
+ protected validateServiceConfig(params: {
37
+ cloudConfigState: routes.InstanceConfigResponse;
38
+ }): Promise<void>;
39
+ protected validateSyncConfig(): Promise<void>;
40
+ protected waitForDeployCompletion(params: {
41
+ deployResult: routes.DeployInstanceResponse;
42
+ indentation?: string;
43
+ logCompletionMessage?: boolean;
44
+ logScheduledMessage?: boolean;
45
+ timeoutMs: number;
46
+ }): Promise<void>;
47
+ protected withDeploy(timeoutMs: number, fn: () => Promise<routes.DeployInstanceResponse>): Promise<void>;
48
+ }