@powersync/cli-core 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.
- package/LICENSE +67 -0
- package/README.md +24 -0
- package/dist/api/validate-sync-config.d.ts +63 -0
- package/dist/api/validate-sync-config.js +103 -0
- package/dist/clients/AccountsHubClientSDKClient.d.ts +67 -0
- package/dist/clients/AccountsHubClientSDKClient.js +66 -0
- package/dist/clients/cli-client-headers.d.ts +10 -0
- package/dist/clients/cli-client-headers.js +28 -0
- package/dist/clients/create-cloud-client.d.ts +6 -0
- package/dist/clients/create-cloud-client.js +36 -0
- package/dist/clients/create-self-hosted-client.d.ts +10 -0
- package/dist/clients/create-self-hosted-client.js +21 -0
- package/dist/command-types/CloudInstanceCommand.d.ts +62 -0
- package/dist/command-types/CloudInstanceCommand.js +190 -0
- package/dist/command-types/HelpGroup.d.ts +23 -0
- package/dist/command-types/HelpGroup.js +25 -0
- package/dist/command-types/InstanceCommand.d.ts +15 -0
- package/dist/command-types/InstanceCommand.js +42 -0
- package/dist/command-types/PowerSyncCommand.d.ts +29 -0
- package/dist/command-types/PowerSyncCommand.js +37 -0
- package/dist/command-types/SelfHostedInstanceCommand.d.ts +25 -0
- package/dist/command-types/SelfHostedInstanceCommand.js +97 -0
- package/dist/command-types/SharedInstanceCommand.d.ts +51 -0
- package/dist/command-types/SharedInstanceCommand.js +217 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +25 -0
- package/dist/services/Services.d.ts +6 -0
- package/dist/services/Services.js +8 -0
- package/dist/services/authentication/AuthenticationService.d.ts +5 -0
- package/dist/services/authentication/AuthenticationService.js +1 -0
- package/dist/services/authentication/AuthenticationServiceImpl.d.ts +12 -0
- package/dist/services/authentication/AuthenticationServiceImpl.js +41 -0
- package/dist/services/storage/KeychainSecureStorage.d.ts +2 -0
- package/dist/services/storage/KeychainSecureStorage.js +58 -0
- package/dist/services/storage/StorageImp.d.ts +18 -0
- package/dist/services/storage/StorageImp.js +85 -0
- package/dist/services/storage/StorageService.d.ts +24 -0
- package/dist/services/storage/StorageService.js +1 -0
- package/dist/utils/ensure-service-type.d.ts +16 -0
- package/dist/utils/ensure-service-type.js +37 -0
- package/dist/utils/env.d.ts +11 -0
- package/dist/utils/env.js +13 -0
- package/dist/utils/object-id.d.ts +1 -0
- package/dist/utils/object-id.js +1 -0
- package/dist/utils/project-config.d.ts +12 -0
- package/dist/utils/project-config.js +12 -0
- package/dist/utils/yaml.d.ts +23 -0
- package/dist/utils/yaml.js +76 -0
- package/package.json +53 -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,24 @@
|
|
|
1
|
+
# @powersync/cli-core
|
|
2
|
+
|
|
3
|
+
Core types, base commands, and utilities shared across the PowerSync CLI and its plugins.
|
|
4
|
+
|
|
5
|
+
> **Internal use:** This package is intended for internal use by the PowerSync CLI and its bundled plugins. It is not part of the public API.
|
|
6
|
+
>
|
|
7
|
+
> **Plugin authors:** You can use `@powersync/cli-core` to build your own PowerSync CLI plugins, but treat this package as **experimental and subject to change**. There are no stability guarantees between releases — APIs, types, and base classes may be renamed, restructured, or removed without a deprecation period.
|
|
8
|
+
|
|
9
|
+
## What's in this package
|
|
10
|
+
|
|
11
|
+
- Base command classes (`PowerSyncCommand`, `InstanceCommand`, `SelfHostedInstanceCommand`) for building CLI commands and plugins.
|
|
12
|
+
- Shared types (`SelfHostedProject`, `SelfHostedInstanceCommandFlags`, `EnsureConfigOptions`, etc.).
|
|
13
|
+
- YAML helpers (`parseYamlFile`, `parseYamlDocumentPreserveTags`, `stringifyYaml`) for `!env`-aware config parsing.
|
|
14
|
+
- Auth and project resolution utilities used by the CLI and official plugins.
|
|
15
|
+
|
|
16
|
+
## Usage in plugins
|
|
17
|
+
|
|
18
|
+
Import from `@powersync/cli-core` when authoring your own plugin:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { SelfHostedInstanceCommand, PowerSyncCommand } from '@powersync/cli-core';
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
See `@powersync/cli-plugin-docker` for a reference implementation.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { routes } from '@powersync/management-types';
|
|
2
|
+
import { ResolvedCloudCLIConfig, ResolvedSelfHostedCLIConfig } from '@powersync/cli-schemas';
|
|
3
|
+
import type { CloudProject } from '../command-types/CloudInstanceCommand.js';
|
|
4
|
+
import type { SelfHostedProject } from '../command-types/SelfHostedInstanceCommand.js';
|
|
5
|
+
/**
|
|
6
|
+
* Result from one validation test execution.
|
|
7
|
+
*
|
|
8
|
+
* `passed` indicates overall pass/fail for the test.
|
|
9
|
+
* `warnings` and `errors` hold preformatted human-readable messages.
|
|
10
|
+
*/
|
|
11
|
+
export type ValidationTestRunResult = {
|
|
12
|
+
errors?: string[];
|
|
13
|
+
passed: boolean;
|
|
14
|
+
warnings?: string[];
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Named validation test result for final reporting output.
|
|
18
|
+
*/
|
|
19
|
+
export type ValidationTestResult = ValidationTestRunResult & {
|
|
20
|
+
name: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Sync-config-specific validation result that includes structured diagnostics.
|
|
24
|
+
*/
|
|
25
|
+
export type SyncValidationTestRunResult = ValidationTestRunResult & {
|
|
26
|
+
diagnostics: SyncDiagnostic[];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Aggregate result for the full validation test suite.
|
|
30
|
+
*/
|
|
31
|
+
export type ValidationResult = {
|
|
32
|
+
passed: boolean;
|
|
33
|
+
tests: ValidationTestResult[];
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Diagnostics warnings linked to the position in the sync rules file (line and column) where the issue occurs.
|
|
37
|
+
*/
|
|
38
|
+
export type SyncDiagnostic = {
|
|
39
|
+
endColumn: number;
|
|
40
|
+
endLine: number;
|
|
41
|
+
level: 'fatal' | 'warning';
|
|
42
|
+
message: string;
|
|
43
|
+
startColumn: number;
|
|
44
|
+
startLine: number;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Enhanced result of sync config validation.
|
|
48
|
+
*/
|
|
49
|
+
export type SyncValidation = routes.ValidateSyncRulesResponse & {
|
|
50
|
+
diagnostics: SyncDiagnostic[];
|
|
51
|
+
};
|
|
52
|
+
export declare function validateCloudSyncRules(input: {
|
|
53
|
+
linked: ResolvedCloudCLIConfig;
|
|
54
|
+
syncRulesContent: string;
|
|
55
|
+
}): Promise<SyncValidation>;
|
|
56
|
+
export declare function validateSelfHostedSyncRules(input: {
|
|
57
|
+
linked: ResolvedSelfHostedCLIConfig;
|
|
58
|
+
syncRulesContent: string;
|
|
59
|
+
}): Promise<SyncValidation>;
|
|
60
|
+
export declare function validateProjectSyncConfig(input: {
|
|
61
|
+
linkedProject: CloudProject | SelfHostedProject;
|
|
62
|
+
syncRulesContent: string;
|
|
63
|
+
}): Promise<SyncValidation>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { createCloudClient } from '../clients/create-cloud-client.js';
|
|
2
|
+
import { createSelfHostedClient } from '../clients/create-self-hosted-client.js';
|
|
3
|
+
const EMPTY_SYNC_RULES_ERROR = {
|
|
4
|
+
connections: [],
|
|
5
|
+
errors: [
|
|
6
|
+
{
|
|
7
|
+
level: 'fatal',
|
|
8
|
+
message: 'No sync config content was provided.'
|
|
9
|
+
}
|
|
10
|
+
]
|
|
11
|
+
};
|
|
12
|
+
function getErrorMessage(error) {
|
|
13
|
+
return error instanceof Error ? error.message : String(error);
|
|
14
|
+
}
|
|
15
|
+
function toValidationRequestError(type, cause) {
|
|
16
|
+
const causeMessage = getErrorMessage(cause);
|
|
17
|
+
if (type === 'cloud') {
|
|
18
|
+
return new Error(`Could not validate sync rules against the cloud instance. Deploy the instance first with "powersync deploy service-config" and try again.\n${causeMessage}`);
|
|
19
|
+
}
|
|
20
|
+
return new Error(`Could not validate sync rules against the self-hosted instance. Ensure the instance is linked and running, then try again.\n${causeMessage}`);
|
|
21
|
+
}
|
|
22
|
+
function offsetToLineColumn(text, offset) {
|
|
23
|
+
const safeOffset = typeof offset === 'number' ? Math.max(0, Math.min(offset, text.length)) : 0;
|
|
24
|
+
let line = 1;
|
|
25
|
+
let column = 1;
|
|
26
|
+
for (let i = 0; i < safeOffset; i++) {
|
|
27
|
+
if (text.codePointAt(i) === 10) {
|
|
28
|
+
line += 1;
|
|
29
|
+
column = 1;
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
column += 1;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { column, line };
|
|
36
|
+
}
|
|
37
|
+
function mapSyncDiagnostics(response, syncRulesContent) {
|
|
38
|
+
const topLevel = response.errors.map((error) => {
|
|
39
|
+
const start = offsetToLineColumn(syncRulesContent, error.location?.start_offset);
|
|
40
|
+
const end = offsetToLineColumn(syncRulesContent, error.location?.end_offset ?? error.location?.start_offset);
|
|
41
|
+
return {
|
|
42
|
+
endColumn: end.column,
|
|
43
|
+
endLine: end.line,
|
|
44
|
+
level: error.level,
|
|
45
|
+
message: error.message,
|
|
46
|
+
startColumn: start.column,
|
|
47
|
+
startLine: start.line
|
|
48
|
+
};
|
|
49
|
+
});
|
|
50
|
+
return topLevel;
|
|
51
|
+
}
|
|
52
|
+
function toSyncValidation(response, syncRulesContent) {
|
|
53
|
+
return {
|
|
54
|
+
...response,
|
|
55
|
+
diagnostics: mapSyncDiagnostics(response, syncRulesContent)
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export async function validateCloudSyncRules(input) {
|
|
59
|
+
if (!input.syncRulesContent.trim()) {
|
|
60
|
+
return toSyncValidation(EMPTY_SYNC_RULES_ERROR, input.syncRulesContent);
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const client = createCloudClient();
|
|
64
|
+
const response = await client.validateSyncRules({
|
|
65
|
+
app_id: input.linked.project_id,
|
|
66
|
+
id: input.linked.instance_id,
|
|
67
|
+
org_id: input.linked.org_id,
|
|
68
|
+
sync_rules: input.syncRulesContent
|
|
69
|
+
});
|
|
70
|
+
return toSyncValidation(response, input.syncRulesContent);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
throw toValidationRequestError('cloud', error);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export async function validateSelfHostedSyncRules(input) {
|
|
77
|
+
if (!input.syncRulesContent.trim()) {
|
|
78
|
+
return toSyncValidation(EMPTY_SYNC_RULES_ERROR, input.syncRulesContent);
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const client = createSelfHostedClient({
|
|
82
|
+
apiKey: input.linked.api_key,
|
|
83
|
+
apiUrl: input.linked.api_url
|
|
84
|
+
});
|
|
85
|
+
const response = await client.validate({ sync_rules: input.syncRulesContent });
|
|
86
|
+
return toSyncValidation(response, input.syncRulesContent);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
throw toValidationRequestError('self-hosted', error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export async function validateProjectSyncConfig(input) {
|
|
93
|
+
if (input.linkedProject.linked.type === 'cloud') {
|
|
94
|
+
return validateCloudSyncRules({
|
|
95
|
+
linked: input.linkedProject.linked,
|
|
96
|
+
syncRulesContent: input.syncRulesContent
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return validateSelfHostedSyncRules({
|
|
100
|
+
linked: input.linkedProject.linked,
|
|
101
|
+
syncRulesContent: input.syncRulesContent
|
|
102
|
+
});
|
|
103
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TODO, replace this with a new public accounts SDK in future
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* @file API client for AccountsHub service
|
|
6
|
+
* @module lib/api/clients/AccountsHubClient
|
|
7
|
+
*/
|
|
8
|
+
import * as sdk from '@journeyapps-labs/common-sdk';
|
|
9
|
+
/**
|
|
10
|
+
* Client for interacting with the AccountsHub API service.
|
|
11
|
+
*
|
|
12
|
+
* Handles:
|
|
13
|
+
* - User authentication and profile management
|
|
14
|
+
* - Organization management
|
|
15
|
+
* - Project listing
|
|
16
|
+
* - User management within organizations
|
|
17
|
+
*/
|
|
18
|
+
export type Org = {
|
|
19
|
+
id: string;
|
|
20
|
+
label: string;
|
|
21
|
+
};
|
|
22
|
+
export type Project = {
|
|
23
|
+
id: string;
|
|
24
|
+
name: string;
|
|
25
|
+
};
|
|
26
|
+
export declare class AccountsHubClientSDKClient<C extends sdk.NetworkClient = sdk.NetworkClient> extends sdk.SDKClient<C> {
|
|
27
|
+
getOrganization: sdk.Endpoint<{
|
|
28
|
+
id: string;
|
|
29
|
+
}, Org, C>;
|
|
30
|
+
listOrganizations: ((params: sdk.PaginationParams & {
|
|
31
|
+
id?: string;
|
|
32
|
+
}) => Promise<sdk.PaginationResponse & {
|
|
33
|
+
objects: Org[];
|
|
34
|
+
}>) & {
|
|
35
|
+
paginate: (params: sdk.PaginationParams & {
|
|
36
|
+
id?: string;
|
|
37
|
+
}) => AsyncGenerator<sdk.PaginationResponse & {
|
|
38
|
+
objects: Org[];
|
|
39
|
+
}, void, unknown>;
|
|
40
|
+
};
|
|
41
|
+
listProjects: ((params: sdk.PaginationParams & {
|
|
42
|
+
id?: string;
|
|
43
|
+
org_id?: string;
|
|
44
|
+
}) => Promise<sdk.PaginationResponse & {
|
|
45
|
+
objects: Project[];
|
|
46
|
+
}>) & {
|
|
47
|
+
paginate: (params: sdk.PaginationParams & {
|
|
48
|
+
id?: string;
|
|
49
|
+
org_id?: string;
|
|
50
|
+
}) => AsyncGenerator<sdk.PaginationResponse & {
|
|
51
|
+
objects: Project[];
|
|
52
|
+
}, void, unknown>;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Creates a PowerSync Accounts Hub Client for the Cloud.
|
|
57
|
+
* Uses the token stored by the login command (secure storage, e.g. macOS Keychain).
|
|
58
|
+
*/
|
|
59
|
+
export declare function createAccountsHubClient(): AccountsHubClientSDKClient;
|
|
60
|
+
/**
|
|
61
|
+
* Resolve the default org ID when the token has access to exactly one organization.
|
|
62
|
+
* Use when --org-id / ORG_ID are not set; most PAT tokens are associated with a single org.
|
|
63
|
+
* Fetches organizations once and uses the result (no pagination).
|
|
64
|
+
* @returns The single org's ID.
|
|
65
|
+
* @throws If the token has zero or multiple orgs (caller should ask the user to pass --org-id).
|
|
66
|
+
*/
|
|
67
|
+
export declare function getDefaultOrgId(): Promise<string>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TODO, replace this with a new public accounts SDK in future
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* @file API client for AccountsHub service
|
|
6
|
+
* @module lib/api/clients/AccountsHubClient
|
|
7
|
+
*/
|
|
8
|
+
import * as sdk from '@journeyapps-labs/common-sdk';
|
|
9
|
+
import { ux } from '@oclif/core';
|
|
10
|
+
import { Services } from '../services/Services.js';
|
|
11
|
+
import { env } from '../utils/env.js';
|
|
12
|
+
import { getCliClientHeadersStore } from './cli-client-headers.js';
|
|
13
|
+
export class AccountsHubClientSDKClient extends sdk.SDKClient {
|
|
14
|
+
getOrganization = this.createEndpoint({
|
|
15
|
+
method: 'post',
|
|
16
|
+
path: '/api/accounts/v5/organizations/get'
|
|
17
|
+
});
|
|
18
|
+
listOrganizations = sdk.createPaginatedEndpoint(this.createEndpoint({
|
|
19
|
+
method: 'post',
|
|
20
|
+
path: '/api/accounts/v5/organizations/list'
|
|
21
|
+
}));
|
|
22
|
+
listProjects = sdk.createPaginatedEndpoint(this.createEndpoint({
|
|
23
|
+
method: 'post',
|
|
24
|
+
path: '/api/accounts/v5/apps/list'
|
|
25
|
+
}));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Creates a PowerSync Accounts Hub Client for the Cloud.
|
|
29
|
+
* Uses the token stored by the login command (secure storage, e.g. macOS Keychain).
|
|
30
|
+
*/
|
|
31
|
+
export function createAccountsHubClient() {
|
|
32
|
+
return new AccountsHubClientSDKClient({
|
|
33
|
+
client: sdk.createWebNetworkClient({
|
|
34
|
+
async headers() {
|
|
35
|
+
const { authentication } = Services;
|
|
36
|
+
const token = env.PS_ADMIN_TOKEN || (await authentication.getToken());
|
|
37
|
+
if (!token) {
|
|
38
|
+
throw new Error(`Not logged in. Run ${ux.colorize('blue', 'powersync login')} to authenticate (you will be prompted for your token), or provide the ${ux.colorize('blue', 'PS_ADMIN_TOKEN')} environment variable.`);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
...getCliClientHeadersStore().headers,
|
|
42
|
+
Authorization: `Bearer ${token}`
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
}),
|
|
46
|
+
endpoint: env._PS_ACCOUNTS_HUB_SERVICE_URL
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Resolve the default org ID when the token has access to exactly one organization.
|
|
51
|
+
* Use when --org-id / ORG_ID are not set; most PAT tokens are associated with a single org.
|
|
52
|
+
* Fetches organizations once and uses the result (no pagination).
|
|
53
|
+
* @returns The single org's ID.
|
|
54
|
+
* @throws If the token has zero or multiple orgs (caller should ask the user to pass --org-id).
|
|
55
|
+
*/
|
|
56
|
+
export async function getDefaultOrgId() {
|
|
57
|
+
const client = createAccountsHubClient();
|
|
58
|
+
const { objects: organizations, total } = await client.listOrganizations({});
|
|
59
|
+
if (total === 0) {
|
|
60
|
+
throw new Error('No organizations found for the current token. Pass --org-id explicitly or use a token that has access to an organization.');
|
|
61
|
+
}
|
|
62
|
+
if (total > 1) {
|
|
63
|
+
throw new Error(`Token has access to multiple organizations (${total}). Pass ${ux.colorize('blue', '--org-id')} to specify which one.`);
|
|
64
|
+
}
|
|
65
|
+
return organizations[0].id;
|
|
66
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
type CliClientHeadersStore = {
|
|
2
|
+
headers: Record<string, string>;
|
|
3
|
+
};
|
|
4
|
+
export declare function getCliClientHeadersStore(): CliClientHeadersStore;
|
|
5
|
+
/**
|
|
6
|
+
* Sets headers that are applied to all outbound CLI clients (cloud and self-hosted).
|
|
7
|
+
* Existing clients also pick up updates because headers are resolved per request.
|
|
8
|
+
*/
|
|
9
|
+
export declare function setCliClientHeaders(headers: Record<string, string>): void;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-wide store key for CLI client headers.
|
|
3
|
+
*
|
|
4
|
+
* Why global:
|
|
5
|
+
* - CLI startup code lives in the `cli` package, while client creation lives in `cli-core`.
|
|
6
|
+
* - In some environments, duplicate copies of `@powersync/cli-core` could be loaded (in the future perhaps).
|
|
7
|
+
* - Module-level state would then be duplicated, causing header injection (for example User-Agent)
|
|
8
|
+
* to only affect one copy.
|
|
9
|
+
*
|
|
10
|
+
* Using `globalThis` + `Symbol.for(...)` gives us one shared store for this process,
|
|
11
|
+
* regardless of how many module instances are loaded.
|
|
12
|
+
*/
|
|
13
|
+
const CLI_CLIENT_HEADERS_STORE_KEY = Symbol.for('powersync.cli-core.cliClientHeaders');
|
|
14
|
+
export function getCliClientHeadersStore() {
|
|
15
|
+
// Read/write the shared process-wide store so all cli-core instances observe the same headers.
|
|
16
|
+
const globalScope = globalThis;
|
|
17
|
+
if (!globalScope[CLI_CLIENT_HEADERS_STORE_KEY]) {
|
|
18
|
+
globalScope[CLI_CLIENT_HEADERS_STORE_KEY] = { headers: {} };
|
|
19
|
+
}
|
|
20
|
+
return globalScope[CLI_CLIENT_HEADERS_STORE_KEY];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Sets headers that are applied to all outbound CLI clients (cloud and self-hosted).
|
|
24
|
+
* Existing clients also pick up updates because headers are resolved per request.
|
|
25
|
+
*/
|
|
26
|
+
export function setCliClientHeaders(headers) {
|
|
27
|
+
Object.assign(getCliClientHeadersStore().headers, headers);
|
|
28
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { PowerSyncManagementClient } from '@powersync/management-client';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a PowerSync Management Client for the Cloud.
|
|
4
|
+
* Uses the token stored by the login command (secure storage, e.g. macOS Keychain).
|
|
5
|
+
*/
|
|
6
|
+
export declare function createCloudClient(): PowerSyncManagementClient;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import * as sdk from '@journeyapps-labs/common-sdk';
|
|
2
|
+
import { ux } from '@oclif/core';
|
|
3
|
+
import { PowerSyncManagementClient } from '@powersync/management-client';
|
|
4
|
+
import { Services } from '../services/Services.js';
|
|
5
|
+
import { env } from '../utils/env.js';
|
|
6
|
+
import { getCliClientHeadersStore } from './cli-client-headers.js';
|
|
7
|
+
/**
|
|
8
|
+
* Creates a PowerSync Management Client for the Cloud.
|
|
9
|
+
* Uses the token stored by the login command (secure storage, e.g. macOS Keychain).
|
|
10
|
+
*/
|
|
11
|
+
export function createCloudClient() {
|
|
12
|
+
return new PowerSyncManagementClient({
|
|
13
|
+
/**
|
|
14
|
+
* Use the web network client rather than the node client. The node client
|
|
15
|
+
* uses agentkeepalive to pool TCP connections across requests. When making
|
|
16
|
+
* multiple requests from the same client, connection reuse can cause 400 Bad
|
|
17
|
+
* Request errors if the server closes connections before the client's
|
|
18
|
+
* freeSocketTimeout (30s). The web client uses fetch() which manages
|
|
19
|
+
* connections differently and avoids this stale-connection issue.
|
|
20
|
+
* Node.js exposes fetch as a global, so we can use it directly without importing it.
|
|
21
|
+
*/
|
|
22
|
+
client: sdk.createWebNetworkClient({
|
|
23
|
+
async headers() {
|
|
24
|
+
const token = env.PS_ADMIN_TOKEN || (await Services.authentication.getToken());
|
|
25
|
+
if (!token) {
|
|
26
|
+
throw new Error(`Not logged in. Run ${ux.colorize('blue', 'powersync login')} to authenticate (you will be prompted for your token), or provide the ${ux.colorize('blue', 'PS_ADMIN_TOKEN')} environment variable.`);
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
...getCliClientHeadersStore().headers,
|
|
30
|
+
Authorization: `Bearer ${token}`
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}),
|
|
34
|
+
endpoint: env._PS_MANAGEMENT_SERVICE_URL
|
|
35
|
+
});
|
|
36
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import * as sdk from '@journeyapps-labs/common-sdk';
|
|
2
|
+
import { InstanceClient } from '@powersync/service-client';
|
|
3
|
+
export type SelfHostedClientConfig = {
|
|
4
|
+
apiKey: string;
|
|
5
|
+
apiUrl: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Creates a PowerSync Instance Client for a self-hosted instance.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createSelfHostedClient(config: SelfHostedClientConfig): InstanceClient<sdk.WebNetworkClient>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import * as sdk from '@journeyapps-labs/common-sdk';
|
|
2
|
+
import { InstanceClient } from '@powersync/service-client';
|
|
3
|
+
import { getCliClientHeadersStore } from './cli-client-headers.js';
|
|
4
|
+
/**
|
|
5
|
+
* Creates a PowerSync Instance Client for a self-hosted instance.
|
|
6
|
+
*/
|
|
7
|
+
export function createSelfHostedClient(config) {
|
|
8
|
+
return new InstanceClient({
|
|
9
|
+
/**
|
|
10
|
+
* Use the web (fetch-based) network client to mirror the cloud client behavior and
|
|
11
|
+
* allow fetch to be spied on in tests. Node exposes fetch globally so we can rely on it.
|
|
12
|
+
*/
|
|
13
|
+
client: sdk.createWebNetworkClient({
|
|
14
|
+
headers: () => ({
|
|
15
|
+
...getCliClientHeadersStore().headers,
|
|
16
|
+
Authorization: `Bearer ${config.apiKey}`
|
|
17
|
+
})
|
|
18
|
+
}),
|
|
19
|
+
endpoint: config.apiUrl
|
|
20
|
+
});
|
|
21
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Interfaces } from '@oclif/core';
|
|
2
|
+
import { ResolvedCloudCLIConfig, ServiceCloudConfigDecoded } from '@powersync/cli-schemas';
|
|
3
|
+
import { PowerSyncManagementClient } from '@powersync/management-client';
|
|
4
|
+
import { CommandHelpGroup } from './HelpGroup.js';
|
|
5
|
+
import { EnsureConfigOptions, InstanceCommand } from './InstanceCommand.js';
|
|
6
|
+
export type CloudProject = {
|
|
7
|
+
linked: ResolvedCloudCLIConfig;
|
|
8
|
+
projectDirectory: string;
|
|
9
|
+
syncRulesContent?: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Parsed (output) type of CloudInstanceCommand flags.
|
|
13
|
+
* Use when you need the type of `flags` from `await this.parse(CloudInstanceCommand)`.
|
|
14
|
+
*/
|
|
15
|
+
export type CloudInstanceCommandFlags = Interfaces.InferredFlags<typeof CloudInstanceCommand.baseFlags & typeof CloudInstanceCommand.flags>;
|
|
16
|
+
/**
|
|
17
|
+
* Base command for operations that require a Cloud-type PowerSync project (service.yaml _type: cloud).
|
|
18
|
+
*
|
|
19
|
+
* Instance context (instance_id, org_id, project_id) is resolved in this order:
|
|
20
|
+
* 1. Command-line flags (--instance-id, --org-id, --project-id)
|
|
21
|
+
* 2. Linked config from cli.yaml
|
|
22
|
+
* 3. Environment variables (INSTANCE_ID, ORG_ID, PROJECT_ID)
|
|
23
|
+
* 4. If org_id is still missing: token's single org (via accounts API); error if multiple orgs.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* # Use linked project (cli.yaml)
|
|
27
|
+
* pnpm exec powersync some-cloud-cmd
|
|
28
|
+
* # Override with env
|
|
29
|
+
* INSTANCE_ID=... ORG_ID=... PROJECT_ID=... pnpm exec powersync some-cloud-cmd
|
|
30
|
+
* # Override with flags
|
|
31
|
+
* pnpm exec powersync some-cloud-cmd --instance-id=... --org-id=... --project-id=...
|
|
32
|
+
*/
|
|
33
|
+
export declare abstract class CloudInstanceCommand extends InstanceCommand {
|
|
34
|
+
static commandHelpGroup: CommandHelpGroup;
|
|
35
|
+
static flags: {
|
|
36
|
+
'instance-id': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
|
|
37
|
+
'org-id': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
|
|
38
|
+
'project-id': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
|
|
39
|
+
directory: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
|
|
40
|
+
};
|
|
41
|
+
protected _project: CloudProject | null;
|
|
42
|
+
/**
|
|
43
|
+
* Used to interface with the PowerSync Management API for Cloud instances. Automatically created with the token from login (or PS_ADMIN_TOKEN env variable).
|
|
44
|
+
*/
|
|
45
|
+
client: PowerSyncManagementClient;
|
|
46
|
+
/**
|
|
47
|
+
* The parsed service config from the service.yaml file. Call parseLocalConfig() before accessing this property. This is set to the parsed config after calling parseLocalConfig() to avoid multiple parses of the same config.
|
|
48
|
+
*/
|
|
49
|
+
protected serviceConfig: null | ServiceCloudConfigDecoded;
|
|
50
|
+
/**
|
|
51
|
+
* The currently loaded project, including linked instance information and sync config content. Call loadProject() before accessing this property. This is set to the loaded project after calling loadProject() to avoid multiple loads of the same project.
|
|
52
|
+
*/
|
|
53
|
+
get project(): CloudProject;
|
|
54
|
+
/**
|
|
55
|
+
* Some commands require contacting a provisioned PowerSync instance.
|
|
56
|
+
* This verifies that the linked instance is provisioned, and shows an error with next steps if it's not.
|
|
57
|
+
*/
|
|
58
|
+
ensureProvisioned(): Promise<void>;
|
|
59
|
+
loadProject(flags: CloudInstanceCommandFlags, options?: EnsureConfigOptions): Promise<CloudProject>;
|
|
60
|
+
parseLocalConfig(projectDirectory: string): ServiceCloudConfigDecoded;
|
|
61
|
+
private ensureObjectIdIfPresent;
|
|
62
|
+
}
|