@cclabsnz/sf-core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +89 -2
  2. package/README.md +36 -4
  3. package/lib/api/ApiError.d.ts +33 -1
  4. package/lib/api/ApiError.js +81 -3
  5. package/lib/api/MetadataClientImpl.js +8 -1
  6. package/lib/api/RestClientImpl.js +19 -19
  7. package/lib/api/SoqlClientImpl.d.ts +3 -1
  8. package/lib/api/SoqlClientImpl.js +24 -9
  9. package/lib/api/ToolingClientImpl.d.ts +3 -1
  10. package/lib/api/ToolingClientImpl.js +18 -15
  11. package/lib/api/fetch/FetchRestClient.d.ts +11 -0
  12. package/lib/api/fetch/FetchRestClient.js +23 -0
  13. package/lib/api/fetch/FetchSoqlClient.d.ts +13 -0
  14. package/lib/api/fetch/FetchSoqlClient.js +22 -0
  15. package/lib/api/fetch/FetchToolingClient.d.ts +12 -0
  16. package/lib/api/fetch/FetchToolingClient.js +18 -0
  17. package/lib/api/fetch/FetchTransport.d.ts +44 -0
  18. package/lib/api/fetch/FetchTransport.js +96 -0
  19. package/lib/api/fetch/index.d.ts +31 -0
  20. package/lib/api/fetch/index.js +32 -0
  21. package/lib/api/fetch/jwtBearer.d.ts +43 -0
  22. package/lib/api/fetch/jwtBearer.js +115 -0
  23. package/lib/api/index.d.ts +2 -1
  24. package/lib/api/index.js +1 -1
  25. package/lib/api/paging.d.ts +25 -0
  26. package/lib/api/paging.js +62 -0
  27. package/lib/api/streamToFile.d.ts +7 -0
  28. package/lib/api/streamToFile.js +22 -0
  29. package/lib/crypto/bundleCrypto.d.ts +30 -1
  30. package/lib/crypto/bundleCrypto.js +269 -9
  31. package/lib/events/eventLogAccess.js +5 -2
  32. package/lib/fetch.d.ts +7 -0
  33. package/lib/fetch.js +4 -0
  34. package/lib/graph/validate.js +1 -1
  35. package/lib/index.d.ts +2 -1
  36. package/lib/index.js +2 -1
  37. package/lib/storage/ObjectStore.d.ts +26 -0
  38. package/lib/storage/ObjectStore.js +2 -0
  39. package/lib/storage/S3ObjectStoreImpl.d.ts +12 -0
  40. package/lib/storage/S3ObjectStoreImpl.js +122 -0
  41. package/lib/storage/errors.d.ts +11 -0
  42. package/lib/storage/errors.js +19 -0
  43. package/lib/storage/index.d.ts +7 -0
  44. package/lib/storage/index.js +4 -0
  45. package/lib/storage/s3Location.d.ts +29 -0
  46. package/lib/storage/s3Location.js +63 -0
  47. package/lib/storage/testing/MemoryObjectStore.d.ts +32 -0
  48. package/lib/storage/testing/MemoryObjectStore.js +79 -0
  49. package/lib/storage.d.ts +2 -0
  50. package/lib/storage.js +4 -0
  51. package/lib/storageTesting.d.ts +2 -0
  52. package/lib/storageTesting.js +3 -0
  53. package/package.json +25 -2
package/CHANGELOG.md CHANGED
@@ -10,7 +10,93 @@ CycloneDX SBOM for the build.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
- Nothing yet.
13
+ ## [0.13.0] — 2026-11-27
14
+
15
+ ### Added
16
+
17
+ - **`@cclabsnz/sf-core/storage`: an S3-compatible `ObjectStore`.** `createS3ObjectStore` connects to
18
+ AWS S3, Cloudflare R2 or MinIO with whole-object `get`, `put`, create-only `putIfAbsent`
19
+ (`If-None-Match: *`) and paged `list`. `resolveS3Endpoint`, `parseS3Uri`, `BucketMissingError`
20
+ and `StorageAccessDeniedError` come with it, and credential values are redacted from every
21
+ error it raises. `@aws-sdk/client-s3` is an optional peer, loaded only when a store is created.
22
+ `@cclabsnz/sf-core/storage/testing` exports `MemoryObjectStore` for tests.
23
+ `s3Host(bucket, endpoint)` names the host the client actually contacts (`<bucket>.s3.<region>.amazonaws.com`
24
+ for AWS, or path-style `s3.<region>.amazonaws.com` for bucket names that are not one DNS label;
25
+ the endpoint's host for a custom endpoint), so tools can list network destinations truthfully.
26
+ Redaction covers credential values set in the environment (`AWS_ACCESS_KEY_ID`,
27
+ `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`) only.
28
+ - **Chunked, streaming encryption: version 2 of the `SFEB` format.** `createEncryptStream` and
29
+ `createDecryptStream` are Node `Transform`s that encrypt and decrypt a file of any size while
30
+ holding at most one chunk (64 KiB by default) in memory. Each chunk is sealed with AES-256-GCM
31
+ under the STREAM construction, so reordered, repeated, dropped or appended chunks, and a file
32
+ cut at a chunk boundary, all fail with `DecryptionError`. The header carries the scrypt
33
+ parameters and chunk size, both bounded before any key is derived. A stream refuses a version 1
34
+ input over 64 MiB rather than buffering it whole.
35
+ - `ENCRYPTED_PREFIX`, the 4-byte `SFEB` prefix shared by every format version.
36
+
37
+ ### Changed
38
+
39
+ - `decryptWithPassphrase` and `createDecryptStream` read both versions; version 1 files are
40
+ unchanged and still readable. `isEncryptedBuffer` now also recognises version 2, and an
41
+ unknown version fails as "Unsupported SFEB format version N" instead of "not in recognized SFEB
42
+ encrypted format".
43
+ - **A header's scrypt settings are bounded together, not only one by one**, for both versions:
44
+ at most 256 MiB of memory (128·N·r) and four times the default's work (N·r·p). Settings that
45
+ passed each per-field limit could still demand about 12 s of blocking work or more than 1 GiB
46
+ per file. A key-derivation failure is now a `DecryptionError`, never a `RangeError`. Files
47
+ written with the defaults are unaffected.
48
+
49
+ ## [0.12.0] — 2026-10-23
50
+
51
+ ### Breaking
52
+
53
+ - **`ApiError.statusCode` is now optional** (`number | undefined`). jsforce keeps no HTTP status
54
+ for a JSON error body, so errors from the `Connection` clients carry none.
55
+ - **`Connection`-path errors are now `SalesforceApiError`, not jsforce's `HttpApiError`.** The
56
+ details move from `err.data` to `err.details`, and `err instanceof HttpApiError` is now false.
57
+ `err.name` and `err.errorCode` are unchanged, and the original jsforce error is kept as
58
+ `err.cause`.
59
+ - **`queryAll` no longer honours `maxQueryLimit` or `SF_ORG_MAX_QUERY_LIMIT`.** It pages to
60
+ completion and throws `QUERY_TOO_LARGE` past a page cap (default 200 pages, child
61
+ relationship pages included) instead of truncating. Set the cap with `{ maxPages }` as the
62
+ second constructor argument of `SoqlClientImpl`, `ToolingClientImpl`, `FetchSoqlClient` and
63
+ `FetchToolingClient`, or `maxPages` on `createFetchClients`.
64
+ - **`RestClientImpl.getRawToFile` throws an `ApiError`** (built from the response, or
65
+ `EMPTY_BODY` when there is no body) instead of a plain "Download failed" `Error`.
66
+ - **An error response with no Salesforce code is `ERROR_HTTP_<status>`**, with the raw body as
67
+ the message, and an array of more than one error is `MULTIPLE_API_ERRORS`, exactly as jsforce
68
+ reports them. Both transports now raise the same code for the same response.
69
+
70
+ ### Added
71
+
72
+ - **Fetch transport and `@cclabsnz/sf-core/fetch`.** `createFetchClients`, `FetchTransport`,
73
+ `FetchSoqlClient`, `FetchToolingClient`, `FetchRestClient`, `jwtBearerToken` and `pemSigner`:
74
+ the same `SoqlClient`, `ToolingClient` and `RestClient` interfaces over global `fetch`, with a
75
+ JWT bearer login, for hosts that cannot carry `@salesforce/core`. The entry point reaches
76
+ neither `@salesforce/core` nor jsforce. The only non-GET request is the OAuth token exchange,
77
+ in one file. `loginUrl` and the returned `instance_url` must be https. Concurrent requests
78
+ that hit an expired token share one re-authentication.
79
+ - `SalesforceApiError`, `PagingOptions`, and a shared paging helper used by both transports.
80
+
81
+ ### Fixed
82
+
83
+ - **`isApiError` now accepts real Salesforce errors.** jsforce's `HttpApiError` carries
84
+ `errorCode` but no `statusCode`, so every real org error failed the check and consumers that
85
+ classify degradations never matched one. Errors from the `Connection` clients are now wrapped
86
+ as `SalesforceApiError`.
87
+ - **`SoqlClientImpl.queryAll` no longer truncates at 10,000 records.** It followed
88
+ `autoFetchQuery`, which stops at the configured cap with only a warning.
89
+ - **`ToolingClientImpl.query` no longer stops silently after 200 pages.** Both clients now throw
90
+ `QUERY_TOO_LARGE` instead of returning a partial result.
91
+ - **Child relationship (subquery) results are complete.** A subquery field that carries its own
92
+ `nextRecordsUrl` is followed to the end on both transports, as `autoFetchQuery` used to do.
93
+ - **`classifyEventLogAccessError` reads only `errorCode`**, so an org error classifies the same
94
+ way whichever transport raised it. `ERROR_HTTP_403` is `no-permission`; `ERROR_HTTP_404` and
95
+ `ERROR_HTTP_400` are `not-enabled`.
96
+
97
+ ### Changed
98
+
99
+ - `@salesforce/core` is now an optional peer dependency.
14
100
 
15
101
  ## [0.11.0] — 2026-10-16
16
102
 
@@ -259,7 +345,8 @@ hourly capture path that dependants build on.
259
345
 
260
346
  Initial internal releases: API clients, org context, findings model and report rendering.
261
347
 
262
- [Unreleased]: https://github.com/cclabsnz/sf-core/compare/v0.4.0...HEAD
348
+ [Unreleased]: https://github.com/cclabsnz/sf-core/compare/v0.13.0...HEAD
349
+ [0.13.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.13.0
263
350
  [0.4.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.4.0
264
351
  [0.3.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.3.0
265
352
  [0.2.0]: https://github.com/cclabsnz/sf-core/releases/tag/v0.2.0
package/README.md CHANGED
@@ -21,7 +21,8 @@ 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
+ | **Storage** | `ObjectStore`, an S3-compatible connection (AWS S3, Cloudflare R2, MinIO) from `@cclabsnz/sf-core/storage`, with `MemoryObjectStore` in `@cclabsnz/sf-core/storage/testing`. `@aws-sdk/client-s3` is an optional peer, loaded only when a store is created |
25
+ | **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
26
  | **Platform behaviour** | `FlowRepository`, `ApexRepository`, `isSalesforceId`, `describeSalesforceError`, `mapWithConcurrency` |
26
27
  | **Event capture** | `EventBaselineStore`, `RTE_CATALOG`, `pullEventLogs`, `pullRealtimeEvents`, `CaptureManifest`: bounded, resumable EventLogFile and Real-Time Event pulls |
27
28
  | **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 +85,36 @@ await mapWithConcurrency(versions, 8, async (v) => {
84
85
  });
85
86
  ```
86
87
 
88
+ ### Without @salesforce/core
89
+
90
+ `@cclabsnz/sf-core/fetch` carries no `@salesforce/core` or jsforce, so it fits a Lambda or edge
91
+ bundle. `@salesforce/core` is an optional peer dependency. It logs in with the JWT bearer flow
92
+ (an External Client App with a certificate) and implements `SoqlClient`, `ToolingClient` and
93
+ `RestClient`:
94
+
95
+ ```ts
96
+ import { createFetchClients, pemSigner } from '@cclabsnz/sf-core/fetch';
97
+
98
+ const { soql, tooling, rest } = createFetchClients({
99
+ apiVersion: '64.0',
100
+ auth: {
101
+ clientId: process.env.SF_CLIENT_ID!,
102
+ username: process.env.SF_USERNAME!,
103
+ loginUrl: 'https://login.salesforce.com', // https only
104
+ sign: pemSigner(process.env.SF_PRIVATE_KEY!),
105
+ },
106
+ });
107
+
108
+ const rows = await soql.queryAll<{ Id: string }>('SELECT Id FROM Account');
109
+ ```
110
+
111
+ Both transports return the same values and raise the same errors for the same org responses.
112
+ `queryAll` follows every page, child relationship pages included, and throws `QUERY_TOO_LARGE`
113
+ rather than return a partial result once it passes the page cap: 200 pages by default, or
114
+ `maxPages` on `createFetchClients` (the `Connection` clients take `{ maxPages }` as a second
115
+ constructor argument). Errors are `SalesforceApiError` with Salesforce's own `errorCode`, or
116
+ `ERROR_HTTP_<status>` when the response carries none; test for them with `isApiError`.
117
+
87
118
  JSON Schemas are reachable as a subpath export:
88
119
 
89
120
  ```ts
@@ -96,10 +127,11 @@ const couplingGraphSchema = loadSchema('coupling-graph');
96
127
  Both are enforced as tests, not asserted in prose. Run them yourself with `pnpm test`:
97
128
 
98
129
  - **Read-only.** No jsforce mutation API, HTTP write verb, or bulk/composite write path may
99
- appear in source. Every org request is a SOQL query, a REST **GET**, or a Metadata read.
130
+ appear in source. The one exception is the OAuth token `POST` in the fetch login, which
131
+ 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
132
  - **Local-first.** No third-party HTTP client, telemetry endpoint, LLM call, websocket, or
101
- remote asset in a generated report. The only network destination is the org the operator
102
- authenticated against.
133
+ remote asset in a generated report. The only network destinations are the org the operator
134
+ authenticated against, or an object-storage endpoint the caller passes explicitly.
103
135
 
104
136
  ## Versioning
105
137
 
@@ -1,6 +1,38 @@
1
1
  export interface ApiError extends Error {
2
2
  errorCode: string;
3
- statusCode: number;
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
@@ -1,6 +1,84 @@
1
1
  export function isApiError(err) {
2
- return (err instanceof Error &&
3
- 'errorCode' in err && typeof err.errorCode === 'string' &&
4
- 'statusCode' in err && typeof err.statusCode === 'number');
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
- const res = await read(type, fullName);
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 { 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';
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
- return this.conn.request(`/services/data/v${version}${normalised}`);
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
- return this.conn.request(`/services/data/v${version}${normalised}`);
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 || !res.body) {
32
- throw new Error(`Download failed for ${normalised} (HTTP ${res.status})`);
33
- }
34
- await secureFs.mkdir(dirname(destPath), { recursive: true });
35
- try {
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
- const result = await this.anyConn.query(soql);
8
- return {
9
- totalSize: result.totalSize,
10
- done: result.done,
11
- records: (result.records ?? []),
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
- const result = await this.anyConn.autoFetchQuery(soql);
16
- return (result.records ?? []);
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
- const result = await this.tooling.query(soql);
10
- let records = (result.records ?? []);
11
- let nextUrl = result.nextRecordsUrl;
12
- // Using conn.request() directly avoids the complex Query<> overload typings
13
- // on tooling.queryMore — the nextRecordsUrl is a plain string handled cleanly here.
14
- // Circuit breaker: 200 pages × 2000 rows = 400 000 records max before we abort.
15
- let page = 0;
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
- return this.conn.request(`/services/data/v${version}/tooling/sobjects/${type}/${id}/`);
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