@cclabsnz/sf-core 0.1.4 → 0.2.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.
@@ -0,0 +1,68 @@
1
+ /** Why something present in the request is absent from the capture. Closed set — consumers branch on it. */
2
+ export type SkipReason = 'not-in-core-set' | 'already-captured' | 'download-failed' | 'too-large' | 'unlicensed' | 'storage-disabled' | 'no-permission' | 'not-queryable' | 'unknown';
3
+ export declare const SKIP_REASONS: readonly SkipReason[];
4
+ export declare function isSkipReason(value: unknown): value is SkipReason;
5
+ export interface CapturedElfFile {
6
+ type: string;
7
+ id: string;
8
+ logDate: string;
9
+ /** Absent for a daily file. */
10
+ hour?: string;
11
+ bytes: number;
12
+ path: string;
13
+ }
14
+ export interface SkippedElfFile {
15
+ type: string;
16
+ id?: string;
17
+ logDate?: string;
18
+ hour?: string;
19
+ reason: SkipReason;
20
+ detail?: string;
21
+ }
22
+ export interface CapturedRteObject {
23
+ object: string;
24
+ rows: number;
25
+ /** Which name actually answered — the base object or its retained-rows Store counterpart. */
26
+ via: 'base' | 'store';
27
+ paths: string[];
28
+ }
29
+ export interface UnavailableRteObject {
30
+ object: string;
31
+ reason: SkipReason;
32
+ detail?: string;
33
+ }
34
+ export interface CaptureCoverage {
35
+ orgId: string;
36
+ capturedAt: string;
37
+ window?: {
38
+ from: string;
39
+ to: string;
40
+ };
41
+ since?: number;
42
+ interval: 'Daily' | 'Hourly' | 'both';
43
+ elf: {
44
+ requestedTypes: string[];
45
+ captured: CapturedElfFile[];
46
+ skipped: SkippedElfFile[];
47
+ failed: SkippedElfFile[];
48
+ };
49
+ rte: {
50
+ captured: CapturedRteObject[];
51
+ unavailable: UnavailableRteObject[];
52
+ };
53
+ /** Query-level failures — an inaccessible EventLogFile object, say. Empty is the good case. */
54
+ accessErrors: Array<{
55
+ scope: string;
56
+ reason: string;
57
+ detail?: string;
58
+ }>;
59
+ }
60
+ /** An empty coverage record for one org, ready to be filled in as a pull proceeds. */
61
+ export declare function emptyCoverage(orgId: string, interval: CaptureCoverage['interval'], capturedAt: string): CaptureCoverage;
62
+ /**
63
+ * Read a coverage manifest back off disk. Returns undefined rather than throwing on a missing
64
+ * or malformed file: a consumer scanning a directory of manifests should skip the bad one and
65
+ * carry on, not abort the scan.
66
+ */
67
+ export declare function readCoverageManifest(filePath: string): CaptureCoverage | undefined;
68
+ //# sourceMappingURL=CaptureManifest.d.ts.map
@@ -0,0 +1,55 @@
1
+ // src/events/CaptureManifest.ts
2
+ // The per-pull coverage record. Its whole reason to exist is letting a downstream consumer
3
+ // tell *nothing happened* from *nothing was captured* — an empty result set is only evidence
4
+ // of absence if you know the capture was actually possible and actually ran.
5
+ //
6
+ // That is why `reason` is a closed enum rather than free text: a consumer branches on it, and
7
+ // "unlicensed" vs "storage-disabled" vs "no-permission" are three different answers to
8
+ // "should I trust this silence?" with three different remediations.
9
+ import * as fs from 'node:fs';
10
+ export const SKIP_REASONS = [
11
+ 'not-in-core-set',
12
+ 'already-captured',
13
+ 'download-failed',
14
+ 'too-large',
15
+ 'unlicensed',
16
+ 'storage-disabled',
17
+ 'no-permission',
18
+ 'not-queryable',
19
+ 'unknown',
20
+ ];
21
+ export function isSkipReason(value) {
22
+ return typeof value === 'string' && SKIP_REASONS.includes(value);
23
+ }
24
+ /** An empty coverage record for one org, ready to be filled in as a pull proceeds. */
25
+ export function emptyCoverage(orgId, interval, capturedAt) {
26
+ return {
27
+ orgId,
28
+ capturedAt,
29
+ interval,
30
+ elf: { requestedTypes: [], captured: [], skipped: [], failed: [] },
31
+ rte: { captured: [], unavailable: [] },
32
+ accessErrors: [],
33
+ };
34
+ }
35
+ /**
36
+ * Read a coverage manifest back off disk. Returns undefined rather than throwing on a missing
37
+ * or malformed file: a consumer scanning a directory of manifests should skip the bad one and
38
+ * carry on, not abort the scan.
39
+ */
40
+ export function readCoverageManifest(filePath) {
41
+ try {
42
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
43
+ return isCoverage(parsed) ? parsed : undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ function isCoverage(value) {
50
+ if (typeof value !== 'object' || value === null)
51
+ return false;
52
+ const c = value;
53
+ return typeof c.orgId === 'string' && typeof c.capturedAt === 'string' && typeof c.elf === 'object';
54
+ }
55
+ //# sourceMappingURL=CaptureManifest.js.map
@@ -4,13 +4,39 @@ export declare class EventBaselineStore {
4
4
  static defaultRoot(): string;
5
5
  /** The per-org base directory logs for this org are stored under. */
6
6
  orgDir(orgId: string): string;
7
- /** Absolute path a given log file is (or would be) stored at. */
8
- pathFor(orgId: string, eventType: string, logDate: string, id: string): string;
7
+ /**
8
+ * Absolute path a given log file is (or would be) stored at. Pass `hour` ('00'–'23', UTC)
9
+ * for an hourly capture; omit it and the layout is exactly what it has always been.
10
+ *
11
+ * `id` stays in the hourly path because a single (type, hour) can hold several files — a
12
+ * verified case had two AuraRequest rows for the same hour.
13
+ */
14
+ pathFor(orgId: string, eventType: string, logDate: string, id: string, hour?: string): string;
9
15
  /** True when this EventLogFile is already on disk — the dedup / idempotency check. */
10
- has(orgId: string, eventType: string, logDate: string, id: string): boolean;
16
+ has(orgId: string, eventType: string, logDate: string, id: string, hour?: string): boolean;
11
17
  /** Write a CSV body verbatim; returns the saved path. Best-effort. */
12
- save(orgId: string, eventType: string, logDate: string, id: string, body: string): string;
13
- /** Write a per-run manifest JSON under {root}/{orgId}/_manifests/; returns its path. */
18
+ save(orgId: string, eventType: string, logDate: string, id: string, body: string, hour?: string): string;
19
+ /** Absolute path the NDJSON for one Real-Time Event object-hour is (or would be) stored at. */
20
+ realtimePathFor(orgId: string, objectName: string, logDate: string, hour: string): string;
21
+ /** True when this object-hour already holds a non-empty NDJSON file. */
22
+ hasRealtime(orgId: string, objectName: string, logDate: string, hour: string): boolean;
23
+ /**
24
+ * Write RTE rows as NDJSON — one JSON object per line, so a run killed mid-write still
25
+ * leaves a parseable file up to the last complete line. Same failure-tolerance rationale as
26
+ * streaming raw CSV bytes to disk before parsing them.
27
+ */
28
+ saveRealtime(orgId: string, objectName: string, logDate: string, hour: string, rows: readonly unknown[]): string;
29
+ /**
30
+ * Write a per-run coverage manifest under {root}/{orgId}/_manifests/. Named `coverage-*` to
31
+ * keep it distinguishable from the legacy `manifest-*` files a consumer may still find in
32
+ * the same directory.
33
+ */
34
+ writeCoverageManifest(orgId: string, manifest: unknown): string;
35
+ /**
36
+ * @deprecated Superseded by {@link writeCoverageManifest}, which records why nothing was
37
+ * captured as well as what was. Retained so existing readers of `manifest-*.json` keep working.
38
+ */
14
39
  writeManifest(orgId: string, manifest: unknown): string;
40
+ private writeManifestAs;
15
41
  }
16
42
  //# sourceMappingURL=EventBaselineStore.d.ts.map
@@ -1,7 +1,19 @@
1
1
  // src/events/EventBaselineStore.ts
2
- // Local, on-disk archive of free EventLogFile CSVs. Mirrors HistoryStore: writes under
3
- // ~/.sf/event-baseline/{orgId}/, takes an optional root for testability, and is best-effort
4
- // (warns rather than throws) so a daily cron run never dies on a filesystem hiccup.
2
+ // Local, on-disk archive of EventLogFile CSVs and Real-Time Event NDJSON. Mirrors HistoryStore:
3
+ // writes under ~/.sf/event-baseline/{orgId}/, takes an optional root for testability, and is
4
+ // best-effort (warns rather than throws) so a scheduled run never dies on a filesystem hiccup.
5
+ //
6
+ // Path layout — this is the contract downstream consumers read against:
7
+ //
8
+ // {base}/{orgId}/
9
+ // {EventType}/{YYYY-MM-DD}-{id}.csv daily
10
+ // {EventType}/{YYYY-MM-DD}/{HH}-{id}.csv hourly
11
+ // _realtime/{ObjectName}/{YYYY-MM-DD}/{HH}.ndjson
12
+ // _manifests/coverage-{epochMs}-{rand}.json
13
+ //
14
+ // The daily and hourly forms cannot collide: the daily form is a *file* named
15
+ // `{date}-{id}.csv` while the hourly form nests a *directory* named `{date}`. Daily archives
16
+ // written by earlier versions therefore keep resolving with no migration.
5
17
  import * as fs from 'node:fs';
6
18
  import * as os from 'node:os';
7
19
  import * as path from 'node:path';
@@ -17,17 +29,25 @@ export class EventBaselineStore {
17
29
  orgDir(orgId) {
18
30
  return path.join(this.root, orgId);
19
31
  }
20
- /** Absolute path a given log file is (or would be) stored at. */
21
- pathFor(orgId, eventType, logDate, id) {
22
- return path.join(this.root, orgId, eventType, `${logDate}-${id}.csv`);
32
+ /**
33
+ * Absolute path a given log file is (or would be) stored at. Pass `hour` ('00'–'23', UTC)
34
+ * for an hourly capture; omit it and the layout is exactly what it has always been.
35
+ *
36
+ * `id` stays in the hourly path because a single (type, hour) can hold several files — a
37
+ * verified case had two AuraRequest rows for the same hour.
38
+ */
39
+ pathFor(orgId, eventType, logDate, id, hour) {
40
+ return hour === undefined
41
+ ? path.join(this.root, orgId, eventType, `${logDate}-${id}.csv`)
42
+ : path.join(this.root, orgId, eventType, logDate, `${padHour(hour)}-${id}.csv`);
23
43
  }
24
44
  /** True when this EventLogFile is already on disk — the dedup / idempotency check. */
25
- has(orgId, eventType, logDate, id) {
26
- return fs.existsSync(this.pathFor(orgId, eventType, logDate, id));
45
+ has(orgId, eventType, logDate, id, hour) {
46
+ return fs.existsSync(this.pathFor(orgId, eventType, logDate, id, hour));
27
47
  }
28
48
  /** Write a CSV body verbatim; returns the saved path. Best-effort. */
29
- save(orgId, eventType, logDate, id, body) {
30
- const filePath = this.pathFor(orgId, eventType, logDate, id);
49
+ save(orgId, eventType, logDate, id, body, hour) {
50
+ const filePath = this.pathFor(orgId, eventType, logDate, id, hour);
31
51
  try {
32
52
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
33
53
  fs.writeFileSync(filePath, body, 'utf-8');
@@ -37,11 +57,55 @@ export class EventBaselineStore {
37
57
  }
38
58
  return filePath;
39
59
  }
40
- /** Write a per-run manifest JSON under {root}/{orgId}/_manifests/; returns its path. */
60
+ /** Absolute path the NDJSON for one Real-Time Event object-hour is (or would be) stored at. */
61
+ realtimePathFor(orgId, objectName, logDate, hour) {
62
+ return path.join(this.root, orgId, '_realtime', objectName, logDate, `${padHour(hour)}.ndjson`);
63
+ }
64
+ /** True when this object-hour already holds a non-empty NDJSON file. */
65
+ hasRealtime(orgId, objectName, logDate, hour) {
66
+ const filePath = this.realtimePathFor(orgId, objectName, logDate, hour);
67
+ try {
68
+ return fs.statSync(filePath).size > 0;
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ /**
75
+ * Write RTE rows as NDJSON — one JSON object per line, so a run killed mid-write still
76
+ * leaves a parseable file up to the last complete line. Same failure-tolerance rationale as
77
+ * streaming raw CSV bytes to disk before parsing them.
78
+ */
79
+ saveRealtime(orgId, objectName, logDate, hour, rows) {
80
+ const filePath = this.realtimePathFor(orgId, objectName, logDate, hour);
81
+ try {
82
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
83
+ fs.writeFileSync(filePath, rows.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf-8');
84
+ }
85
+ catch (err) {
86
+ process.stderr.write(`[sf-audit] Warning: could not save realtime events ${objectName} ${logDate} ${hour}: ${String(err)}\n`);
87
+ }
88
+ return filePath;
89
+ }
90
+ /**
91
+ * Write a per-run coverage manifest under {root}/{orgId}/_manifests/. Named `coverage-*` to
92
+ * keep it distinguishable from the legacy `manifest-*` files a consumer may still find in
93
+ * the same directory.
94
+ */
95
+ writeCoverageManifest(orgId, manifest) {
96
+ return this.writeManifestAs(orgId, 'coverage', manifest);
97
+ }
98
+ /**
99
+ * @deprecated Superseded by {@link writeCoverageManifest}, which records why nothing was
100
+ * captured as well as what was. Retained so existing readers of `manifest-*.json` keep working.
101
+ */
41
102
  writeManifest(orgId, manifest) {
103
+ return this.writeManifestAs(orgId, 'manifest', manifest);
104
+ }
105
+ writeManifestAs(orgId, prefix, manifest) {
42
106
  const dir = path.join(this.root, orgId, '_manifests');
43
107
  const suffix = Math.random().toString(36).slice(2, 8);
44
- const filePath = path.join(dir, `manifest-${Date.now()}-${suffix}.json`);
108
+ const filePath = path.join(dir, `${prefix}-${Date.now()}-${suffix}.json`);
45
109
  try {
46
110
  fs.mkdirSync(dir, { recursive: true });
47
111
  fs.writeFileSync(filePath, JSON.stringify(manifest, null, 2), 'utf-8');
@@ -52,4 +116,8 @@ export class EventBaselineStore {
52
116
  return filePath;
53
117
  }
54
118
  }
119
+ /** Hours are stored zero-padded so lexical order matches chronological order. */
120
+ function padHour(hour) {
121
+ return String(hour).padStart(2, '0');
122
+ }
55
123
  //# sourceMappingURL=EventBaselineStore.js.map
@@ -1,9 +1,29 @@
1
+ /** Which EventLogFile Interval to discover. `both` omits the predicate entirely. */
2
+ export type EventLogInterval = 'Daily' | 'Hourly' | 'both';
3
+ /** An explicit, bounded LogDate window. Both bounds are inclusive ISO8601 instants. */
4
+ export interface EventLogWindow {
5
+ from: string;
6
+ to: string;
7
+ }
1
8
  export interface EventLogQueryOptions {
2
- /** Number of days of LogDate to request (LAST_N_DAYS:N). */
3
- since: number;
9
+ /** Number of days of LogDate to request (LAST_N_DAYS:N). Mutually exclusive with `window`. */
10
+ since?: number;
11
+ /** Explicit LogDate bounds. Mutually exclusive with `since`. */
12
+ window?: EventLogWindow;
13
+ /** Defaults to 'Daily', which preserves the free-tier behaviour byte-for-byte. */
14
+ interval?: EventLogInterval;
4
15
  /** Optional EventType allow-list (already sanitised or not — we sanitise again). */
5
16
  types?: string[];
6
17
  }
18
+ /**
19
+ * The EventTypes worth capturing hourly. Deliberately a short list: hourly capture of every
20
+ * type runs to ~25GB/month on a busy org, against ~1–2GB for these. They are the types that
21
+ * carry either the access evidence itself or the join keys (REQUEST_ID, CLIENT_IP,
22
+ * SESSION_KEY, LOGIN_KEY) a consumer needs to tie types together.
23
+ *
24
+ * Exported as data so downstream packages can name the same default rather than duplicate it.
25
+ */
26
+ export declare const HOURLY_FORENSIC_CORE: readonly ["AuraRequest", "Sites", "URI", "UniqueQuery", "GraphQlQueryExecution", "ApexExecution", "RestApi", "API", "Login", "Logout"];
7
27
  /**
8
28
  * Reduce free-form `--types` input to safe EventType tokens. EventTypes are PascalCase
9
29
  * identifiers (Login, ApiTotalUsage, LightningError, …), so we strip anything that is not
@@ -13,9 +33,25 @@ export declare function sanitizeTypes(raw: string | undefined): string[];
13
33
  /** Normalise a Salesforce LogDate (datetime) to a YYYY-MM-DD string for filenames. */
14
34
  export declare function toLogDate(raw: string): string;
15
35
  /**
16
- * Build the read-only EventLogFile discovery query. `Interval = 'Daily'` excludes the paid
17
- * hourly logs; `LogDate = LAST_N_DAYS:N` bounds the window. `since` is coerced to a
18
- * non-negative integer and `types` are sanitised, so the interpolated string is injection-safe.
36
+ * Extract the zero-padded UTC hour ('00'–'23') from a Salesforce LogDate. Returns undefined
37
+ * when the value carries no time component, which is how a Daily row is told from an Hourly
38
+ * one without trusting the Interval field alone.
39
+ */
40
+ export declare function toLogHour(raw: string): string | undefined;
41
+ /**
42
+ * Build the read-only EventLogFile discovery query.
43
+ *
44
+ * `Interval = 'Daily'` (the default) excludes the paid hourly logs and emits exactly the SOQL
45
+ * this function has always emitted — free-tier callers are unaffected. `'Hourly'` selects the
46
+ * paid logs; `'both'` omits the predicate rather than emitting `IN ('Daily','Hourly')`, which
47
+ * is the same result set with fewer moving parts.
48
+ *
49
+ * NOTE: never probe for hourly rows with a `GROUP BY Interval` aggregate. A verified quirk of
50
+ * the platform is that such a query reports only `Daily` even in orgs where an explicit
51
+ * `WHERE Interval = 'Hourly'` returns thousands of rows.
52
+ *
53
+ * `since` is coerced to a non-negative integer, `window` bounds are shape-validated and
54
+ * `types` are sanitised, so the interpolated string is injection-safe.
19
55
  */
20
56
  export declare function buildEventLogQuery(opts: EventLogQueryOptions): string;
21
57
  //# sourceMappingURL=eventLogQuery.d.ts.map
@@ -1,5 +1,25 @@
1
1
  // Pure helpers for the `audit events pull` command. Kept free of I/O so they are
2
2
  // unit-testable without an org connection or the oclif command harness.
3
+ /**
4
+ * The EventTypes worth capturing hourly. Deliberately a short list: hourly capture of every
5
+ * type runs to ~25GB/month on a busy org, against ~1–2GB for these. They are the types that
6
+ * carry either the access evidence itself or the join keys (REQUEST_ID, CLIENT_IP,
7
+ * SESSION_KEY, LOGIN_KEY) a consumer needs to tie types together.
8
+ *
9
+ * Exported as data so downstream packages can name the same default rather than duplicate it.
10
+ */
11
+ export const HOURLY_FORENSIC_CORE = [
12
+ 'AuraRequest',
13
+ 'Sites',
14
+ 'URI',
15
+ 'UniqueQuery',
16
+ 'GraphQlQueryExecution',
17
+ 'ApexExecution',
18
+ 'RestApi',
19
+ 'API',
20
+ 'Login',
21
+ 'Logout',
22
+ ];
3
23
  /**
4
24
  * Reduce free-form `--types` input to safe EventType tokens. EventTypes are PascalCase
5
25
  * identifiers (Login, ApiTotalUsage, LightningError, …), so we strip anything that is not
@@ -18,17 +38,59 @@ export function toLogDate(raw) {
18
38
  return String(raw).slice(0, 10);
19
39
  }
20
40
  /**
21
- * Build the read-only EventLogFile discovery query. `Interval = 'Daily'` excludes the paid
22
- * hourly logs; `LogDate = LAST_N_DAYS:N` bounds the window. `since` is coerced to a
23
- * non-negative integer and `types` are sanitised, so the interpolated string is injection-safe.
41
+ * Extract the zero-padded UTC hour ('00'–'23') from a Salesforce LogDate. Returns undefined
42
+ * when the value carries no time component, which is how a Daily row is told from an Hourly
43
+ * one without trusting the Interval field alone.
44
+ */
45
+ export function toLogHour(raw) {
46
+ const match = /T(\d{2}):/.exec(String(raw));
47
+ return match ? match[1] : undefined;
48
+ }
49
+ /**
50
+ * Salesforce rejects a bare ISO instant in SOQL if it carries milliseconds or a `Z` the
51
+ * driver has not normalised, so bounds are validated to the shape the platform accepts and
52
+ * interpolated only once proven safe. Anything else throws rather than reaching the org.
53
+ */
54
+ const SOQL_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
55
+ function assertDateTime(value, label) {
56
+ if (!SOQL_DATETIME.test(value)) {
57
+ throw new TypeError(`Invalid ${label} '${value}': expected an ISO8601 datetime such as 2026-08-02T04:00:00Z`);
58
+ }
59
+ return value;
60
+ }
61
+ /**
62
+ * Build the read-only EventLogFile discovery query.
63
+ *
64
+ * `Interval = 'Daily'` (the default) excludes the paid hourly logs and emits exactly the SOQL
65
+ * this function has always emitted — free-tier callers are unaffected. `'Hourly'` selects the
66
+ * paid logs; `'both'` omits the predicate rather than emitting `IN ('Daily','Hourly')`, which
67
+ * is the same result set with fewer moving parts.
68
+ *
69
+ * NOTE: never probe for hourly rows with a `GROUP BY Interval` aggregate. A verified quirk of
70
+ * the platform is that such a query reports only `Daily` even in orgs where an explicit
71
+ * `WHERE Interval = 'Hourly'` returns thousands of rows.
72
+ *
73
+ * `since` is coerced to a non-negative integer, `window` bounds are shape-validated and
74
+ * `types` are sanitised, so the interpolated string is injection-safe.
24
75
  */
25
76
  export function buildEventLogQuery(opts) {
26
- const since = Math.max(0, Math.trunc(opts.since));
77
+ if (opts.since !== undefined && opts.window !== undefined) {
78
+ throw new TypeError('buildEventLogQuery: `since` and `window` are mutually exclusive');
79
+ }
80
+ if (opts.since === undefined && opts.window === undefined) {
81
+ throw new TypeError('buildEventLogQuery: one of `since` or `window` is required');
82
+ }
83
+ const interval = opts.interval ?? 'Daily';
84
+ const intervalClause = interval === 'both' ? '' : `Interval = '${interval}' AND `;
85
+ const dateClause = opts.window
86
+ ? `LogDate >= ${assertDateTime(opts.window.from, 'window.from')} AND ` +
87
+ `LogDate <= ${assertDateTime(opts.window.to, 'window.to')}`
88
+ : `LogDate = LAST_N_DAYS:${Math.max(0, Math.trunc(opts.since))}`;
27
89
  const types = (opts.types ?? []).filter((t) => t.length > 0);
28
90
  const typeClause = types.length > 0 ? ` AND EventType IN (${types.map((t) => `'${t}'`).join(', ')})` : '';
29
91
  return ('SELECT Id, EventType, LogDate, LogFileLength, Interval, LogFileFieldNames ' +
30
92
  'FROM EventLogFile ' +
31
- `WHERE Interval = 'Daily' AND LogDate = LAST_N_DAYS:${since}${typeClause} ` +
93
+ `WHERE ${intervalClause}${dateClause}${typeClause} ` +
32
94
  'ORDER BY LogDate');
33
95
  }
34
96
  //# sourceMappingURL=eventLogQuery.js.map
@@ -1,7 +1,17 @@
1
1
  import type { SoqlClient } from '../api/SoqlClient.js';
2
2
  import type { RestClient } from '../api/RestClient.js';
3
3
  import type { EventLogAccess } from '../context/AuditCache.js';
4
- import { EventBaselineStore } from './EventBaselineStore.js';
4
+ import type { EventBaselineStore } from './EventBaselineStore.js';
5
+ import { type EventLogInterval, type EventLogWindow } from './eventLogQuery.js';
6
+ import { type CaptureCoverage } from './CaptureManifest.js';
7
+ import type { RteType } from './rteCatalog.js';
8
+ /**
9
+ * Ceiling on a single LogFile body. Checked against LogFileLength *before* the download so an
10
+ * oversized blob costs nothing, and surfaced as `too-large` in the manifest — never as a
11
+ * silent truncation. Generous by design: this is a runaway guard, not a capture policy. A
12
+ * busy org's daily Sites/URI log legitimately reaches tens of MB.
13
+ */
14
+ export declare const MAX_FILE_BYTES: number;
5
15
  /** The subset of EventLogFile fields the discovery query returns. */
6
16
  export interface EventLogFileRow {
7
17
  Id: string;
@@ -16,6 +26,9 @@ export interface PulledLog {
16
26
  id: string;
17
27
  eventType: string;
18
28
  logDate: string;
29
+ /** Zero-padded UTC hour; present only for an Hourly row. */
30
+ hour?: string;
31
+ interval: 'Daily' | 'Hourly';
19
32
  bytes: number;
20
33
  savedPath: string;
21
34
  status: 'downloaded' | 'skipped' | 'failed';
@@ -23,7 +36,9 @@ export interface PulledLog {
23
36
  /** Structured result of a pull run — returned by the command. */
24
37
  export interface EventsPullResult {
25
38
  orgId: string;
26
- since: number;
39
+ since?: number;
40
+ window?: EventLogWindow;
41
+ interval: EventLogInterval;
27
42
  storagePath: string;
28
43
  found: number;
29
44
  downloaded: number;
@@ -31,7 +46,9 @@ export interface EventsPullResult {
31
46
  failed: number;
32
47
  totalBytes: number;
33
48
  logs: PulledLog[];
34
- manifestPath?: string;
49
+ /** Always written — a run that captured nothing is exactly the run whose record matters. */
50
+ manifestPath: string;
51
+ coverage: CaptureCoverage;
35
52
  /** Set when the EventLogFile query itself failed (no crash); tells license vs permission apart. */
36
53
  accessError?: EventLogAccess;
37
54
  }
@@ -42,8 +59,25 @@ export interface PullDeps {
42
59
  orgId: string;
43
60
  }
44
61
  export interface PullOptions {
45
- since: number;
62
+ /** Days of LogDate to request. Mutually exclusive with `window`. */
63
+ since?: number;
64
+ /** Explicit ISO8601 bounds. Mutually exclusive with `since`. */
65
+ window?: EventLogWindow;
66
+ /** Defaults to 'Daily' — the free-tier behaviour, unchanged. */
67
+ interval?: EventLogInterval;
68
+ /**
69
+ * EventType allow-list. When omitted, daily capture takes every type the org offers and
70
+ * hourly capture falls back to HOURLY_FORENSIC_CORE; an explicit list overrides both.
71
+ */
46
72
  types?: string[];
73
+ /** Also capture Real-Time Event Monitoring rows. Requires `window`. */
74
+ realtime?: boolean;
75
+ /** Restrict the RTE probe to these catalog entries. */
76
+ rteCatalog?: readonly RteType[];
77
+ /** Re-download / re-capture even when the target is already on disk. */
78
+ force?: boolean;
79
+ /** Cap on one LogFile body. Defaults to MAX_FILE_BYTES. */
80
+ maxFileBytes?: number;
47
81
  /** Optional sink for non-fatal warnings (per-file download failures). */
48
82
  warn?: (msg: string) => void;
49
83
  }
@@ -1,79 +1,188 @@
1
1
  import { classifyEventLogAccessError } from './eventLogAccess.js';
2
- import { buildEventLogQuery, toLogDate } from './eventLogQuery.js';
2
+ import { HOURLY_FORENSIC_CORE, buildEventLogQuery, toLogDate, toLogHour, } from './eventLogQuery.js';
3
+ import { emptyCoverage } from './CaptureManifest.js';
4
+ import { pullRealtimeEvents } from './pullRealtimeEvents.js';
5
+ /**
6
+ * Ceiling on a single LogFile body. Checked against LogFileLength *before* the download so an
7
+ * oversized blob costs nothing, and surfaced as `too-large` in the manifest — never as a
8
+ * silent truncation. Generous by design: this is a runaway guard, not a capture policy. A
9
+ * busy org's daily Sites/URI log legitimately reaches tens of MB.
10
+ */
11
+ export const MAX_FILE_BYTES = 512 * 1024 * 1024;
3
12
  export async function pullEventLogs(deps, opts) {
4
13
  const { soql, rest, store, orgId } = deps;
5
- const since = opts.since;
6
- const storagePath = store.orgDir(orgId);
14
+ const interval = opts.interval ?? 'Daily';
15
+ const maxFileBytes = opts.maxFileBytes ?? MAX_FILE_BYTES;
16
+ const coverage = emptyCoverage(orgId, interval, new Date().toISOString());
17
+ if (opts.window)
18
+ coverage.window = opts.window;
19
+ if (opts.since !== undefined)
20
+ coverage.since = opts.since;
7
21
  const base = {
8
22
  orgId,
9
- since,
10
- storagePath,
23
+ since: opts.since,
24
+ window: opts.window,
25
+ interval,
26
+ storagePath: store.orgDir(orgId),
11
27
  found: 0,
12
28
  downloaded: 0,
13
29
  skipped: 0,
14
30
  failed: 0,
15
31
  totalBytes: 0,
16
32
  logs: [],
33
+ manifestPath: '',
34
+ coverage,
17
35
  };
18
- let rows;
19
- try {
20
- rows = await soql.queryAll(buildEventLogQuery({ since, types: opts.types }));
21
- }
22
- catch (err) {
23
- // Inaccessible EventLogFile (unlicensed / no permission) must not crash the command.
24
- return { ...base, accessError: classifyEventLogAccessError(err) };
25
- }
26
- base.found = rows.length;
27
- for (const row of rows) {
28
- const logDate = toLogDate(row.LogDate);
29
- if (store.has(orgId, row.EventType, logDate, row.Id)) {
30
- base.skipped += 1;
31
- base.logs.push({
32
- id: row.Id,
33
- eventType: row.EventType,
34
- logDate,
35
- bytes: 0,
36
- savedPath: store.pathFor(orgId, row.EventType, logDate, row.Id),
37
- status: 'skipped',
36
+ // 'both' cannot be a single query: daily takes every type while hourly defaults to the
37
+ // forensic core, and one SOQL statement cannot carry two different EventType filters. Two
38
+ // passes it is — which also keeps a failure in one interval from blanking the other.
39
+ const passes = interval === 'both'
40
+ ? [
41
+ { interval: 'Daily', types: opts.types },
42
+ { interval: 'Hourly', types: opts.types ?? [...HOURLY_FORENSIC_CORE] },
43
+ ]
44
+ : [
45
+ {
46
+ interval,
47
+ types: interval === 'Hourly' ? (opts.types ?? [...HOURLY_FORENSIC_CORE]) : opts.types,
48
+ },
49
+ ];
50
+ for (const pass of passes) {
51
+ coverage.elf.requestedTypes.push(...(pass.types ?? []));
52
+ let rows;
53
+ try {
54
+ rows = await soql.queryAll(buildEventLogQuery({
55
+ since: opts.since,
56
+ window: opts.window,
57
+ interval: pass.interval,
58
+ types: pass.types,
59
+ }));
60
+ }
61
+ catch (err) {
62
+ // Inaccessible EventLogFile (unlicensed / no permission) must not crash the command,
63
+ // and must not stop the other interval's pass from running.
64
+ const reason = classifyEventLogAccessError(err);
65
+ base.accessError ??= reason;
66
+ coverage.accessErrors.push({
67
+ scope: `EventLogFile:${pass.interval}`,
68
+ reason,
69
+ detail: err instanceof Error ? err.message : String(err),
38
70
  });
39
71
  continue;
40
72
  }
41
- try {
42
- // Stream straight to disk — never buffer the body — so large daily logs don't blow the heap.
43
- const savedPath = store.pathFor(orgId, row.EventType, logDate, row.Id);
44
- const bytes = await rest.getRawToFile(`/sobjects/EventLogFile/${row.Id}/LogFile`, savedPath);
45
- base.downloaded += 1;
46
- base.totalBytes += bytes;
47
- base.logs.push({ id: row.Id, eventType: row.EventType, logDate, bytes, savedPath, status: 'downloaded' });
73
+ base.found += rows.length;
74
+ for (const row of rows) {
75
+ await captureRow(deps, opts, base, coverage, row, pass.interval, maxFileBytes);
48
76
  }
49
- catch (err) {
50
- base.failed += 1;
51
- base.logs.push({
52
- id: row.Id,
53
- eventType: row.EventType,
54
- logDate,
55
- bytes: 0,
56
- savedPath: store.pathFor(orgId, row.EventType, logDate, row.Id),
57
- status: 'failed',
77
+ }
78
+ // RTE capture is independent of ELF by design: a broken probe on either side must never
79
+ // prevent the other from running.
80
+ if (opts.realtime) {
81
+ if (!opts.window) {
82
+ coverage.accessErrors.push({
83
+ scope: 'RealtimeEvents',
84
+ reason: 'unknown',
85
+ detail: 'realtime capture requires an explicit window',
58
86
  });
59
- opts.warn?.(`Failed to download EventLogFile ${row.Id} (${row.EventType} ${logDate}): ${String(err)}`);
60
87
  }
88
+ else {
89
+ try {
90
+ const rte = await pullRealtimeEvents({ soql, rest, store, orgId }, {
91
+ window: opts.window,
92
+ catalog: opts.rteCatalog,
93
+ force: opts.force,
94
+ warn: opts.warn,
95
+ });
96
+ coverage.rte = rte;
97
+ }
98
+ catch (err) {
99
+ coverage.accessErrors.push({
100
+ scope: 'RealtimeEvents',
101
+ reason: 'unknown',
102
+ detail: err instanceof Error ? err.message : String(err),
103
+ });
104
+ }
105
+ }
106
+ }
107
+ // Always written. A run that captured nothing is exactly the run a consumer needs a record
108
+ // of — without it, "no data" and "never looked" are indistinguishable.
109
+ base.manifestPath = store.writeCoverageManifest(orgId, coverage);
110
+ return base;
111
+ }
112
+ /** Download (or account for skipping) one EventLogFile row. Never throws. */
113
+ async function captureRow(deps, opts, base, coverage, row, passInterval, maxFileBytes) {
114
+ const { rest, store, orgId } = deps;
115
+ const logDate = toLogDate(row.LogDate);
116
+ // Trust the row's own Interval over the pass it arrived on: with interval 'both' the query
117
+ // carries no Interval predicate, so a pass can return either kind.
118
+ const rowInterval = row.Interval === 'Hourly' || row.Interval === 'Daily' ? row.Interval : passInterval;
119
+ const hour = rowInterval === 'Hourly' ? toLogHour(row.LogDate) : undefined;
120
+ const savedPath = store.pathFor(orgId, row.EventType, logDate, row.Id, hour);
121
+ const record = (status, bytes) => {
122
+ base.logs.push({
123
+ id: row.Id,
124
+ eventType: row.EventType,
125
+ logDate,
126
+ hour,
127
+ interval: rowInterval,
128
+ bytes,
129
+ savedPath,
130
+ status,
131
+ });
132
+ };
133
+ if (!opts.force && store.has(orgId, row.EventType, logDate, row.Id, hour)) {
134
+ base.skipped += 1;
135
+ record('skipped', 0);
136
+ coverage.elf.skipped.push({
137
+ type: row.EventType,
138
+ id: row.Id,
139
+ logDate,
140
+ hour,
141
+ reason: 'already-captured',
142
+ });
143
+ return;
61
144
  }
62
- // Only write a manifest when something was actually captured — a pure all-skipped or
63
- // empty run leaves no new record to make.
64
- if (base.downloaded > 0) {
65
- base.manifestPath = store.writeManifest(orgId, {
66
- orgId,
67
- since,
68
- pulledAt: new Date().toISOString(),
69
- found: base.found,
70
- downloaded: base.downloaded,
71
- skipped: base.skipped,
72
- failed: base.failed,
73
- totalBytes: base.totalBytes,
74
- logs: base.logs,
145
+ if (typeof row.LogFileLength === 'number' && row.LogFileLength > maxFileBytes) {
146
+ base.skipped += 1;
147
+ record('skipped', 0);
148
+ coverage.elf.skipped.push({
149
+ type: row.EventType,
150
+ id: row.Id,
151
+ logDate,
152
+ hour,
153
+ reason: 'too-large',
154
+ detail: `${row.LogFileLength} bytes exceeds the ${maxFileBytes}-byte cap`,
75
155
  });
156
+ opts.warn?.(`Skipped EventLogFile ${row.Id} (${row.EventType} ${logDate}): ${row.LogFileLength} bytes exceeds the cap`);
157
+ return;
158
+ }
159
+ try {
160
+ // Stream straight to disk — never buffer the body — so large logs don't blow the heap.
161
+ const bytes = await rest.getRawToFile(`/sobjects/EventLogFile/${row.Id}/LogFile`, savedPath);
162
+ base.downloaded += 1;
163
+ base.totalBytes += bytes;
164
+ record('downloaded', bytes);
165
+ coverage.elf.captured.push({
166
+ type: row.EventType,
167
+ id: row.Id,
168
+ logDate,
169
+ hour,
170
+ bytes,
171
+ path: savedPath,
172
+ });
173
+ }
174
+ catch (err) {
175
+ base.failed += 1;
176
+ record('failed', 0);
177
+ coverage.elf.failed.push({
178
+ type: row.EventType,
179
+ id: row.Id,
180
+ logDate,
181
+ hour,
182
+ reason: 'download-failed',
183
+ detail: err instanceof Error ? err.message : String(err),
184
+ });
185
+ opts.warn?.(`Failed to download EventLogFile ${row.Id} (${row.EventType} ${logDate}): ${String(err)}`);
76
186
  }
77
- return base;
78
187
  }
79
188
  //# sourceMappingURL=pullEventLogs.js.map
@@ -0,0 +1,49 @@
1
+ import type { SoqlClient } from '../api/SoqlClient.js';
2
+ import type { RestClient } from '../api/RestClient.js';
3
+ import type { EventBaselineStore } from './EventBaselineStore.js';
4
+ import type { CapturedRteObject, SkipReason, UnavailableRteObject } from './CaptureManifest.js';
5
+ import { type RteType } from './rteCatalog.js';
6
+ export interface RealtimePullDeps {
7
+ soql: SoqlClient;
8
+ rest: RestClient;
9
+ store: EventBaselineStore;
10
+ orgId: string;
11
+ }
12
+ export interface RealtimePullOptions {
13
+ /** Inclusive ISO8601 bounds. Rows are bucketed to one NDJSON file per UTC hour within it. */
14
+ window: {
15
+ from: string;
16
+ to: string;
17
+ };
18
+ /** Defaults to the full catalog. */
19
+ catalog?: readonly RteType[];
20
+ /** Re-capture object-hours already on disk. */
21
+ force?: boolean;
22
+ warn?: (msg: string) => void;
23
+ }
24
+ export interface RealtimePullResult {
25
+ captured: CapturedRteObject[];
26
+ unavailable: UnavailableRteObject[];
27
+ }
28
+ export declare function pullRealtimeEvents(deps: RealtimePullDeps, opts: RealtimePullOptions): Promise<RealtimePullResult>;
29
+ /**
30
+ * Intersect the preferred field list with what the object actually defines. Field sets differ
31
+ * per object — LightningUriEvent has no RowsProcessed — so a fixed SELECT list fails outright.
32
+ */
33
+ export declare function describeFields(rest: RestClient, objectName: string, preferred: readonly string[]): Promise<string[]>;
34
+ /**
35
+ * Build the RTE window query. Deliberately emits no ORDER BY: RTE objects reject
36
+ * `ORDER BY EventDate ASC` with "Unsupported order direction on filter column". Sorting is a
37
+ * client-side concern here.
38
+ */
39
+ export declare function buildRealtimeQuery(objectName: string, fields: readonly string[], window: {
40
+ from: string;
41
+ to: string;
42
+ }): string;
43
+ /**
44
+ * Map an RTE failure to a manifest reason. The distinction that matters most is
45
+ * "does not support query" — meaning the base object is streaming-only and the Store should be
46
+ * tried — versus a licence or permission wall, where trying harder will not help.
47
+ */
48
+ export declare function classifyRteError(err: unknown): SkipReason;
49
+ //# sourceMappingURL=pullRealtimeEvents.d.ts.map
@@ -0,0 +1,152 @@
1
+ import { RTE_CATALOG } from './rteCatalog.js';
2
+ const SOQL_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
3
+ export async function pullRealtimeEvents(deps, opts) {
4
+ for (const bound of [opts.window.from, opts.window.to]) {
5
+ if (!SOQL_DATETIME.test(bound)) {
6
+ throw new TypeError(`pullRealtimeEvents: invalid window bound '${bound}': expected an ISO8601 datetime`);
7
+ }
8
+ }
9
+ const result = { captured: [], unavailable: [] };
10
+ for (const entry of opts.catalog ?? RTE_CATALOG) {
11
+ const outcome = await captureOne(deps, opts, entry);
12
+ if ('reason' in outcome)
13
+ result.unavailable.push(outcome);
14
+ else
15
+ result.captured.push(outcome);
16
+ }
17
+ return result;
18
+ }
19
+ /** Probe base, fall back to store, classify whatever went wrong. Never rejects. */
20
+ async function captureOne(deps, opts, entry) {
21
+ const attempts = [
22
+ { name: entry.base, via: 'base' },
23
+ ];
24
+ if (entry.store)
25
+ attempts.push({ name: entry.store, via: 'store' });
26
+ const details = [];
27
+ let lastReason = 'unknown';
28
+ for (const attempt of attempts) {
29
+ let fields;
30
+ try {
31
+ fields = await describeFields(deps.rest, attempt.name, entry.preferredFields);
32
+ }
33
+ catch (err) {
34
+ lastReason = classifyRteError(err);
35
+ details.push(`${attempt.name}: describe failed (${message(err)})`);
36
+ continue;
37
+ }
38
+ if (fields.length === 0) {
39
+ // The object exists (describe answered) but defines none of the forensic fields, so
40
+ // there is no SELECT list to build. Not a licence problem — genuinely unexpected.
41
+ lastReason = 'unknown';
42
+ details.push(`${attempt.name}: describe returned none of the preferred fields`);
43
+ continue;
44
+ }
45
+ let rows;
46
+ try {
47
+ rows = await deps.soql.queryAll(buildRealtimeQuery(attempt.name, fields, opts.window));
48
+ }
49
+ catch (err) {
50
+ lastReason = classifyRteError(err);
51
+ details.push(`${attempt.name}: ${message(err)}`);
52
+ continue;
53
+ }
54
+ if (rows.length === 0) {
55
+ if (attempt.via === 'base') {
56
+ // The live event channel answered and had nothing. That is a real finding — nothing
57
+ // happened in this window — not a gap in capture, so it is recorded as a capture of
58
+ // zero rows rather than as an unavailable object.
59
+ return { object: entry.base, rows: 0, via: 'base', paths: [] };
60
+ }
61
+ // Only the retained-rows Store answered, and it is empty. Empty and never-retained are
62
+ // indistinguishable from here, so this must not be reported as "nothing happened".
63
+ lastReason = 'storage-disabled';
64
+ details.push(`${attempt.name}: queryable but returned 0 rows`);
65
+ continue;
66
+ }
67
+ return writeBuckets(deps, opts, entry.base, attempt.via, rows);
68
+ }
69
+ return {
70
+ object: entry.base,
71
+ reason: lastReason,
72
+ detail: details.join('; ') || undefined,
73
+ };
74
+ }
75
+ /**
76
+ * Bucket rows into one NDJSON file per UTC hour and write them. Rows whose EventDate is
77
+ * missing or unparseable land in the window-start bucket rather than being dropped — an
78
+ * unattributable row is still evidence.
79
+ */
80
+ function writeBuckets(deps, opts, objectName, via, rows) {
81
+ const fallback = bucketKey(opts.window.from) ?? { date: opts.window.from.slice(0, 10), hour: '00' };
82
+ const buckets = new Map();
83
+ for (const row of rows) {
84
+ const key = bucketKey(row.EventDate) ?? fallback;
85
+ const id = `${key.date}T${key.hour}`;
86
+ const bucket = buckets.get(id) ?? { ...key, rows: [] };
87
+ bucket.rows.push(row);
88
+ buckets.set(id, bucket);
89
+ }
90
+ const paths = [];
91
+ let written = 0;
92
+ for (const bucket of buckets.values()) {
93
+ if (!opts.force && deps.store.hasRealtime(deps.orgId, objectName, bucket.date, bucket.hour)) {
94
+ paths.push(deps.store.realtimePathFor(deps.orgId, objectName, bucket.date, bucket.hour));
95
+ continue;
96
+ }
97
+ // ORDER BY EventDate is rejected outright on RTE objects ("Unsupported order direction on
98
+ // filter column: EVENTDATE"), so ordering happens here instead.
99
+ bucket.rows.sort((a, b) => String(a.EventDate ?? '').localeCompare(String(b.EventDate ?? '')));
100
+ paths.push(deps.store.saveRealtime(deps.orgId, objectName, bucket.date, bucket.hour, bucket.rows));
101
+ written += bucket.rows.length;
102
+ }
103
+ return { object: objectName, rows: written, via, paths };
104
+ }
105
+ function bucketKey(raw) {
106
+ const match = /^(\d{4}-\d{2}-\d{2})T(\d{2}):/.exec(String(raw ?? ''));
107
+ return match ? { date: match[1], hour: match[2] } : undefined;
108
+ }
109
+ /**
110
+ * Intersect the preferred field list with what the object actually defines. Field sets differ
111
+ * per object — LightningUriEvent has no RowsProcessed — so a fixed SELECT list fails outright.
112
+ */
113
+ export async function describeFields(rest, objectName, preferred) {
114
+ const describe = await rest.get(`/sobjects/${objectName}/describe`);
115
+ const actual = new Set((describe.fields ?? []).map((f) => String(f.name ?? '').toLowerCase()));
116
+ return preferred.filter((f) => actual.has(f.toLowerCase()));
117
+ }
118
+ /**
119
+ * Build the RTE window query. Deliberately emits no ORDER BY: RTE objects reject
120
+ * `ORDER BY EventDate ASC` with "Unsupported order direction on filter column". Sorting is a
121
+ * client-side concern here.
122
+ */
123
+ export function buildRealtimeQuery(objectName, fields, window) {
124
+ const safeObject = objectName.replace(/[^A-Za-z0-9_]/g, '');
125
+ const safeFields = fields.map((f) => f.replace(/[^A-Za-z0-9_]/g, '')).filter((f) => f.length > 0);
126
+ return (`SELECT ${safeFields.join(', ')} FROM ${safeObject} ` +
127
+ `WHERE EventDate >= ${window.from} AND EventDate <= ${window.to}`);
128
+ }
129
+ /**
130
+ * Map an RTE failure to a manifest reason. The distinction that matters most is
131
+ * "does not support query" — meaning the base object is streaming-only and the Store should be
132
+ * tried — versus a licence or permission wall, where trying harder will not help.
133
+ */
134
+ export function classifyRteError(err) {
135
+ const msg = message(err).toLowerCase();
136
+ if (msg.includes('does not support query'))
137
+ return 'not-queryable';
138
+ if (msg.includes('insufficient') || msg.includes('permission'))
139
+ return 'no-permission';
140
+ if (msg.includes('invalid type') ||
141
+ msg.includes('not found') ||
142
+ msg.includes('sobject type') ||
143
+ msg.includes('licens') ||
144
+ msg.includes('not enabled')) {
145
+ return 'unlicensed';
146
+ }
147
+ return 'unknown';
148
+ }
149
+ function message(err) {
150
+ return err instanceof Error ? err.message : String(err);
151
+ }
152
+ //# sourceMappingURL=pullRealtimeEvents.js.map
@@ -0,0 +1,14 @@
1
+ export interface RteType {
2
+ /** The streaming/base object name, e.g. 'ListViewEvent'. Probed first. */
3
+ base: string;
4
+ /** The retained-rows counterpart, e.g. 'GuestUserAnomalyEventStore'. Probed on fallback. */
5
+ store?: string;
6
+ /** Forensic fields in priority order; intersected with describe() at runtime. */
7
+ preferredFields: string[];
8
+ }
9
+ /**
10
+ * The 20 known RTE types. `store` is declared wherever a `*Store` counterpart is known to
11
+ * exist; its absence on ListViewEvent is deliberate, not an oversight.
12
+ */
13
+ export declare const RTE_CATALOG: readonly RteType[];
14
+ //# sourceMappingURL=rteCatalog.d.ts.map
@@ -0,0 +1,90 @@
1
+ // src/events/rteCatalog.ts
2
+ // Static description of the Real-Time Event Monitoring objects worth capturing. Data only —
3
+ // no logic, no I/O — so the probe in pullRealtimeEvents stays the single place that decides
4
+ // what an org can actually serve.
5
+ //
6
+ // Two verified facts drive the shape of this table:
7
+ //
8
+ // 1. Roughly half the RTE base objects reject `SELECT ... FROM x` outright with "entity type
9
+ // x does not support query" while their `*Store` counterpart answers fine. The Store holds
10
+ // the retained rows; the base object is the streaming channel.
11
+ // 2. The base/Store split is NOT uniform and cannot be derived from the name. ListViewEvent
12
+ // is queryable and has no ListViewEventStore at all; GuestUserAnomalyEvent is the exact
13
+ // inverse. Hence: declare both names, probe at runtime, believe the org.
14
+ /**
15
+ * Fields every RTE object is asked for when it defines them. Field sets differ per object —
16
+ * LightningUriEvent has no RowsProcessed, for one — so a fixed SELECT list across objects
17
+ * fails outright. The intersection with describe() is what makes a shared list workable.
18
+ */
19
+ const COMMON_FIELDS = [
20
+ 'EventDate',
21
+ 'SourceIp',
22
+ 'Username',
23
+ 'UserId',
24
+ 'SessionKey',
25
+ 'LoginKey',
26
+ 'EventIdentifier',
27
+ 'RelatedEventIdentifier',
28
+ ];
29
+ /**
30
+ * The fields that answer *did any records actually leave*. EventLogFile cannot answer this —
31
+ * it records no response bodies and no row counts for Aura actions — which is precisely why
32
+ * RTE capture exists. Requested wherever the object defines them.
33
+ */
34
+ const EXFIL_FIELDS = ['RowsProcessed', 'QueriedEntities', 'Records'];
35
+ /** Query/'what was asked for' context, where present. */
36
+ const CONTEXT_FIELDS = [
37
+ 'Query',
38
+ 'Operation',
39
+ 'Name',
40
+ 'DeveloperName',
41
+ 'Scope',
42
+ 'FilterCriteria',
43
+ 'Status',
44
+ 'Platform',
45
+ 'Application',
46
+ ];
47
+ const ALL_PREFERRED = [...COMMON_FIELDS, ...EXFIL_FIELDS, ...CONTEXT_FIELDS];
48
+ /**
49
+ * The 20 known RTE types. `store` is declared wherever a `*Store` counterpart is known to
50
+ * exist; its absence on ListViewEvent is deliberate, not an oversight.
51
+ */
52
+ export const RTE_CATALOG = [
53
+ { base: 'ListViewEvent', preferredFields: ALL_PREFERRED },
54
+ { base: 'ApiEvent', store: 'ApiEventStore', preferredFields: ALL_PREFERRED },
55
+ { base: 'LoginEvent', store: 'LoginEventStore', preferredFields: ALL_PREFERRED },
56
+ { base: 'LogoutEvent', store: 'LogoutEventStore', preferredFields: ALL_PREFERRED },
57
+ { base: 'ReportEvent', store: 'ReportEventStore', preferredFields: ALL_PREFERRED },
58
+ { base: 'UriEvent', store: 'UriEventStore', preferredFields: ALL_PREFERRED },
59
+ { base: 'LightningUriEvent', store: 'LightningUriEventStore', preferredFields: ALL_PREFERRED },
60
+ { base: 'ApexExecutionEvent', preferredFields: ALL_PREFERRED },
61
+ { base: 'BulkApiResultEvent', store: 'BulkApiResultEventStore', preferredFields: ALL_PREFERRED },
62
+ { base: 'FileEvent', store: 'FileEventStore', preferredFields: ALL_PREFERRED },
63
+ { base: 'ApiAnomalyEvent', store: 'ApiAnomalyEventStore', preferredFields: ALL_PREFERRED },
64
+ {
65
+ base: 'GuestUserAnomalyEvent',
66
+ store: 'GuestUserAnomalyEventStore',
67
+ preferredFields: ALL_PREFERRED,
68
+ },
69
+ {
70
+ base: 'SessionHijackingEvent',
71
+ store: 'SessionHijackingEventStore',
72
+ preferredFields: ALL_PREFERRED,
73
+ },
74
+ {
75
+ base: 'CredentialStuffingEvent',
76
+ store: 'CredentialStuffingEventStore',
77
+ preferredFields: ALL_PREFERRED,
78
+ },
79
+ { base: 'ReportAnomalyEvent', store: 'ReportAnomalyEventStore', preferredFields: ALL_PREFERRED },
80
+ { base: 'PermissionSetEvent', store: 'PermissionSetEventStore', preferredFields: ALL_PREFERRED },
81
+ {
82
+ base: 'ConcurLongRunApexErrEvent',
83
+ store: 'ConcurLongRunApexErrEventStore',
84
+ preferredFields: ALL_PREFERRED,
85
+ },
86
+ { base: 'OrgLifecycleNotification', preferredFields: ALL_PREFERRED },
87
+ { base: 'LoginAsEvent', store: 'LoginAsEventStore', preferredFields: ALL_PREFERRED },
88
+ { base: 'IdentityProviderEventStore', preferredFields: ALL_PREFERRED },
89
+ ];
90
+ //# sourceMappingURL=rteCatalog.js.map
package/lib/index.d.ts CHANGED
@@ -7,11 +7,17 @@ export { EMPTY_METRICS } from './context/OrgMetrics.js';
7
7
  export type { AuditOptions, AuditContext } from './context/AuditContext.js';
8
8
  export type { HealthCheckRisk, ApexClassBody, VfPageBody, EventLogAccess, EventLogSummary, AgentAccess, AgentDefinition, AgentUser, CspTrustedSite, MfaRegistration, EffectivePermissionGrant, AuditCache, } from './context/AuditCache.js';
9
9
  export { EventBaselineStore } from './events/EventBaselineStore.js';
10
- export type { EventLogQueryOptions } from './events/eventLogQuery.js';
11
- export { sanitizeTypes, toLogDate, buildEventLogQuery } from './events/eventLogQuery.js';
10
+ export type { EventLogQueryOptions, EventLogInterval, EventLogWindow, } from './events/eventLogQuery.js';
11
+ export { sanitizeTypes, toLogDate, toLogHour, buildEventLogQuery, HOURLY_FORENSIC_CORE, } from './events/eventLogQuery.js';
12
12
  export type { EventLogFileRow, PulledLog, EventsPullResult, PullDeps, PullOptions, } from './events/pullEventLogs.js';
13
- export { pullEventLogs } from './events/pullEventLogs.js';
13
+ export { pullEventLogs, MAX_FILE_BYTES } from './events/pullEventLogs.js';
14
14
  export { classifyEventLogAccessError } from './events/eventLogAccess.js';
15
+ export type { RteType } from './events/rteCatalog.js';
16
+ export { RTE_CATALOG } from './events/rteCatalog.js';
17
+ export type { RealtimePullDeps, RealtimePullOptions, RealtimePullResult, } from './events/pullRealtimeEvents.js';
18
+ export { pullRealtimeEvents, buildRealtimeQuery, describeFields, classifyRteError, } from './events/pullRealtimeEvents.js';
19
+ export type { SkipReason, CaptureCoverage, CapturedElfFile, SkippedElfFile, CapturedRteObject, UnavailableRteObject, } from './events/CaptureManifest.js';
20
+ export { SKIP_REASONS, isSkipReason, emptyCoverage, readCoverageManifest, } from './events/CaptureManifest.js';
15
21
  export type { Branding, BrandingOverrides } from './report/branding.js';
16
22
  export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
17
23
  export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
package/lib/index.js CHANGED
@@ -5,9 +5,12 @@ export { MetadataClientImpl } from './api/MetadataClientImpl.js';
5
5
  export { EMPTY_METRICS } from './context/OrgMetrics.js';
6
6
  // --- Event log ---
7
7
  export { EventBaselineStore } from './events/EventBaselineStore.js';
8
- export { sanitizeTypes, toLogDate, buildEventLogQuery } from './events/eventLogQuery.js';
9
- export { pullEventLogs } from './events/pullEventLogs.js';
8
+ export { sanitizeTypes, toLogDate, toLogHour, buildEventLogQuery, HOURLY_FORENSIC_CORE, } from './events/eventLogQuery.js';
9
+ export { pullEventLogs, MAX_FILE_BYTES } from './events/pullEventLogs.js';
10
10
  export { classifyEventLogAccessError } from './events/eventLogAccess.js';
11
+ export { RTE_CATALOG } from './events/rteCatalog.js';
12
+ export { pullRealtimeEvents, buildRealtimeQuery, describeFields, classifyRteError, } from './events/pullRealtimeEvents.js';
13
+ export { SKIP_REASONS, isSkipReason, emptyCoverage, readCoverageManifest, } from './events/CaptureManifest.js';
11
14
  export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
12
15
  export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
13
16
  export { esc } from './renderers/html-utils.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-core",
3
- "version": "0.1.4",
3
+ "version": "0.2.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",
@@ -25,9 +25,6 @@
25
25
  "clean": "rm -rf lib",
26
26
  "prepare": "git config core.hooksPath .githooks 2>/dev/null || true"
27
27
  },
28
- "dependencies": {
29
- "@salesforce/core": "^8"
30
- },
31
28
  "devDependencies": {
32
29
  "@jest/globals": "^29.7.0",
33
30
  "@types/jest": "^29",
@@ -36,7 +33,8 @@
36
33
  "jest": "^29",
37
34
  "ts-jest": "^29",
38
35
  "ts-node": "^10.9.2",
39
- "typescript": "^5"
36
+ "typescript": "^5",
37
+ "@salesforce/core": "^9"
40
38
  },
41
39
  "engines": {
42
40
  "node": ">=18.0.0"
@@ -78,5 +76,8 @@
78
76
  "brace-expansion": "^5.0.8",
79
77
  "fast-uri@3": "^3.1.4"
80
78
  }
79
+ },
80
+ "peerDependencies": {
81
+ "@salesforce/core": "^8 || ^9"
81
82
  }
82
83
  }