@cclabsnz/sf-core 0.11.0 → 0.12.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/CHANGELOG.md +51 -1
- package/README.md +33 -2
- package/lib/api/ApiError.d.ts +33 -1
- package/lib/api/ApiError.js +81 -3
- package/lib/api/MetadataClientImpl.js +8 -1
- package/lib/api/RestClientImpl.js +19 -19
- package/lib/api/SoqlClientImpl.d.ts +3 -1
- package/lib/api/SoqlClientImpl.js +24 -9
- package/lib/api/ToolingClientImpl.d.ts +3 -1
- package/lib/api/ToolingClientImpl.js +18 -15
- package/lib/api/fetch/FetchRestClient.d.ts +11 -0
- package/lib/api/fetch/FetchRestClient.js +23 -0
- package/lib/api/fetch/FetchSoqlClient.d.ts +13 -0
- package/lib/api/fetch/FetchSoqlClient.js +22 -0
- package/lib/api/fetch/FetchToolingClient.d.ts +12 -0
- package/lib/api/fetch/FetchToolingClient.js +18 -0
- package/lib/api/fetch/FetchTransport.d.ts +44 -0
- package/lib/api/fetch/FetchTransport.js +96 -0
- package/lib/api/fetch/index.d.ts +31 -0
- package/lib/api/fetch/index.js +32 -0
- package/lib/api/fetch/jwtBearer.d.ts +43 -0
- package/lib/api/fetch/jwtBearer.js +115 -0
- package/lib/api/index.d.ts +2 -1
- package/lib/api/index.js +1 -1
- package/lib/api/paging.d.ts +25 -0
- package/lib/api/paging.js +62 -0
- package/lib/api/streamToFile.d.ts +7 -0
- package/lib/api/streamToFile.js +22 -0
- package/lib/events/eventLogAccess.js +5 -2
- package/lib/fetch.d.ts +7 -0
- package/lib/fetch.js +4 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/package.json +11 -1
package/CHANGELOG.md
CHANGED
|
@@ -10,7 +10,57 @@ CycloneDX SBOM for the build.
|
|
|
10
10
|
|
|
11
11
|
## [Unreleased]
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
## [0.12.0] — 2026-10-23
|
|
14
|
+
|
|
15
|
+
### Breaking
|
|
16
|
+
|
|
17
|
+
- **`ApiError.statusCode` is now optional** (`number | undefined`). jsforce keeps no HTTP status
|
|
18
|
+
for a JSON error body, so errors from the `Connection` clients carry none.
|
|
19
|
+
- **`Connection`-path errors are now `SalesforceApiError`, not jsforce's `HttpApiError`.** The
|
|
20
|
+
details move from `err.data` to `err.details`, and `err instanceof HttpApiError` is now false.
|
|
21
|
+
`err.name` and `err.errorCode` are unchanged, and the original jsforce error is kept as
|
|
22
|
+
`err.cause`.
|
|
23
|
+
- **`queryAll` no longer honours `maxQueryLimit` or `SF_ORG_MAX_QUERY_LIMIT`.** It pages to
|
|
24
|
+
completion and throws `QUERY_TOO_LARGE` past a page cap (default 200 pages, child
|
|
25
|
+
relationship pages included) instead of truncating. Set the cap with `{ maxPages }` as the
|
|
26
|
+
second constructor argument of `SoqlClientImpl`, `ToolingClientImpl`, `FetchSoqlClient` and
|
|
27
|
+
`FetchToolingClient`, or `maxPages` on `createFetchClients`.
|
|
28
|
+
- **`RestClientImpl.getRawToFile` throws an `ApiError`** (built from the response, or
|
|
29
|
+
`EMPTY_BODY` when there is no body) instead of a plain "Download failed" `Error`.
|
|
30
|
+
- **An error response with no Salesforce code is `ERROR_HTTP_<status>`**, with the raw body as
|
|
31
|
+
the message, and an array of more than one error is `MULTIPLE_API_ERRORS`, exactly as jsforce
|
|
32
|
+
reports them. Both transports now raise the same code for the same response.
|
|
33
|
+
|
|
34
|
+
### Added
|
|
35
|
+
|
|
36
|
+
- **Fetch transport and `@cclabsnz/sf-core/fetch`.** `createFetchClients`, `FetchTransport`,
|
|
37
|
+
`FetchSoqlClient`, `FetchToolingClient`, `FetchRestClient`, `jwtBearerToken` and `pemSigner`:
|
|
38
|
+
the same `SoqlClient`, `ToolingClient` and `RestClient` interfaces over global `fetch`, with a
|
|
39
|
+
JWT bearer login, for hosts that cannot carry `@salesforce/core`. The entry point reaches
|
|
40
|
+
neither `@salesforce/core` nor jsforce. The only non-GET request is the OAuth token exchange,
|
|
41
|
+
in one file. `loginUrl` and the returned `instance_url` must be https. Concurrent requests
|
|
42
|
+
that hit an expired token share one re-authentication.
|
|
43
|
+
- `SalesforceApiError`, `PagingOptions`, and a shared paging helper used by both transports.
|
|
44
|
+
|
|
45
|
+
### Fixed
|
|
46
|
+
|
|
47
|
+
- **`isApiError` now accepts real Salesforce errors.** jsforce's `HttpApiError` carries
|
|
48
|
+
`errorCode` but no `statusCode`, so every real org error failed the check and consumers that
|
|
49
|
+
classify degradations never matched one. Errors from the `Connection` clients are now wrapped
|
|
50
|
+
as `SalesforceApiError`.
|
|
51
|
+
- **`SoqlClientImpl.queryAll` no longer truncates at 10,000 records.** It followed
|
|
52
|
+
`autoFetchQuery`, which stops at the configured cap with only a warning.
|
|
53
|
+
- **`ToolingClientImpl.query` no longer stops silently after 200 pages.** Both clients now throw
|
|
54
|
+
`QUERY_TOO_LARGE` instead of returning a partial result.
|
|
55
|
+
- **Child relationship (subquery) results are complete.** A subquery field that carries its own
|
|
56
|
+
`nextRecordsUrl` is followed to the end on both transports, as `autoFetchQuery` used to do.
|
|
57
|
+
- **`classifyEventLogAccessError` reads only `errorCode`**, so an org error classifies the same
|
|
58
|
+
way whichever transport raised it. `ERROR_HTTP_403` is `no-permission`; `ERROR_HTTP_404` and
|
|
59
|
+
`ERROR_HTTP_400` are `not-enabled`.
|
|
60
|
+
|
|
61
|
+
### Changed
|
|
62
|
+
|
|
63
|
+
- `@salesforce/core` is now an optional peer dependency.
|
|
14
64
|
|
|
15
65
|
## [0.11.0] — 2026-10-16
|
|
16
66
|
|
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ contracts behind [`@cclabsnz/sf-audit`](https://www.npmjs.com/package/@cclabsnz/
|
|
|
21
21
|
|
|
22
22
|
| Area | What it provides |
|
|
23
23
|
| --- | --- |
|
|
24
|
-
| **API clients** | `SoqlClient`, `ToolingClient`, `RestClient`, `MetadataClient`: read-only wrappers over a `@salesforce/core` `Connection` |
|
|
24
|
+
| **API clients** | `SoqlClient`, `ToolingClient`, `RestClient`, `MetadataClient`: read-only wrappers over a `@salesforce/core` `Connection`, or, via `@cclabsnz/sf-core/fetch`, over plain `fetch` with a JWT bearer login (no `@salesforce/core`; `MetadataClient` is Connection-only) |
|
|
25
25
|
| **Platform behaviour** | `FlowRepository`, `ApexRepository`, `isSalesforceId`, `describeSalesforceError`, `mapWithConcurrency` |
|
|
26
26
|
| **Event capture** | `EventBaselineStore`, `RTE_CATALOG`, `pullEventLogs`, `pullRealtimeEvents`, `CaptureManifest`: bounded, resumable EventLogFile and Real-Time Event pulls |
|
|
27
27
|
| **Activity engine** | Turns captured EventLogFile rows into a classified, sessionised account of one actor's API activity. Classifies each call as a read, write, destructive, control or unknown operation — `unknown` is a real answer for undecomposed `/composite` requests, not a failure to classify — resolves them into their subrequests, groups events into runs and cycles, recovers the repeating sequence, and flags outliers on median and MAD. Pure functions; no org connection. |
|
|
@@ -84,6 +84,36 @@ await mapWithConcurrency(versions, 8, async (v) => {
|
|
|
84
84
|
});
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
+
### Without @salesforce/core
|
|
88
|
+
|
|
89
|
+
`@cclabsnz/sf-core/fetch` carries no `@salesforce/core` or jsforce, so it fits a Lambda or edge
|
|
90
|
+
bundle. `@salesforce/core` is an optional peer dependency. It logs in with the JWT bearer flow
|
|
91
|
+
(an External Client App with a certificate) and implements `SoqlClient`, `ToolingClient` and
|
|
92
|
+
`RestClient`:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
import { createFetchClients, pemSigner } from '@cclabsnz/sf-core/fetch';
|
|
96
|
+
|
|
97
|
+
const { soql, tooling, rest } = createFetchClients({
|
|
98
|
+
apiVersion: '64.0',
|
|
99
|
+
auth: {
|
|
100
|
+
clientId: process.env.SF_CLIENT_ID!,
|
|
101
|
+
username: process.env.SF_USERNAME!,
|
|
102
|
+
loginUrl: 'https://login.salesforce.com', // https only
|
|
103
|
+
sign: pemSigner(process.env.SF_PRIVATE_KEY!),
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const rows = await soql.queryAll<{ Id: string }>('SELECT Id FROM Account');
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Both transports return the same values and raise the same errors for the same org responses.
|
|
111
|
+
`queryAll` follows every page, child relationship pages included, and throws `QUERY_TOO_LARGE`
|
|
112
|
+
rather than return a partial result once it passes the page cap: 200 pages by default, or
|
|
113
|
+
`maxPages` on `createFetchClients` (the `Connection` clients take `{ maxPages }` as a second
|
|
114
|
+
constructor argument). Errors are `SalesforceApiError` with Salesforce's own `errorCode`, or
|
|
115
|
+
`ERROR_HTTP_<status>` when the response carries none; test for them with `isApiError`.
|
|
116
|
+
|
|
87
117
|
JSON Schemas are reachable as a subpath export:
|
|
88
118
|
|
|
89
119
|
```ts
|
|
@@ -96,7 +126,8 @@ const couplingGraphSchema = loadSchema('coupling-graph');
|
|
|
96
126
|
Both are enforced as tests, not asserted in prose. Run them yourself with `pnpm test`:
|
|
97
127
|
|
|
98
128
|
- **Read-only.** No jsforce mutation API, HTTP write verb, or bulk/composite write path may
|
|
99
|
-
appear in source.
|
|
129
|
+
appear in source. The one exception is the OAuth token `POST` in the fetch login, which
|
|
130
|
+
writes no org data and is confined to one file by a test. Every org request is a SOQL query, a REST **GET**, or a Metadata read.
|
|
100
131
|
- **Local-first.** No third-party HTTP client, telemetry endpoint, LLM call, websocket, or
|
|
101
132
|
remote asset in a generated report. The only network destination is the org the operator
|
|
102
133
|
authenticated against.
|
package/lib/api/ApiError.d.ts
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
export interface ApiError extends Error {
|
|
2
2
|
errorCode: string;
|
|
3
|
-
statusCode
|
|
3
|
+
statusCode?: number;
|
|
4
4
|
}
|
|
5
5
|
export declare function isApiError(err: unknown): err is ApiError;
|
|
6
|
+
export declare class SalesforceApiError extends Error implements ApiError {
|
|
7
|
+
readonly errorCode: string;
|
|
8
|
+
readonly statusCode?: number;
|
|
9
|
+
readonly details?: unknown;
|
|
10
|
+
constructor(errorCode: string, message: string, opts?: {
|
|
11
|
+
statusCode?: number;
|
|
12
|
+
details?: unknown;
|
|
13
|
+
cause?: unknown;
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Builds an ApiError from a non-OK Salesforce HTTP response, mirroring jsforce's HttpApi.getError
|
|
18
|
+
* (http-api.js) so the fetch and Connection transports raise the same errorCode, message and details:
|
|
19
|
+
* a body is parsed as JSON only when the content type is application/json; an array of other than
|
|
20
|
+
* one entry is MULTIPLE_API_ERRORS; a body with no string `message` is ERROR_HTTP_<status> with the
|
|
21
|
+
* raw body as the message; an entry with a message but no errorCode gets jsforce's 'Error'.
|
|
22
|
+
* Internal: not exported from either entry point.
|
|
23
|
+
*/
|
|
24
|
+
export declare function apiErrorFromResponse(res: {
|
|
25
|
+
status: number;
|
|
26
|
+
headers: {
|
|
27
|
+
get(name: string): string | null;
|
|
28
|
+
};
|
|
29
|
+
text(): Promise<string>;
|
|
30
|
+
}): Promise<SalesforceApiError>;
|
|
31
|
+
/**
|
|
32
|
+
* Wraps a jsforce error (string errorCode, no statusCode) as a SalesforceApiError, so `details` and
|
|
33
|
+
* a uniform class are present whichever transport raised it; the original is kept as `cause`.
|
|
34
|
+
* Anything else passes through unchanged. Internal: not exported from either entry point.
|
|
35
|
+
* (isApiError alone cannot be the gate: it now accepts a statusCode-less error.)
|
|
36
|
+
*/
|
|
37
|
+
export declare function normaliseApiError(err: unknown): unknown;
|
|
6
38
|
//# sourceMappingURL=ApiError.d.ts.map
|
package/lib/api/ApiError.js
CHANGED
|
@@ -1,6 +1,84 @@
|
|
|
1
1
|
export function isApiError(err) {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
if (!(err instanceof Error))
|
|
3
|
+
return false;
|
|
4
|
+
const e = err;
|
|
5
|
+
return typeof e.errorCode === 'string' && (e.statusCode === undefined || typeof e.statusCode === 'number');
|
|
6
|
+
}
|
|
7
|
+
export class SalesforceApiError extends Error {
|
|
8
|
+
errorCode;
|
|
9
|
+
statusCode;
|
|
10
|
+
details;
|
|
11
|
+
constructor(errorCode, message, opts = {}) {
|
|
12
|
+
super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
|
|
13
|
+
// jsforce sets name to the Salesforce error code; keep that so existing `name` readers don't change.
|
|
14
|
+
this.name = errorCode;
|
|
15
|
+
this.errorCode = errorCode;
|
|
16
|
+
this.statusCode = opts.statusCode;
|
|
17
|
+
this.details = opts.details;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
// Messages copied from jsforce's HttpApi.getError, so both transports raise the same text.
|
|
21
|
+
const MULTIPLE_MESSAGE = `Multiple errors returned.
|
|
22
|
+
Check \`error.data\` for the error details`;
|
|
23
|
+
const htmlMessage = (status) => `HTTP response contains html content.
|
|
24
|
+
Check that the org exists and can be reached.
|
|
25
|
+
|
|
26
|
+
HTTP status code: ${status}.
|
|
27
|
+
REST API Status Codes and Error Responses:
|
|
28
|
+
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/errorcodes.htm
|
|
29
|
+
|
|
30
|
+
See \`error.data\` for the full html response.`;
|
|
31
|
+
/**
|
|
32
|
+
* Builds an ApiError from a non-OK Salesforce HTTP response, mirroring jsforce's HttpApi.getError
|
|
33
|
+
* (http-api.js) so the fetch and Connection transports raise the same errorCode, message and details:
|
|
34
|
+
* a body is parsed as JSON only when the content type is application/json; an array of other than
|
|
35
|
+
* one entry is MULTIPLE_API_ERRORS; a body with no string `message` is ERROR_HTTP_<status> with the
|
|
36
|
+
* raw body as the message; an entry with a message but no errorCode gets jsforce's 'Error'.
|
|
37
|
+
* Internal: not exported from either entry point.
|
|
38
|
+
*/
|
|
39
|
+
export async function apiErrorFromResponse(res) {
|
|
40
|
+
const text = await res.text();
|
|
41
|
+
const contentType = res.headers.get('content-type') ?? '';
|
|
42
|
+
const statusCode = res.status;
|
|
43
|
+
let body = text;
|
|
44
|
+
if (/^application\/json(;|$)/.test(contentType)) {
|
|
45
|
+
try {
|
|
46
|
+
body = JSON.parse(text);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
body = text;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(body)) {
|
|
53
|
+
if (body.length !== 1) {
|
|
54
|
+
return new SalesforceApiError('MULTIPLE_API_ERRORS', MULTIPLE_MESSAGE, { statusCode, details: body });
|
|
55
|
+
}
|
|
56
|
+
body = body[0];
|
|
57
|
+
}
|
|
58
|
+
const entry = typeof body === 'object' && body !== null && typeof body.message === 'string'
|
|
59
|
+
? body
|
|
60
|
+
: { errorCode: `ERROR_HTTP_${statusCode}`, message: text };
|
|
61
|
+
// jsforce's HttpApiError falls back to Error's own name when the code is missing.
|
|
62
|
+
const code = typeof entry.errorCode === 'string' && entry.errorCode !== '' ? entry.errorCode : 'Error';
|
|
63
|
+
// jsforce compares the raw header, so only a bare `text/html` takes this branch.
|
|
64
|
+
if (contentType === 'text/html') {
|
|
65
|
+
return new SalesforceApiError(code, htmlMessage(statusCode), { statusCode, details: entry.message });
|
|
66
|
+
}
|
|
67
|
+
return new SalesforceApiError(code, entry.message, { statusCode, details: entry });
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Wraps a jsforce error (string errorCode, no statusCode) as a SalesforceApiError, so `details` and
|
|
71
|
+
* a uniform class are present whichever transport raised it; the original is kept as `cause`.
|
|
72
|
+
* Anything else passes through unchanged. Internal: not exported from either entry point.
|
|
73
|
+
* (isApiError alone cannot be the gate: it now accepts a statusCode-less error.)
|
|
74
|
+
*/
|
|
75
|
+
export function normaliseApiError(err) {
|
|
76
|
+
if (err instanceof Error && !(err instanceof SalesforceApiError)) {
|
|
77
|
+
const { errorCode, statusCode, data } = err;
|
|
78
|
+
if (typeof errorCode === 'string' && statusCode === undefined) {
|
|
79
|
+
return new SalesforceApiError(errorCode, err.message, { details: data, cause: err });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return err;
|
|
5
83
|
}
|
|
6
84
|
//# sourceMappingURL=ApiError.js.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normaliseApiError } from './ApiError.js';
|
|
1
2
|
export class MetadataClientImpl {
|
|
2
3
|
conn;
|
|
3
4
|
constructor(conn) {
|
|
@@ -7,7 +8,13 @@ export class MetadataClientImpl {
|
|
|
7
8
|
// jsforce types `read` to a fixed MetadataType union; we pass through arbitrary
|
|
8
9
|
// type names (e.g. 'SecuritySettings'), so call via a loosened signature.
|
|
9
10
|
const read = this.conn.metadata.read.bind(this.conn.metadata);
|
|
10
|
-
|
|
11
|
+
let res;
|
|
12
|
+
try {
|
|
13
|
+
res = await read(type, fullName);
|
|
14
|
+
}
|
|
15
|
+
catch (e) {
|
|
16
|
+
throw normaliseApiError(e);
|
|
17
|
+
}
|
|
11
18
|
if (res == null)
|
|
12
19
|
return null;
|
|
13
20
|
const rec = Array.isArray(res) ? res[0] : res;
|
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { Readable } from 'node:stream';
|
|
4
|
-
import { pipeline } from 'node:stream/promises';
|
|
5
|
-
import { secureFs } from '../fs/secureFs.js';
|
|
1
|
+
import { SalesforceApiError, apiErrorFromResponse, normaliseApiError } from './ApiError.js';
|
|
2
|
+
import { streamToFile } from './streamToFile.js';
|
|
6
3
|
export class RestClientImpl {
|
|
7
4
|
conn;
|
|
8
5
|
constructor(conn) {
|
|
@@ -11,13 +8,23 @@ export class RestClientImpl {
|
|
|
11
8
|
async get(path) {
|
|
12
9
|
const version = this.conn.getApiVersion();
|
|
13
10
|
const normalised = path.startsWith('/') ? path : `/${path}`;
|
|
14
|
-
|
|
11
|
+
try {
|
|
12
|
+
return await this.conn.request(`/services/data/v${version}${normalised}`);
|
|
13
|
+
}
|
|
14
|
+
catch (e) {
|
|
15
|
+
throw normaliseApiError(e);
|
|
16
|
+
}
|
|
15
17
|
}
|
|
16
18
|
async getRaw(path) {
|
|
17
19
|
const version = this.conn.getApiVersion();
|
|
18
20
|
const normalised = path.startsWith('/') ? path : `/${path}`;
|
|
19
21
|
// jsforce returns the raw body string for non-JSON content types (text/csv here).
|
|
20
|
-
|
|
22
|
+
try {
|
|
23
|
+
return await this.conn.request(`/services/data/v${version}${normalised}`);
|
|
24
|
+
}
|
|
25
|
+
catch (e) {
|
|
26
|
+
throw normaliseApiError(e);
|
|
27
|
+
}
|
|
21
28
|
}
|
|
22
29
|
async getRawToFile(path, destPath) {
|
|
23
30
|
const version = this.conn.getApiVersion();
|
|
@@ -28,18 +35,11 @@ export class RestClientImpl {
|
|
|
28
35
|
const res = await fetch(url, {
|
|
29
36
|
headers: { Authorization: `Bearer ${this.conn.accessToken ?? ''}` },
|
|
30
37
|
});
|
|
31
|
-
if (!res.ok
|
|
32
|
-
throw
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
await pipeline(Readable.fromWeb(res.body), secureFs.createWriteStream(destPath));
|
|
37
|
-
}
|
|
38
|
-
catch (err) {
|
|
39
|
-
await rm(destPath, { force: true }); // never leave a partial file behind
|
|
40
|
-
throw err;
|
|
41
|
-
}
|
|
42
|
-
return (await stat(destPath)).size;
|
|
38
|
+
if (!res.ok)
|
|
39
|
+
throw await apiErrorFromResponse(res);
|
|
40
|
+
if (!res.body)
|
|
41
|
+
throw new SalesforceApiError('EMPTY_BODY', `The org returned no body for ${normalised}.`, { statusCode: res.status });
|
|
42
|
+
return streamToFile(res.body, destPath);
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
//# sourceMappingURL=RestClientImpl.js.map
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { Connection } from '@salesforce/core';
|
|
2
|
+
import { type PagingOptions } from './paging.js';
|
|
2
3
|
import type { QueryResult, SoqlClient } from './SoqlClient.js';
|
|
3
4
|
export declare class SoqlClientImpl implements SoqlClient {
|
|
5
|
+
private readonly paging;
|
|
4
6
|
private readonly anyConn;
|
|
5
|
-
constructor(conn: Connection);
|
|
7
|
+
constructor(conn: Connection, paging?: PagingOptions);
|
|
6
8
|
query<T>(soql: string): Promise<QueryResult<T>>;
|
|
7
9
|
queryAll<T>(soql: string): Promise<T[]>;
|
|
8
10
|
}
|
|
@@ -1,19 +1,34 @@
|
|
|
1
|
+
import { normaliseApiError } from './ApiError.js';
|
|
2
|
+
import { collectPages } from './paging.js';
|
|
1
3
|
export class SoqlClientImpl {
|
|
4
|
+
paging;
|
|
2
5
|
anyConn;
|
|
3
|
-
constructor(conn) {
|
|
6
|
+
constructor(conn, paging = {}) {
|
|
7
|
+
this.paging = paging;
|
|
4
8
|
this.anyConn = conn;
|
|
5
9
|
}
|
|
6
10
|
async query(soql) {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
try {
|
|
12
|
+
const result = await this.anyConn.query(soql);
|
|
13
|
+
return {
|
|
14
|
+
totalSize: result.totalSize,
|
|
15
|
+
done: result.done,
|
|
16
|
+
records: (result.records ?? []),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
catch (e) {
|
|
20
|
+
throw normaliseApiError(e);
|
|
21
|
+
}
|
|
13
22
|
}
|
|
14
23
|
async queryAll(soql) {
|
|
15
|
-
|
|
16
|
-
|
|
24
|
+
try {
|
|
25
|
+
// First page without autoFetch (which caps at 10k), then the shared pager.
|
|
26
|
+
const first = (await this.anyConn.query(soql));
|
|
27
|
+
return await collectPages(first, (url) => this.anyConn.request(url), this.paging);
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
throw normaliseApiError(e);
|
|
31
|
+
}
|
|
17
32
|
}
|
|
18
33
|
}
|
|
19
34
|
//# sourceMappingURL=SoqlClientImpl.js.map
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Connection } from '@salesforce/core';
|
|
2
|
+
import { type PagingOptions } from './paging.js';
|
|
2
3
|
import type { ToolingClient } from './ToolingClient.js';
|
|
3
4
|
export declare class ToolingClientImpl implements ToolingClient {
|
|
4
5
|
private readonly conn;
|
|
6
|
+
private readonly paging;
|
|
5
7
|
private readonly tooling;
|
|
6
|
-
constructor(conn: Connection);
|
|
8
|
+
constructor(conn: Connection, paging?: PagingOptions);
|
|
7
9
|
query<T>(soql: string): Promise<T[]>;
|
|
8
10
|
getRecord<T>(type: string, id: string): Promise<T>;
|
|
9
11
|
}
|
|
@@ -1,29 +1,32 @@
|
|
|
1
|
+
import { normaliseApiError } from './ApiError.js';
|
|
2
|
+
import { collectPages } from './paging.js';
|
|
1
3
|
export class ToolingClientImpl {
|
|
2
4
|
conn;
|
|
5
|
+
paging;
|
|
3
6
|
tooling;
|
|
4
|
-
constructor(conn) {
|
|
7
|
+
constructor(conn, paging = {}) {
|
|
5
8
|
this.conn = conn;
|
|
9
|
+
this.paging = paging;
|
|
6
10
|
this.tooling = conn.tooling;
|
|
7
11
|
}
|
|
8
12
|
async query(soql) {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
while (nextUrl && page < 200) {
|
|
17
|
-
page++;
|
|
18
|
-
const next = await this.conn.request(nextUrl);
|
|
19
|
-
records = records.concat(next.records ?? []);
|
|
20
|
-
nextUrl = next.nextRecordsUrl;
|
|
13
|
+
try {
|
|
14
|
+
const result = await this.tooling.query(soql);
|
|
15
|
+
// conn.request() follows nextRecordsUrl; tooling.queryMore has awkward overload typings.
|
|
16
|
+
return await collectPages(result, (url) => this.conn.request(url), this.paging);
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
throw normaliseApiError(e);
|
|
21
20
|
}
|
|
22
|
-
return records;
|
|
23
21
|
}
|
|
24
22
|
async getRecord(type, id) {
|
|
25
23
|
const version = this.conn.getApiVersion();
|
|
26
|
-
|
|
24
|
+
try {
|
|
25
|
+
return await this.conn.request(`/services/data/v${version}/tooling/sobjects/${type}/${id}/`);
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
throw normaliseApiError(e);
|
|
29
|
+
}
|
|
27
30
|
}
|
|
28
31
|
}
|
|
29
32
|
//# sourceMappingURL=ToolingClientImpl.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { RestClient } from '../RestClient.js';
|
|
2
|
+
import type { FetchTransport } from './FetchTransport.js';
|
|
3
|
+
/** RestClient over FetchTransport. Returns the same values as RestClientImpl for the same org responses. */
|
|
4
|
+
export declare class FetchRestClient implements RestClient {
|
|
5
|
+
private readonly t;
|
|
6
|
+
constructor(t: FetchTransport);
|
|
7
|
+
get<T>(path: string): Promise<T>;
|
|
8
|
+
getRaw(path: string): Promise<string>;
|
|
9
|
+
getRawToFile(path: string, destPath: string): Promise<number>;
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=FetchRestClient.d.ts.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { SalesforceApiError } from '../ApiError.js';
|
|
2
|
+
import { streamToFile } from '../streamToFile.js';
|
|
3
|
+
/** RestClient over FetchTransport. Returns the same values as RestClientImpl for the same org responses. */
|
|
4
|
+
export class FetchRestClient {
|
|
5
|
+
t;
|
|
6
|
+
constructor(t) {
|
|
7
|
+
this.t = t;
|
|
8
|
+
}
|
|
9
|
+
get(path) {
|
|
10
|
+
return this.t.getJson(path);
|
|
11
|
+
}
|
|
12
|
+
getRaw(path) {
|
|
13
|
+
return this.t.getText(path);
|
|
14
|
+
}
|
|
15
|
+
async getRawToFile(path, destPath) {
|
|
16
|
+
const res = await this.t.get(path, '*/*');
|
|
17
|
+
if (!res.body) {
|
|
18
|
+
throw new SalesforceApiError('EMPTY_BODY', `The org returned no body for ${path}.`, { statusCode: res.status });
|
|
19
|
+
}
|
|
20
|
+
return streamToFile(res.body, destPath);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=FetchRestClient.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type PagingOptions } from '../paging.js';
|
|
2
|
+
import type { QueryResult, SoqlClient } from '../SoqlClient.js';
|
|
3
|
+
import type { FetchTransport } from './FetchTransport.js';
|
|
4
|
+
/** SoqlClient over FetchTransport. Returns the same values as SoqlClientImpl for the same org responses. */
|
|
5
|
+
export declare class FetchSoqlClient implements SoqlClient {
|
|
6
|
+
private readonly t;
|
|
7
|
+
private readonly paging;
|
|
8
|
+
constructor(t: FetchTransport, paging?: PagingOptions);
|
|
9
|
+
query<T>(soql: string): Promise<QueryResult<T>>;
|
|
10
|
+
queryAll<T>(soql: string): Promise<T[]>;
|
|
11
|
+
private firstPage;
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=FetchSoqlClient.d.ts.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { collectPages } from '../paging.js';
|
|
2
|
+
/** SoqlClient over FetchTransport. Returns the same values as SoqlClientImpl for the same org responses. */
|
|
3
|
+
export class FetchSoqlClient {
|
|
4
|
+
t;
|
|
5
|
+
paging;
|
|
6
|
+
constructor(t, paging = {}) {
|
|
7
|
+
this.t = t;
|
|
8
|
+
this.paging = paging;
|
|
9
|
+
}
|
|
10
|
+
async query(soql) {
|
|
11
|
+
const page = await this.firstPage(soql);
|
|
12
|
+
return { totalSize: page.totalSize, done: page.done, records: page.records ?? [] };
|
|
13
|
+
}
|
|
14
|
+
async queryAll(soql) {
|
|
15
|
+
const first = await this.firstPage(soql);
|
|
16
|
+
return collectPages(first, (url) => this.t.getJson(url), this.paging);
|
|
17
|
+
}
|
|
18
|
+
firstPage(soql) {
|
|
19
|
+
return this.t.getJson('query?q=' + encodeURIComponent(soql));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=FetchSoqlClient.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type PagingOptions } from '../paging.js';
|
|
2
|
+
import type { ToolingClient } from '../ToolingClient.js';
|
|
3
|
+
import type { FetchTransport } from './FetchTransport.js';
|
|
4
|
+
/** ToolingClient over FetchTransport. Returns the same values as ToolingClientImpl for the same org responses. */
|
|
5
|
+
export declare class FetchToolingClient implements ToolingClient {
|
|
6
|
+
private readonly t;
|
|
7
|
+
private readonly paging;
|
|
8
|
+
constructor(t: FetchTransport, paging?: PagingOptions);
|
|
9
|
+
query<T>(soql: string): Promise<T[]>;
|
|
10
|
+
getRecord<T>(type: string, id: string): Promise<T>;
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=FetchToolingClient.d.ts.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { collectPages } from '../paging.js';
|
|
2
|
+
/** ToolingClient over FetchTransport. Returns the same values as ToolingClientImpl for the same org responses. */
|
|
3
|
+
export class FetchToolingClient {
|
|
4
|
+
t;
|
|
5
|
+
paging;
|
|
6
|
+
constructor(t, paging = {}) {
|
|
7
|
+
this.t = t;
|
|
8
|
+
this.paging = paging;
|
|
9
|
+
}
|
|
10
|
+
async query(soql) {
|
|
11
|
+
const first = await this.t.getJson('tooling/query?q=' + encodeURIComponent(soql));
|
|
12
|
+
return collectPages(first, (url) => this.t.getJson(url), this.paging);
|
|
13
|
+
}
|
|
14
|
+
getRecord(type, id) {
|
|
15
|
+
return this.t.getJson('tooling/sobjects/' + type + '/' + id + '/');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=FetchToolingClient.js.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { AccessToken } from './jwtBearer.js';
|
|
2
|
+
export interface FetchTransportOptions {
|
|
3
|
+
/** Obtains an access token. Called lazily, and again after a 401. */
|
|
4
|
+
auth: () => Promise<AccessToken>;
|
|
5
|
+
/** API version without the leading `v`, e.g. '64.0'. Never defaulted in sf-core. */
|
|
6
|
+
apiVersion: string;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
/** Time to response headers, per request. Defaults to 120 seconds. The body then streams with no limit. */
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The fetch path's single door to the org: URL building, bearer header, timeout, one re-auth
|
|
13
|
+
* after a 401, and error mapping. GET only; there is deliberately no other verb here.
|
|
14
|
+
*/
|
|
15
|
+
export declare class FetchTransport {
|
|
16
|
+
private readonly authFn;
|
|
17
|
+
private readonly apiVersion;
|
|
18
|
+
private readonly fetch;
|
|
19
|
+
private readonly timeoutMs;
|
|
20
|
+
private token;
|
|
21
|
+
constructor(opts: FetchTransportOptions);
|
|
22
|
+
/**
|
|
23
|
+
* GETs `path`. A path starting `/services/` is used as-is (a `nextRecordsUrl`, or `/services/data/`);
|
|
24
|
+
* any other path is prefixed with the versioned data root, matching RestClientImpl.
|
|
25
|
+
*
|
|
26
|
+
* A timeout surfaces as a TimeoutError DOMException (as AbortSignal.timeout raises), deliberately not converted
|
|
27
|
+
* to an ApiError: it is not a Salesforce error response and carries no errorCode.
|
|
28
|
+
*/
|
|
29
|
+
get(path: string, accept?: string): Promise<Response>;
|
|
30
|
+
getJson<T>(path: string): Promise<T>;
|
|
31
|
+
getText(path: string): Promise<string>;
|
|
32
|
+
/** The org's clock, from the Date header of the `/services/data/` listing. */
|
|
33
|
+
serverDate(): Promise<Date>;
|
|
34
|
+
/** The cached token, fetched lazily on first use and shared by concurrent first calls. */
|
|
35
|
+
private currentToken;
|
|
36
|
+
/**
|
|
37
|
+
* A token to retry with after `used` drew a 401. Only the first caller holding `used` starts a new
|
|
38
|
+
* exchange; any later one finds the cache already moved on and reuses that.
|
|
39
|
+
*/
|
|
40
|
+
private refreshedToken;
|
|
41
|
+
private startAuth;
|
|
42
|
+
private send;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=FetchTransport.d.ts.map
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { apiErrorFromResponse } from '../ApiError.js';
|
|
2
|
+
/**
|
|
3
|
+
* The fetch path's single door to the org: URL building, bearer header, timeout, one re-auth
|
|
4
|
+
* after a 401, and error mapping. GET only; there is deliberately no other verb here.
|
|
5
|
+
*/
|
|
6
|
+
export class FetchTransport {
|
|
7
|
+
authFn;
|
|
8
|
+
apiVersion;
|
|
9
|
+
// Named `fetch` so the read-only invariant's scanner sees the one call site in send().
|
|
10
|
+
fetch;
|
|
11
|
+
timeoutMs;
|
|
12
|
+
token;
|
|
13
|
+
constructor(opts) {
|
|
14
|
+
this.authFn = opts.auth;
|
|
15
|
+
this.apiVersion = opts.apiVersion;
|
|
16
|
+
this.fetch = opts.fetch ?? globalThis.fetch;
|
|
17
|
+
this.timeoutMs = opts.timeoutMs ?? 120_000;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* GETs `path`. A path starting `/services/` is used as-is (a `nextRecordsUrl`, or `/services/data/`);
|
|
21
|
+
* any other path is prefixed with the versioned data root, matching RestClientImpl.
|
|
22
|
+
*
|
|
23
|
+
* A timeout surfaces as a TimeoutError DOMException (as AbortSignal.timeout raises), deliberately not converted
|
|
24
|
+
* to an ApiError: it is not a Salesforce error response and carries no errorCode.
|
|
25
|
+
*/
|
|
26
|
+
async get(path, accept = 'application/json') {
|
|
27
|
+
const used = this.currentToken();
|
|
28
|
+
const res = await this.send(await used, path, accept);
|
|
29
|
+
if (res.ok)
|
|
30
|
+
return res;
|
|
31
|
+
if (res.status === 401) {
|
|
32
|
+
// Release the 401's socket before the retry; its body says nothing the retry won't.
|
|
33
|
+
await res.body?.cancel().catch(() => undefined);
|
|
34
|
+
// Each call gets at most one re-auth, and concurrent 401s on the same token share one exchange.
|
|
35
|
+
const retry = await this.send(await this.refreshedToken(used), path, accept);
|
|
36
|
+
if (retry.ok)
|
|
37
|
+
return retry;
|
|
38
|
+
throw await apiErrorFromResponse(retry);
|
|
39
|
+
}
|
|
40
|
+
throw await apiErrorFromResponse(res);
|
|
41
|
+
}
|
|
42
|
+
async getJson(path) {
|
|
43
|
+
const res = await this.get(path);
|
|
44
|
+
return (await res.json());
|
|
45
|
+
}
|
|
46
|
+
async getText(path) {
|
|
47
|
+
const res = await this.get(path, '*/*');
|
|
48
|
+
return res.text();
|
|
49
|
+
}
|
|
50
|
+
/** The org's clock, from the Date header of the `/services/data/` listing. */
|
|
51
|
+
async serverDate() {
|
|
52
|
+
const res = await this.get('/services/data/');
|
|
53
|
+
const header = res.headers.get('date');
|
|
54
|
+
const parsed = header === null ? new Date(Number.NaN) : new Date(header);
|
|
55
|
+
if (Number.isNaN(parsed.getTime()))
|
|
56
|
+
throw new Error('the org response carried no usable Date header');
|
|
57
|
+
return parsed;
|
|
58
|
+
}
|
|
59
|
+
/** The cached token, fetched lazily on first use and shared by concurrent first calls. */
|
|
60
|
+
currentToken() {
|
|
61
|
+
this.token ??= this.startAuth();
|
|
62
|
+
return this.token;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A token to retry with after `used` drew a 401. Only the first caller holding `used` starts a new
|
|
66
|
+
* exchange; any later one finds the cache already moved on and reuses that.
|
|
67
|
+
*/
|
|
68
|
+
refreshedToken(used) {
|
|
69
|
+
if (this.token === used || this.token === undefined)
|
|
70
|
+
this.token = this.startAuth();
|
|
71
|
+
return this.token;
|
|
72
|
+
}
|
|
73
|
+
startAuth() {
|
|
74
|
+
const fresh = this.authFn();
|
|
75
|
+
// A failed auth must not be cached, or every later call would fail with the same rejection.
|
|
76
|
+
fresh.catch(() => {
|
|
77
|
+
if (this.token === fresh)
|
|
78
|
+
this.token = undefined;
|
|
79
|
+
});
|
|
80
|
+
return fresh;
|
|
81
|
+
}
|
|
82
|
+
send(token, path, accept) {
|
|
83
|
+
const rel = path.startsWith('/services/')
|
|
84
|
+
? path
|
|
85
|
+
: `/services/data/v${this.apiVersion}${path.startsWith('/') ? '' : '/'}${path}`;
|
|
86
|
+
// The timer covers time to response headers only and is cleared once they arrive (or the call
|
|
87
|
+
// fails), so a large body, such as an EventLogFile, streams with no time limit.
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const timer = setTimeout(() => controller.abort(new DOMException('The operation timed out.', 'TimeoutError')), this.timeoutMs);
|
|
90
|
+
return this.fetch(`${token.instanceUrl}${rel}`, {
|
|
91
|
+
headers: { Authorization: `Bearer ${token.accessToken}`, Accept: accept },
|
|
92
|
+
signal: controller.signal,
|
|
93
|
+
}).finally(() => clearTimeout(timer));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=FetchTransport.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { FetchRestClient } from './FetchRestClient.js';
|
|
2
|
+
import { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
3
|
+
import { FetchToolingClient } from './FetchToolingClient.js';
|
|
4
|
+
import { FetchTransport } from './FetchTransport.js';
|
|
5
|
+
import { type AccessToken, type JwtBearerConfig } from './jwtBearer.js';
|
|
6
|
+
export { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
7
|
+
export { FetchToolingClient } from './FetchToolingClient.js';
|
|
8
|
+
export { FetchRestClient } from './FetchRestClient.js';
|
|
9
|
+
export { FetchTransport } from './FetchTransport.js';
|
|
10
|
+
export type { FetchTransportOptions } from './FetchTransport.js';
|
|
11
|
+
export { jwtBearerToken, pemSigner } from './jwtBearer.js';
|
|
12
|
+
export type { AccessToken, JwtBearerConfig, Signer } from './jwtBearer.js';
|
|
13
|
+
export type { PagingOptions } from '../paging.js';
|
|
14
|
+
export interface CreateFetchClientsOptions {
|
|
15
|
+
/** A JWT bearer config, or your own token source. */
|
|
16
|
+
auth: JwtBearerConfig | (() => Promise<AccessToken>);
|
|
17
|
+
/** API version without the leading `v`, e.g. '64.0'. */
|
|
18
|
+
apiVersion: string;
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
timeoutMs?: number;
|
|
21
|
+
/** Page cap for queryAll and Tooling query, child relationship pages included. Defaults to 200. */
|
|
22
|
+
maxPages?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Builds the three clients over one shared transport, so they share one token. */
|
|
25
|
+
export declare function createFetchClients(opts: CreateFetchClientsOptions): {
|
|
26
|
+
soql: FetchSoqlClient;
|
|
27
|
+
tooling: FetchToolingClient;
|
|
28
|
+
rest: FetchRestClient;
|
|
29
|
+
transport: FetchTransport;
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { FetchRestClient } from './FetchRestClient.js';
|
|
2
|
+
import { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
3
|
+
import { FetchToolingClient } from './FetchToolingClient.js';
|
|
4
|
+
import { FetchTransport } from './FetchTransport.js';
|
|
5
|
+
import { jwtBearerToken } from './jwtBearer.js';
|
|
6
|
+
export { FetchSoqlClient } from './FetchSoqlClient.js';
|
|
7
|
+
export { FetchToolingClient } from './FetchToolingClient.js';
|
|
8
|
+
export { FetchRestClient } from './FetchRestClient.js';
|
|
9
|
+
export { FetchTransport } from './FetchTransport.js';
|
|
10
|
+
export { jwtBearerToken, pemSigner } from './jwtBearer.js';
|
|
11
|
+
/** Builds the three clients over one shared transport, so they share one token. */
|
|
12
|
+
export function createFetchClients(opts) {
|
|
13
|
+
const auth = typeof opts.auth === 'function'
|
|
14
|
+
? opts.auth
|
|
15
|
+
: (() => {
|
|
16
|
+
const config = opts.auth;
|
|
17
|
+
return () => jwtBearerToken(config, { fetch: opts.fetch });
|
|
18
|
+
})();
|
|
19
|
+
const transport = new FetchTransport({
|
|
20
|
+
auth,
|
|
21
|
+
apiVersion: opts.apiVersion,
|
|
22
|
+
fetch: opts.fetch,
|
|
23
|
+
timeoutMs: opts.timeoutMs,
|
|
24
|
+
});
|
|
25
|
+
return {
|
|
26
|
+
soql: new FetchSoqlClient(transport, { maxPages: opts.maxPages }),
|
|
27
|
+
tooling: new FetchToolingClient(transport, { maxPages: opts.maxPages }),
|
|
28
|
+
rest: new FetchRestClient(transport),
|
|
29
|
+
transport,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** The global fetch signature, named once so the call site below can shadow `fetch` locally. */
|
|
2
|
+
type FetchFn = typeof fetch;
|
|
3
|
+
/** Signs the JWT signing input with RS256 and returns the raw signature bytes. */
|
|
4
|
+
export type Signer = (signingInput: string) => Promise<Buffer>;
|
|
5
|
+
/**
|
|
6
|
+
* A signer over a PEM held in this process.
|
|
7
|
+
*
|
|
8
|
+
* Vercel, GitHub Actions and Lambda environment variables all round-trip PEM newlines as the
|
|
9
|
+
* literal two characters `\n`; a key with escaped newlines fails at signing time, far from the
|
|
10
|
+
* cause, so they are restored here.
|
|
11
|
+
*/
|
|
12
|
+
export declare function pemSigner(privateKeyPem: string): Signer;
|
|
13
|
+
export interface JwtBearerConfig {
|
|
14
|
+
/** External Client App consumer key. Becomes the JWT `iss`. */
|
|
15
|
+
clientId: string;
|
|
16
|
+
/** The Salesforce username to run as. Becomes the JWT `sub`. */
|
|
17
|
+
username: string;
|
|
18
|
+
/** Token endpoint host: login.salesforce.com, test.salesforce.com or a My Domain URL. */
|
|
19
|
+
loginUrl: string;
|
|
20
|
+
/** The `aud` claim. Defaults to `loginUrl`. */
|
|
21
|
+
audience?: string;
|
|
22
|
+
sign: Signer;
|
|
23
|
+
}
|
|
24
|
+
export interface AccessToken {
|
|
25
|
+
accessToken: string;
|
|
26
|
+
instanceUrl: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Exchange a signed assertion for an access token (OAuth 2.0 JWT bearer flow).
|
|
30
|
+
*
|
|
31
|
+
* This is the only request in sf-core that is not a GET. It authenticates and writes no org data.
|
|
32
|
+
* The `exp` claim must be within five minutes of now or Salesforce rejects it; three minutes leaves
|
|
33
|
+
* room for clock skew without approaching that ceiling. There is no `iat` or `jti`: Salesforce
|
|
34
|
+
* ignores both. Salesforce returns no `expires_in` for this flow, so callers treat a 401 as expiry.
|
|
35
|
+
*
|
|
36
|
+
* Neither the private key nor the access token ever appears in a thrown error.
|
|
37
|
+
*/
|
|
38
|
+
export declare function jwtBearerToken(config: JwtBearerConfig, deps?: {
|
|
39
|
+
fetch?: FetchFn;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
}): Promise<AccessToken>;
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=jwtBearer.d.ts.map
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { createSign } from 'node:crypto';
|
|
2
|
+
import { SalesforceApiError } from '../ApiError.js';
|
|
3
|
+
/**
|
|
4
|
+
* A signer over a PEM held in this process.
|
|
5
|
+
*
|
|
6
|
+
* Vercel, GitHub Actions and Lambda environment variables all round-trip PEM newlines as the
|
|
7
|
+
* literal two characters `\n`; a key with escaped newlines fails at signing time, far from the
|
|
8
|
+
* cause, so they are restored here.
|
|
9
|
+
*/
|
|
10
|
+
export function pemSigner(privateKeyPem) {
|
|
11
|
+
const pem = privateKeyPem.replace(/\\n/g, '\n');
|
|
12
|
+
if (pem.trim() === '') {
|
|
13
|
+
throw new Error("The JWT signing key is empty. It is the private half of the certificate uploaded to the org's " +
|
|
14
|
+
'External Client App; without it the org cannot be reached.');
|
|
15
|
+
}
|
|
16
|
+
// Synchronous under the hood, and deliberately still a promise: other signers (a KMS) are network calls.
|
|
17
|
+
return (signingInput) => Promise.resolve(createSign('RSA-SHA256').update(signingInput).sign(pem));
|
|
18
|
+
}
|
|
19
|
+
const str = (v) => (typeof v === 'string' && v !== '' ? v : undefined);
|
|
20
|
+
/** base64url without padding, as JWS requires. */
|
|
21
|
+
const b64url = (input) => (typeof input === 'string' ? Buffer.from(input, 'utf8') : input)
|
|
22
|
+
.toString('base64url');
|
|
23
|
+
const truncate = (s, max = 300) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
|
|
24
|
+
/**
|
|
25
|
+
* Exchange a signed assertion for an access token (OAuth 2.0 JWT bearer flow).
|
|
26
|
+
*
|
|
27
|
+
* This is the only request in sf-core that is not a GET. It authenticates and writes no org data.
|
|
28
|
+
* The `exp` claim must be within five minutes of now or Salesforce rejects it; three minutes leaves
|
|
29
|
+
* room for clock skew without approaching that ceiling. There is no `iat` or `jti`: Salesforce
|
|
30
|
+
* ignores both. Salesforce returns no `expires_in` for this flow, so callers treat a 401 as expiry.
|
|
31
|
+
*
|
|
32
|
+
* Neither the private key nor the access token ever appears in a thrown error.
|
|
33
|
+
*/
|
|
34
|
+
export async function jwtBearerToken(config, deps = {}) {
|
|
35
|
+
// The assertion is a three-minute bearer credential; never let it travel over cleartext.
|
|
36
|
+
let loginProtocol;
|
|
37
|
+
try {
|
|
38
|
+
loginProtocol = new URL(config.loginUrl).protocol;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
loginProtocol = undefined;
|
|
42
|
+
}
|
|
43
|
+
if (loginProtocol !== 'https:') {
|
|
44
|
+
throw new SalesforceApiError('INVALID_LOGIN_URL', 'The login URL must be a valid https URL; nothing was signed or sent.');
|
|
45
|
+
}
|
|
46
|
+
const now = deps.now ?? Date.now;
|
|
47
|
+
const header = b64url(JSON.stringify({ alg: 'RS256' }));
|
|
48
|
+
const claims = b64url(JSON.stringify({
|
|
49
|
+
iss: config.clientId,
|
|
50
|
+
sub: config.username,
|
|
51
|
+
aud: config.audience ?? config.loginUrl,
|
|
52
|
+
exp: Math.floor(now() / 1000) + 180,
|
|
53
|
+
}));
|
|
54
|
+
const signingInput = `${header}.${claims}`;
|
|
55
|
+
const assertion = `${signingInput}.${b64url(await config.sign(signingInput))}`;
|
|
56
|
+
const body = new URLSearchParams({
|
|
57
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
|
58
|
+
assertion,
|
|
59
|
+
}).toString();
|
|
60
|
+
const fetch = deps.fetch ?? globalThis.fetch;
|
|
61
|
+
const res = await fetch(`${config.loginUrl.replace(/\/$/, '')}/services/oauth2/token`, {
|
|
62
|
+
method: 'POST', // invariant:allow — OAuth token exchange; authenticates, writes no org data
|
|
63
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
64
|
+
body,
|
|
65
|
+
});
|
|
66
|
+
const text = await res.text();
|
|
67
|
+
let parsed;
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(text);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
throw new SalesforceApiError('TOKEN_ENDPOINT_NOT_JSON', truncate(text), { statusCode: res.status });
|
|
73
|
+
}
|
|
74
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
75
|
+
parsed = {};
|
|
76
|
+
if (!res.ok || typeof parsed.access_token !== 'string' || parsed.access_token === '') {
|
|
77
|
+
// Never carry a token into details, even on a failed response.
|
|
78
|
+
const { access_token: _dropped, ...safe } = parsed;
|
|
79
|
+
throw new SalesforceApiError(str(parsed.error) ?? 'TOKEN_REQUEST_FAILED', explainTokenError(parsed), {
|
|
80
|
+
statusCode: res.status,
|
|
81
|
+
details: safe,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const instanceUrl = (parsed.instance_url ?? '').replace(/\/$/, '');
|
|
85
|
+
let protocol;
|
|
86
|
+
try {
|
|
87
|
+
protocol = new URL(instanceUrl).protocol;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
protocol = undefined;
|
|
91
|
+
}
|
|
92
|
+
if (protocol !== 'https:') {
|
|
93
|
+
throw new SalesforceApiError('INVALID_INSTANCE_URL', 'The token endpoint returned an instance_url that is missing or not https; refusing to send the access token there.', { statusCode: res.status });
|
|
94
|
+
}
|
|
95
|
+
return { accessToken: parsed.access_token, instanceUrl };
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The JWT bearer flow's failures are opaque: `invalid_grant` covers at least four unrelated
|
|
99
|
+
* misconfigurations. The two that actually happen are named here.
|
|
100
|
+
*/
|
|
101
|
+
function explainTokenError(parsed) {
|
|
102
|
+
const base = str(parsed.error_description) ?? str(parsed.error) ?? 'The token request failed.';
|
|
103
|
+
if (parsed.error === 'invalid_grant') {
|
|
104
|
+
return (`${base} (for the JWT bearer flow this usually means one of: the user is not pre-authorised ` +
|
|
105
|
+
'for the External Client App (assign the permission set, or set the app policy to admin-approved ' +
|
|
106
|
+
'users); the certificate in the External Client App does not match the signing private key; the ' +
|
|
107
|
+
'username is wrong for this org; or the app was saved less than ten minutes ago and has not ' +
|
|
108
|
+
'propagated yet.)');
|
|
109
|
+
}
|
|
110
|
+
if (parsed.error === 'invalid_client_id') {
|
|
111
|
+
return `${base} (the consumer key does not match an External Client App in this org.)`;
|
|
112
|
+
}
|
|
113
|
+
return base;
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=jwtBearer.js.map
|
package/lib/api/index.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ export type { QueryResult, SoqlClient } from './SoqlClient.js';
|
|
|
2
2
|
export type { ToolingClient } from './ToolingClient.js';
|
|
3
3
|
export type { RestClient } from './RestClient.js';
|
|
4
4
|
export type { ApiError } from './ApiError.js';
|
|
5
|
-
export {
|
|
5
|
+
export type { PagingOptions } from './paging.js';
|
|
6
|
+
export { isApiError, SalesforceApiError } from './ApiError.js';
|
|
6
7
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
7
8
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
8
9
|
export { RestClientImpl } from './RestClientImpl.js';
|
package/lib/api/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { isApiError } from './ApiError.js';
|
|
1
|
+
export { isApiError, SalesforceApiError } from './ApiError.js';
|
|
2
2
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
3
3
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
4
4
|
export { RestClientImpl } from './RestClientImpl.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** One page of a SOQL or Tooling query response, in Salesforce's own shape. */
|
|
2
|
+
export interface QueryPage<T> {
|
|
3
|
+
totalSize: number;
|
|
4
|
+
done: boolean;
|
|
5
|
+
records: T[];
|
|
6
|
+
nextRecordsUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
/** Default cap on pages followed: 200 pages of up to 2000 rows is 400 000 records. */
|
|
9
|
+
export declare const MAX_QUERY_PAGES = 200;
|
|
10
|
+
/** Options for the query clients' paging. */
|
|
11
|
+
export interface PagingOptions {
|
|
12
|
+
/** Most pages one queryAll may follow, child relationship pages included. Defaults to MAX_QUERY_PAGES. */
|
|
13
|
+
maxPages?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Follow nextRecordsUrl until it is absent and return every record. Exceeding the page cap
|
|
17
|
+
* (`maxPages`, default MAX_QUERY_PAGES) throws; a partial result is never returned.
|
|
18
|
+
*
|
|
19
|
+
* A child relationship (subquery) field that carries its own nextRecordsUrl is followed too,
|
|
20
|
+
* as jsforce's autoFetch did (query.js `_fetchAllSubqueryRecords`): the field becomes
|
|
21
|
+
* `{ ...field, records: <all>, done: true, nextRecordsUrl: undefined }`. Child pages count
|
|
22
|
+
* toward the page cap.
|
|
23
|
+
*/
|
|
24
|
+
export declare function collectPages<T>(first: QueryPage<T>, fetchNext: (nextRecordsUrl: string) => Promise<QueryPage<T>>, opts?: PagingOptions): Promise<T[]>;
|
|
25
|
+
//# sourceMappingURL=paging.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { SalesforceApiError } from './ApiError.js';
|
|
2
|
+
/** Default cap on pages followed: 200 pages of up to 2000 rows is 400 000 records. */
|
|
3
|
+
export const MAX_QUERY_PAGES = 200;
|
|
4
|
+
/**
|
|
5
|
+
* Follow nextRecordsUrl until it is absent and return every record. Exceeding the page cap
|
|
6
|
+
* (`maxPages`, default MAX_QUERY_PAGES) throws; a partial result is never returned.
|
|
7
|
+
*
|
|
8
|
+
* A child relationship (subquery) field that carries its own nextRecordsUrl is followed too,
|
|
9
|
+
* as jsforce's autoFetch did (query.js `_fetchAllSubqueryRecords`): the field becomes
|
|
10
|
+
* `{ ...field, records: <all>, done: true, nextRecordsUrl: undefined }`. Child pages count
|
|
11
|
+
* toward the page cap.
|
|
12
|
+
*/
|
|
13
|
+
export async function collectPages(first, fetchNext, opts = {}) {
|
|
14
|
+
const maxPages = opts.maxPages ?? MAX_QUERY_PAGES;
|
|
15
|
+
if (!Number.isInteger(maxPages) || maxPages < 1) {
|
|
16
|
+
throw new RangeError(`maxPages must be a positive integer; got ${String(maxPages)}.`);
|
|
17
|
+
}
|
|
18
|
+
let pages = 1;
|
|
19
|
+
const follow = async (url) => {
|
|
20
|
+
if (pages >= maxPages) {
|
|
21
|
+
throw new SalesforceApiError('QUERY_TOO_LARGE', `The query returned more than ${maxPages} pages; narrow the query (for sf-evidence, a shorter time slice). No partial result is returned.`);
|
|
22
|
+
}
|
|
23
|
+
pages++;
|
|
24
|
+
return (await fetchNext(url));
|
|
25
|
+
};
|
|
26
|
+
let page = first;
|
|
27
|
+
let records = await expandChildPages(page.records ?? [], follow);
|
|
28
|
+
while (page.nextRecordsUrl) {
|
|
29
|
+
page = await follow(page.nextRecordsUrl);
|
|
30
|
+
records = records.concat(await expandChildPages(page.records ?? [], follow));
|
|
31
|
+
}
|
|
32
|
+
return records;
|
|
33
|
+
}
|
|
34
|
+
/** Each record with every partial child relationship followed to completion, in order. */
|
|
35
|
+
async function expandChildPages(records, follow) {
|
|
36
|
+
const out = [];
|
|
37
|
+
for (const record of records) {
|
|
38
|
+
if (typeof record !== 'object' || record === null) {
|
|
39
|
+
out.push(record);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
let expanded;
|
|
43
|
+
for (const [key, field] of Object.entries(record)) {
|
|
44
|
+
// jsforce's test: an object with both `records` and `nextRecordsUrl` keys.
|
|
45
|
+
if (!field || typeof field !== 'object' || !('records' in field) || !('nextRecordsUrl' in field))
|
|
46
|
+
continue;
|
|
47
|
+
const child = field;
|
|
48
|
+
let all = child.records ? [...child.records] : [];
|
|
49
|
+
let next = child.records ? child.nextRecordsUrl : undefined;
|
|
50
|
+
while (next) {
|
|
51
|
+
const more = await follow(next);
|
|
52
|
+
all = all.concat(more.records ?? []);
|
|
53
|
+
next = more.nextRecordsUrl;
|
|
54
|
+
}
|
|
55
|
+
expanded ??= { ...record };
|
|
56
|
+
expanded[key] = { ...child, records: all, done: true, nextRecordsUrl: undefined };
|
|
57
|
+
}
|
|
58
|
+
out.push((expanded ?? record));
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=paging.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streams a response body to disk without ever holding it as a JS string (which would fail on logs
|
|
3
|
+
* larger than ~512 MB). Creates parent directories, never leaves a partial file behind, and returns
|
|
4
|
+
* the number of bytes written. Shared by both REST clients.
|
|
5
|
+
*/
|
|
6
|
+
export declare function streamToFile(body: ReadableStream<Uint8Array>, destPath: string): Promise<number>;
|
|
7
|
+
//# sourceMappingURL=streamToFile.d.ts.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { rm, stat } from 'node:fs/promises';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { secureFs } from '../fs/secureFs.js';
|
|
6
|
+
/**
|
|
7
|
+
* Streams a response body to disk without ever holding it as a JS string (which would fail on logs
|
|
8
|
+
* larger than ~512 MB). Creates parent directories, never leaves a partial file behind, and returns
|
|
9
|
+
* the number of bytes written. Shared by both REST clients.
|
|
10
|
+
*/
|
|
11
|
+
export async function streamToFile(body, destPath) {
|
|
12
|
+
await secureFs.mkdir(dirname(destPath), { recursive: true });
|
|
13
|
+
try {
|
|
14
|
+
await pipeline(Readable.fromWeb(body), secureFs.createWriteStream(destPath));
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
await rm(destPath, { force: true }); // never leave a partial file behind
|
|
18
|
+
throw err;
|
|
19
|
+
}
|
|
20
|
+
return (await stat(destPath)).size;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=streamToFile.js.map
|
|
@@ -11,10 +11,13 @@ import { isApiError } from '../api/ApiError.js';
|
|
|
11
11
|
* vs. grant a permission), so the distinction is worth surfacing.
|
|
12
12
|
*/
|
|
13
13
|
export function classifyEventLogAccessError(err) {
|
|
14
|
+
// Classify on errorCode only. The fetch transport keeps the HTTP status and jsforce does not, so
|
|
15
|
+
// reading statusCode would classify the same org error differently on the two transports.
|
|
14
16
|
if (isApiError(err)) {
|
|
15
|
-
|
|
17
|
+
const code = err.errorCode;
|
|
18
|
+
if (/ACCESS|INSUFFICIENT/i.test(code) || code === 'ERROR_HTTP_403')
|
|
16
19
|
return 'no-permission';
|
|
17
|
-
if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(
|
|
20
|
+
if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(code) || code === 'ERROR_HTTP_404' || code === 'ERROR_HTTP_400') {
|
|
18
21
|
return 'not-enabled';
|
|
19
22
|
}
|
|
20
23
|
}
|
package/lib/fetch.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export * from './api/fetch/index.js';
|
|
2
|
+
export { isApiError, SalesforceApiError } from './api/ApiError.js';
|
|
3
|
+
export type { ApiError } from './api/ApiError.js';
|
|
4
|
+
export type { QueryResult, SoqlClient } from './api/SoqlClient.js';
|
|
5
|
+
export type { ToolingClient } from './api/ToolingClient.js';
|
|
6
|
+
export type { RestClient } from './api/RestClient.js';
|
|
7
|
+
//# sourceMappingURL=fetch.d.ts.map
|
package/lib/fetch.js
ADDED
package/lib/index.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// @cclabsnz/sf-core — shared platform layer for CloudCounsel Salesforce sf plugins.
|
|
2
2
|
// --- API clients ---
|
|
3
3
|
export * from './api/index.js';
|
|
4
|
+
export * from './api/fetch/index.js';
|
|
4
5
|
export { MetadataClientImpl } from './api/MetadataClientImpl.js';
|
|
5
6
|
export { EMPTY_METRICS } from './context/OrgMetrics.js';
|
|
6
7
|
// --- Event log ---
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cclabsnz/sf-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Shared platform layer for CloudCounsel Salesforce sf plugins — API clients, org context, event log pull, report shell, and versioned IR schemas.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
"types": "./lib/index.d.ts",
|
|
12
12
|
"default": "./lib/index.js"
|
|
13
13
|
},
|
|
14
|
+
"./fetch": {
|
|
15
|
+
"types": "./lib/fetch.d.ts",
|
|
16
|
+
"default": "./lib/fetch.js"
|
|
17
|
+
},
|
|
14
18
|
"./testing": {
|
|
15
19
|
"types": "./lib/testing/invariants.d.ts",
|
|
16
20
|
"default": "./lib/testing/invariants.js"
|
|
@@ -28,6 +32,7 @@
|
|
|
28
32
|
},
|
|
29
33
|
"devDependencies": {
|
|
30
34
|
"@jest/globals": "^29.7.0",
|
|
35
|
+
"@jsforce/jsforce-node": "3.10.19",
|
|
31
36
|
"@salesforce/core": "^9",
|
|
32
37
|
"@types/jest": "^29",
|
|
33
38
|
"@types/node": "^22",
|
|
@@ -82,6 +87,11 @@
|
|
|
82
87
|
"peerDependencies": {
|
|
83
88
|
"@salesforce/core": "^8 || ^9"
|
|
84
89
|
},
|
|
90
|
+
"peerDependenciesMeta": {
|
|
91
|
+
"@salesforce/core": {
|
|
92
|
+
"optional": true
|
|
93
|
+
}
|
|
94
|
+
},
|
|
85
95
|
"dependencies": {
|
|
86
96
|
"ajv": "^8.20.0"
|
|
87
97
|
}
|