@salesforce/emp-api 12.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,82 @@
1
+ Terms of Use
2
+
3
+ Copyright 2026 Salesforce, Inc. All rights reserved.
4
+
5
+ These Terms of Use govern the download, installation, and/or use of this
6
+ software provided by Salesforce, Inc. ("Salesforce") (the "Software"), were
7
+ last updated on April 15, 2025, and constitute a legally binding
8
+ agreement between you and Salesforce. If you do not agree to these Terms of
9
+ Use, do not install or use the Software.
10
+
11
+ Salesforce grants you a worldwide, non-exclusive, no-charge, royalty-free
12
+ copyright license to reproduce, prepare derivative works of, publicly
13
+ display, publicly perform, sublicense, and distribute the Software and
14
+ derivative works subject to these Terms. These Terms shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ Subject to the limited rights expressly granted hereunder, Salesforce
18
+ reserves all rights, title, and interest in and to all intellectual
19
+ property subsisting in the Software. No rights are granted to you hereunder
20
+ other than as expressly set forth herein. Users residing in countries on
21
+ the United States Office of Foreign Assets Control sanction list, or which
22
+ are otherwise subject to a US export embargo, may not use the Software.
23
+
24
+ Implementation of the Software may require development work, for which you
25
+ are responsible. The Software may contain bugs, errors and
26
+ incompatibilities and is made available on an AS IS basis without support,
27
+ updates, or service level commitments.
28
+
29
+ Salesforce reserves the right at any time to modify, suspend, or
30
+ discontinue, the Software (or any part thereof) with or without notice. You
31
+ agree that Salesforce shall not be liable to you or to any third party for
32
+ any modification, suspension, or discontinuance.
33
+
34
+ You agree to defend Salesforce against any claim, demand, suit or
35
+ proceeding made or brought against Salesforce by a third party arising out
36
+ of or accruing from (a) your use of the Software, and (b) any application
37
+ you develop with the Software that infringes any copyright, trademark,
38
+ trade secret, trade dress, patent, or other intellectual property right of
39
+ any person or defames any person or violates their rights of publicity or
40
+ privacy (each a "Claim Against Salesforce"), and will indemnify Salesforce
41
+ from any damages, attorney fees, and costs finally awarded against
42
+ Salesforce as a result of, or for any amounts paid by Salesforce under a
43
+ settlement approved by you in writing of, a Claim Against Salesforce,
44
+ provided Salesforce (x) promptly gives you written notice of the Claim
45
+ Against Salesforce, (y) gives you sole control of the defense and
46
+ settlement of the Claim Against Salesforce (except that you may not settle
47
+ any Claim Against Salesforce unless it unconditionally releases Salesforce
48
+ of all liability), and (z) gives you all reasonable assistance, at your
49
+ expense.
50
+
51
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE SOFTWARE IS NOT
52
+ SUPPORTED AND IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED. IN NO EVENT SHALL SALESFORCE HAVE ANY LIABILITY FOR ANY DAMAGES,
54
+ INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
55
+ PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR DAMAGES BASED ON LOST PROFITS, DATA,
56
+ OR USE, IN CONNECTION WITH THE SOFTWARE, HOWEVER CAUSED AND WHETHER IN
57
+ CONTRACT, TORT, OR UNDER ANY OTHER THEORY OF LIABILITY, WHETHER OR NOT YOU
58
+ HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
59
+
60
+ These Terms of Use shall be governed exclusively by the internal laws of
61
+ the State of California, without regard to its conflicts of laws
62
+ rules. Each party hereby consents to the exclusive jurisdiction of the
63
+ state and federal courts located in San Francisco County, California to
64
+ adjudicate any dispute arising out of or relating to these Terms of Use and
65
+ the download, installation, and/or use of the Software. Except as expressly
66
+ stated herein, these Terms of Use constitute the entire agreement between
67
+ the parties, and supersede all prior and contemporaneous agreements,
68
+ proposals, or representations, written or oral, concerning their subject
69
+ matter. No modification, amendment, or waiver of any provision of these
70
+ Terms of Use shall be effective unless it is by an update to these Terms of
71
+ Use that Salesforce makes available, or is in writing and signed by the
72
+ party against whom the modification, amendment, or waiver is to be
73
+ asserted.
74
+
75
+ Data Privacy: Salesforce may collect, process, and store device,
76
+ system, and other information related to your use of the Software. This
77
+ information includes, but is not limited to, IP address, user metrics, and
78
+ other data ("Usage Data"). Salesforce may use Usage Data for analytics,
79
+ product development, and marketing purposes. You acknowledge that files
80
+ generated in conjunction with the Software may contain sensitive or
81
+ confidential data, and you are solely responsible for anonymizing and
82
+ protecting such data.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @salesforce/emp-api (Beta)
2
+
3
+ > **Beta:** This is a pilot or beta service subject to the
4
+ > [Beta Services Terms](https://www.salesforce.com/company/legal/agreements/) or a written
5
+ > Unified Pilot Agreement, and applicable terms in the
6
+ > [Product Terms Directory](https://ptd.salesforce.com/).
7
+
8
+ An `empApi`-shaped wrapper (`subscribe`, `unsubscribe`, `onError`) for the
9
+ platform's CometD/Bayeux streaming engine, so a UI Bundle can react to
10
+ Platform Events and Change Data Capture (CDC) events without polling.
11
+
12
+ Provides the same functionality of [lightning/empApi](https://developer.salesforce.com/docs/platform/lightning-component-reference/guide/lightning-emp-api.html?type=Develop) for
13
+ ui-bundles.
14
+
15
+ Like the `lightning/empApi` module, `@salesforce/emp-api` is supported only in desktop browsers and requires API version 65.0 or later. For use in Lightning Experience only.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @salesforce/emp-api
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```ts
26
+ import { subscribe } from "@salesforce/emp-api";
27
+
28
+ const subscription = await subscribe(
29
+ "/data/Account__ChangeEvent", // or a Platform Event channel, e.g. "/event/Foo__e"
30
+ -1, // replayId: -1 = new events only, -2 = replay retention window, or a specific id
31
+ (message) => {
32
+ console.log(message.channel, message.data.payload);
33
+ },
34
+ );
35
+
36
+ // later
37
+ subscription.unsubscribe();
38
+ ```
39
+
40
+ ```ts
41
+ import { onError } from "@salesforce/emp-api";
42
+
43
+ const removeListener = onError((message) => {
44
+ // Handle connection/transport errors, including a subscribe failure
45
+ // (e.g. an invalid channel).
46
+ });
47
+
48
+ // later, to stop this listener from receiving further errors
49
+ removeListener();
50
+ ```
51
+
52
+ ## API
53
+
54
+ - **`subscribe(channel, replayId, onMessage)`** — Subscribes to a
55
+ Platform Event or CDC channel. Resolves once the streaming engine is
56
+ configured and the subscription is registered (it does not wait for a
57
+ server ack). Two calls on the same channel produce two independent
58
+ subscriptions.
59
+ - **`unsubscribe(subscription)`** — Also available as `subscription.unsubscribe()`.
60
+ Synchronous, and a no-op if already unsubscribed.
61
+ - **`onError(callback)`** — Registers a listener for engine-level errors.
62
+ Per-channel and later transport failures surface here, not through the
63
+ `subscribe()` promise. Returns a function that removes this listener.
64
+
65
+ Messages delivered to `onMessage` are one of two shapes — a Platform Event
66
+ message, or a Change Data Capture message whose payload carries a
67
+ `ChangeEventHeader` (fields per Salesforce's [Change Data Capture Developer
68
+ Guide](https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_event_fields_header.htm)):
69
+
70
+ ```ts
71
+ interface PlatformEventMessage {
72
+ channel: string;
73
+ data: {
74
+ schema?: string;
75
+ payload: Record<string, unknown>;
76
+ event: { replayId: number; EventUuid?: string };
77
+ };
78
+ }
79
+
80
+ interface ChangeDataCaptureMessage {
81
+ channel: string;
82
+ data: {
83
+ schema?: string;
84
+ payload: { ChangeEventHeader: ChangeEventHeader } & Record<string, unknown>;
85
+ event: { replayId: number };
86
+ };
87
+ }
88
+ ```
89
+
90
+ Use `isChangeDataCaptureMessage(message)` to narrow — the channel string
91
+ alone isn't a reliable discriminant, since the aggregate `/data/ChangeEvents`
92
+ channel carries CDC messages for multiple entities:
93
+
94
+ ```ts
95
+ import { isChangeDataCaptureMessage, subscribe } from "@salesforce/emp-api";
96
+
97
+ await subscribe("/data/ChangeEvents", -1, (message) => {
98
+ if (isChangeDataCaptureMessage(message)) {
99
+ console.log(message.data.payload.ChangeEventHeader.changeType);
100
+ }
101
+ });
102
+ ```
103
+
104
+ ## Configuration
105
+
106
+ Before the engine can start, it needs a CometD URL and worker script path.
107
+ These are resolved automatically from the platform's GraphQL API via
108
+ `getStreamingConfig` — this is an internal implementation detail of
109
+ `subscribe()`, not something callers can override.
110
+
111
+ ## Vendored engine
112
+
113
+ This package wraps the platform's CometD/Bayeux client, vendored unedited
114
+ under `src/vendor` (original copyright preserved). It does not modify the
115
+ vendored engine's internal logic.
package/dist/api.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ import { GetStreamingConfig } from './config';
2
+ import { EmpErrorMessage, StreamingMessage, Subscription } from './types';
3
+ import { EmpSubscriptionHandle } from './vendor/emp.js';
4
+ /**
5
+ * Subscribes to a Platform Event or CDC channel.
6
+ *
7
+ * The returned Promise waits only on the one-time config fetch + engine
8
+ * init, never on a `/meta/subscribe` server ack — it resolves right after
9
+ * `Emp.init()` and the engine's synchronous `subscribe()` call for this
10
+ * channel. It rejects only if config/init cannot be obtained; per-channel
11
+ * and later transport failures surface exclusively through {@link onError},
12
+ * never through this Promise, and never after it has already resolved.
13
+ *
14
+ * `channel` and `replayId` are passed straight through with no validation,
15
+ * clamping, or rewriting. Two `subscribe()` calls on the same channel are
16
+ * two independent handles.
17
+ *
18
+ * @param channel - A Platform Event or CDC channel name, e.g. `/event/Foo__e`.
19
+ * @param replayId - `-1` for new events from the tip, `-2` to replay the
20
+ * retention window, or a numeric replay id.
21
+ * @param onMessage - Invoked with each delivered message.
22
+ * @param getConfig - Injectable config seam, defaults to the real
23
+ * GraphQL-backed {@link getStreamingConfig}. Tests substitute a fake. Not
24
+ * part of the public interface — the barrel's exported `subscribe` omits
25
+ * this parameter.
26
+ *
27
+ * A failed subscribe ack (`successful !== true`) is also routed to
28
+ * `onError`'s listeners via this call's own `subscribeCallback`, not just
29
+ * the engine's broadcast — the ack is delivered before the engine's
30
+ * empty-subscriptions disconnect check runs, so it survives even when the
31
+ * connection is torn down immediately after (see `dispatchError`).
32
+ */
33
+ export declare function subscribe(channel: string, replayId: number, onMessage: (message: StreamingMessage) => void, getConfig?: GetStreamingConfig): Promise<Subscription>;
34
+ /**
35
+ * Unsubscribes a handle returned by {@link subscribe}.
36
+ * Synchronous, returns nothing, and is a silent no-op on a handle that has
37
+ * already been unsubscribed — v1 has no completion callback, since the
38
+ * vendored engine's unsubscribe callback is not a reliable per-handle ack.
39
+ *
40
+ * @param subscription - The handle returned by {@link subscribe}.
41
+ */
42
+ export declare function unsubscribe(subscription: Subscription | EmpSubscriptionHandle): void;
43
+ /**
44
+ * Registers an error listener. Errors are passed
45
+ * through unfiltered; classifying transient reconnect blips vs. terminal
46
+ * failure is a caller concern, not this package's.
47
+ *
48
+ * The vendored engine itself has no per-listener removal — this package
49
+ * tracks listeners on its own side and the returned function splices this
50
+ * registration out of that list, rather than deleting anything from the
51
+ * engine. Each call wraps `callback` in a fresh closure before storing it,
52
+ * so registering the exact same function reference more than once still
53
+ * gives each call its own removable registration — removing one doesn't
54
+ * touch another registration that happens to wrap the same callback.
55
+ *
56
+ * Note the engine's inherited `clearState()` behavior: it sends an
57
+ * unsubscribe for every active local subscription but does not delete this
58
+ * package's bookkeeping the way public `unsubscribe()` does, so a message
59
+ * can still fire after `clearState()` — that is existing engine behavior,
60
+ * not something this package fixes.
61
+ *
62
+ * @param callback - Invoked with the engine's error/reply message.
63
+ * @returns A function that removes this listener. Calling it more than once
64
+ * is a no-op.
65
+ */
66
+ export declare function onError(callback: (message: EmpErrorMessage) => void): () => void;
67
+ /**
68
+ * Test-only escape hatch to reset the module-level init guard between test
69
+ * cases. Not part of the public barrel.
70
+ */
71
+ export declare function _resetInitGuardForTests(): void;
72
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAsB,KAAK,kBAAkB,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC/E,OAAO,EAAO,KAAK,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAyKlE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,SAAS,CAC9B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,IAAI,EAC9C,SAAS,GAAE,kBAAuC,GAChD,OAAO,CAAC,YAAY,CAAC,CAsBvB;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,YAAY,EAAE,YAAY,GAAG,qBAAqB,GAAG,IAAI,CAEpF;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,GAAG,MAAM,IAAI,CAUhF;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,IAAI,IAAI,CAK9C"}
@@ -0,0 +1,22 @@
1
+ import { StreamingConfig } from './types';
2
+ /**
3
+ * Config-fetch seam. The real implementation below issues
4
+ * `uiapi.platform.streamingConfig` — a GraphQL field whose server-side
5
+ * landing status is unverified from this workspace (see README.md). Tests
6
+ * substitute this seam with a fake resolving to fixed values; a local-dev
7
+ * harness may instead resolve `cometdUrl`/`cometdWorkerJs` from the
8
+ * already-working proxy routes in `packages/ui-bundle/src/proxy` without
9
+ * going through GraphQL at all — this package makes no assumption either way
10
+ * beyond the shape below.
11
+ */
12
+ export type GetStreamingConfig = () => Promise<StreamingConfig>;
13
+ /**
14
+ * Production implementation of {@link GetStreamingConfig}. Missing or empty
15
+ * `cometdUrl`/`cometdWorkerJs` — including a GraphQL surface with no
16
+ * `graphql` namespace, a query error, or a field that has not landed
17
+ * server-side yet — all resolve to the same refusal: this function rejects,
18
+ * which feeds the caller's terminal-refusal path (see `ensureInit` in
19
+ * `api.ts`).
20
+ */
21
+ export declare function getStreamingConfig(): Promise<StreamingConfig>;
22
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;;;GASG;AACH,MAAM,MAAM,kBAAkB,GAAG,MAAM,OAAO,CAAC,eAAe,CAAC,CAAC;AA0BhE;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,eAAe,CAAC,CAsBnE"}
@@ -0,0 +1,12 @@
1
+ import { StreamingMessage, Subscription } from './types';
2
+ export { unsubscribe, onError } from './api';
3
+ export { isChangeDataCaptureMessage } from './types';
4
+ export type { BayeuxFailure, ChangeDataCaptureMessage, ChangeEventHeader, EmpErrorMessage, PlatformEventMessage, StreamingConfig, StreamingMessage, Subscription, } from './types';
5
+ /**
6
+ * Subscribes to a Platform Event or CDC channel. See {@link subscribeInternal}
7
+ * for full behavior. The config seam (`getConfig`) is an internal
8
+ * implementation detail used by tests — it is intentionally not part of the
9
+ * public interface.
10
+ */
11
+ export declare function subscribe(channel: string, replayId: number, onMessage: (message: StreamingMessage) => void): Promise<Subscription>;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAiBH,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE9D,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAC;AACrD,YAAY,EACX,aAAa,EACb,wBAAwB,EACxB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,EACpB,eAAe,EACf,gBAAgB,EAChB,YAAY,GACZ,MAAM,SAAS,CAAC;AAEjB;;;;;GAKG;AACH,wBAAsB,SAAS,CAC9B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,IAAI,GAC5C,OAAO,CAAC,YAAY,CAAC,CAEvB"}
package/dist/index.js ADDED
@@ -0,0 +1,625 @@
1
+ import { gql as je, createDataSDK as Ge } from "@salesforce/platform-sdk";
2
+ const Ke = je`
3
+ query GetStreamingConfig {
4
+ uiapi {
5
+ platform {
6
+ streamingConfig {
7
+ cometdUrl
8
+ cometdWorkerJs
9
+ }
10
+ }
11
+ }
12
+ }
13
+ `;
14
+ async function Be() {
15
+ const r = await Ge();
16
+ if (!r.graphql)
17
+ throw new Error("@salesforce/emp-api: GraphQL is not supported on this surface");
18
+ const a = await r.graphql.query({
19
+ query: Ke
20
+ }), l = a.data?.uiapi?.platform?.streamingConfig, d = l?.cometdUrl, b = l?.cometdWorkerJs;
21
+ if (a.errors?.length || !d || !b)
22
+ throw new Error(
23
+ "@salesforce/emp-api: failed to resolve uiapi.platform.streamingConfig (cometdUrl/cometdWorkerJs missing, or the GraphQL query errored)"
24
+ );
25
+ return { cometdUrl: d, cometdWorkerJs: b };
26
+ }
27
+ function Ve(r, a) {
28
+ const l = "emp.leaderElection", d = "emp.heartbeat", b = ["FOLLOWER", "CANDIDATE", "LEADER"], E = Date.now() + "_" + w(1, 1e4), y = 4e3, T = 6e3, _ = 3e3, S = 4e3;
29
+ let u = b[0], p = !1, s = 0, g = !1, f = null, C, L, O = !1;
30
+ const D = {};
31
+ D.heartBeat = () => {
32
+ const n = {};
33
+ return n.eventType = "heartbeat", n.leader = {
34
+ id: E,
35
+ candidateTime: f
36
+ }, n;
37
+ }, D.election = () => {
38
+ const n = {};
39
+ return n.eventType = "election", n.candidateId = E, n.candidateTime = f, n;
40
+ }, D.vote = (n) => {
41
+ const i = {};
42
+ return i.eventType = "vote", i.candidateId = n, i;
43
+ };
44
+ function h(...n) {
45
+ O && window.console.log(...n);
46
+ }
47
+ function c(n) {
48
+ return typeof n == "function";
49
+ }
50
+ function w(n, i) {
51
+ return n = Math.ceil(n), i = Math.floor(i), Math.floor(Math.random() * (i - n + 1)) + n;
52
+ }
53
+ function k(n) {
54
+ J(d, n);
55
+ }
56
+ function H(n) {
57
+ J(l, n);
58
+ }
59
+ function J(n, i) {
60
+ i.time = Date.now();
61
+ const V = JSON.stringify(i);
62
+ window.localStorage.setItem(n, V);
63
+ }
64
+ function P(n) {
65
+ c(a) && a(n);
66
+ }
67
+ function j(n) {
68
+ u === b[2] && f > n.leader.candidateTime && (u = b[0], clearInterval(C), C = null), L !== n.leader.id && (L = n.leader.id, P({ leaderId: L })), g = !1, s = 0, p = !0;
69
+ }
70
+ function G(n) {
71
+ n.candidateId === E && (s += 1, h("[EmpLe] Vote handler: received votes [" + s + "]"));
72
+ }
73
+ function N(n) {
74
+ return n === E;
75
+ }
76
+ function W(n) {
77
+ h("[EmpLe] Election handler");
78
+ const i = n.candidateId;
79
+ if (N(i)) {
80
+ h(
81
+ "[EmpLe] Event candidateId is same as Node Id. Ignore our own heartbeat message"
82
+ );
83
+ return;
84
+ }
85
+ !K() && n.candidateTime < f && (u = b[0], h(
86
+ "[EmpLe] Election handler: Detected two candidates or leaders, becoming follower."
87
+ )), R() && K() && (h("[EmpLe] Election handler: voted for [" + i + "]."), H(D.vote(i)), g = !0), p = !0;
88
+ }
89
+ function R() {
90
+ return !g;
91
+ }
92
+ function K() {
93
+ return u === b[0];
94
+ }
95
+ function A() {
96
+ window.setTimeout(() => {
97
+ p ? (p = !1, A()) : F();
98
+ }, w(y, T));
99
+ }
100
+ function v() {
101
+ window.setTimeout(() => {
102
+ h(
103
+ "[EmpLe] Election Timedout: heartbeat received=" + p
104
+ ), p ? (p = !1, A()) : s > 0 && u !== b[0] && (u = b[2], g = !1, h(
105
+ "[EmpLe] Yay I am the leader :" + E + " with [" + s + "] votes."
106
+ ), X(), P({ leaderId: E }));
107
+ }, w(S, S));
108
+ }
109
+ function F() {
110
+ u = b[1], s = 0, p ? A() : (s += 1, g = !0, f = Date.now(), H(D.election()), v());
111
+ }
112
+ function X() {
113
+ C = window.setInterval(() => {
114
+ k(D.heartBeat());
115
+ }, w(_, _));
116
+ }
117
+ function U() {
118
+ clearInterval(C), C = null;
119
+ }
120
+ function B(n) {
121
+ let i;
122
+ n.newValue && (n.key === l || n.key === d) && (i = JSON.parse(n.newValue)), i && i.eventType && (h("[EmpLe]", i), i.eventType === "heartbeat" && j(i), i.eventType === "vote" && G(i), i.eventType === "election" && W(i));
123
+ }
124
+ function z() {
125
+ c(r) && r({ nodeId: E }), window.addEventListener("storage", B), A();
126
+ }
127
+ function $(n) {
128
+ O = n;
129
+ }
130
+ function x() {
131
+ try {
132
+ h("[EmpLe] Stopping heartbeats..."), U(), h("[EmpLe] Successfully stopped heartbeats");
133
+ } catch (n) {
134
+ h("[EmpLe] Failed to stop heartbeats. Reason = " + n);
135
+ }
136
+ }
137
+ return {
138
+ start: z,
139
+ stop: x,
140
+ setDebugFlag: $
141
+ };
142
+ }
143
+ const Q = (() => {
144
+ const r = "org.cometd.reload.fromLocalStorage", a = "emp.cometd", l = "emp.debugFlag", d = J(), b = D(), E = {
145
+ log: () => {
146
+ }
147
+ }, y = {
148
+ SHARED_WORKER: "In shared worker mode. When shared worker is available.",
149
+ LEADER_ELECTION: "In leader election mode. When shared worker is not available and local storage is available.",
150
+ STANDALONE: "In standalone mode. When local storage and shared worker are not available."
151
+ };
152
+ let T, _, S = null;
153
+ const u = {}, p = {};
154
+ let s = null, g = null, f = null, C = null, L = {}, O = b;
155
+ function D() {
156
+ return d ? localStorage.getItem(l) === "true" : !1;
157
+ }
158
+ function h() {
159
+ return O;
160
+ }
161
+ function c() {
162
+ return h() ? window.console : E;
163
+ }
164
+ function w(e) {
165
+ return typeof e == "function";
166
+ }
167
+ function k(e, t) {
168
+ Object.entries(e).forEach(([o, m]) => {
169
+ t.length === 2 ? t(o, m) : t(m);
170
+ });
171
+ }
172
+ function H() {
173
+ return !!navigator.userAgent.match(/ipad|iphone|ipod/i);
174
+ }
175
+ function J() {
176
+ try {
177
+ return G("key", { value: "emp.test" }), localStorage.removeItem("key"), !0;
178
+ } catch {
179
+ return !1;
180
+ }
181
+ }
182
+ function P(e, t) {
183
+ return e = Math.ceil(e), t = Math.floor(t), Math.floor(Math.random() * (t - e + 1)) + e;
184
+ }
185
+ function j() {
186
+ let e = "";
187
+ return f && (e = f), e + "_" + Date.now() + "_" + P(1, 1e4);
188
+ }
189
+ function G(e, t) {
190
+ t.time = Date.now();
191
+ const o = JSON.stringify(t);
192
+ window.localStorage.setItem(e, o);
193
+ }
194
+ function N(e) {
195
+ if (!d) {
196
+ c().log(
197
+ "[Emp] Is localStorage available",
198
+ d
199
+ );
200
+ return;
201
+ }
202
+ G(a, e);
203
+ }
204
+ function W(e) {
205
+ c().log("[Emp] toCometdWorker: ", e);
206
+ let t = s;
207
+ s ? (S === y.SHARED_WORKER && (t = s.port), t.postMessage(e)) : N(e);
208
+ }
209
+ function R(e) {
210
+ return !!u[e.id];
211
+ }
212
+ function K(e) {
213
+ return !!p[e.id];
214
+ }
215
+ function A(e) {
216
+ return !!L[e.id];
217
+ }
218
+ function v() {
219
+ return C === f;
220
+ }
221
+ function F() {
222
+ return !!C || s;
223
+ }
224
+ function X(e) {
225
+ return e.data.nodeId === f;
226
+ }
227
+ function U(e) {
228
+ const t = {};
229
+ return t.id = e.id, t.channel = e.channel, t.replayId = e.replayId, t;
230
+ }
231
+ function B(e) {
232
+ const t = {};
233
+ return t.id = e.id, t;
234
+ }
235
+ function z() {
236
+ if (_) {
237
+ const e = {
238
+ eventType: "functionCall",
239
+ nodeId: f,
240
+ functionName: "init",
241
+ functionParams: {
242
+ config: ie()
243
+ }
244
+ };
245
+ c().log("[Emp] Init config, remote call with ", e), W(e);
246
+ }
247
+ }
248
+ function $() {
249
+ return {
250
+ subscriptions: u,
251
+ unsubscribes: p
252
+ };
253
+ }
254
+ function x(e) {
255
+ _ = e, T = _.paths.cometdWorkerJs, S = Ne(), c().log(
256
+ "[Emp] Init config, the mode of operation is ",
257
+ S
258
+ ), S === y.LEADER_ELECTION && He(), !F() && Object.keys(u).length > 0 && ee();
259
+ }
260
+ function n(e) {
261
+ b || (O = e, i());
262
+ }
263
+ function i() {
264
+ _ && W({
265
+ eventType: "functionCall",
266
+ nodeId: f,
267
+ functionName: "setDebugFlag",
268
+ functionParams: {
269
+ debugFlag: O
270
+ }
271
+ }), g && g.setDebugFlag(O);
272
+ }
273
+ function V(e) {
274
+ const t = {
275
+ eventType: "functionCall",
276
+ nodeId: f,
277
+ functionName: "addOnErrorListener",
278
+ functionParams: {
279
+ listener: B(e)
280
+ }
281
+ };
282
+ W(t);
283
+ }
284
+ function oe() {
285
+ k(L, V);
286
+ }
287
+ function fe(e) {
288
+ const t = {
289
+ eventType: "functionCall",
290
+ nodeId: f,
291
+ functionName: "removeOnErrorListener",
292
+ functionParams: {
293
+ listener: B(e)
294
+ }
295
+ };
296
+ W(t);
297
+ }
298
+ function be() {
299
+ k(L, fe), L = {};
300
+ }
301
+ function pe(e) {
302
+ const t = {};
303
+ t.id = j(), t.callback = e, L[t.id] = t, F() && V(t);
304
+ }
305
+ function re() {
306
+ be(), Ie();
307
+ }
308
+ function me(e) {
309
+ k(u, (t, o) => {
310
+ o.channel === e && delete u[t];
311
+ });
312
+ }
313
+ function Ee(e) {
314
+ k(p, (t, o) => {
315
+ o.channel === e && delete p[t];
316
+ });
317
+ }
318
+ function ge(e) {
319
+ const t = e.message, o = JSON.parse(t);
320
+ o && (o.channel === "/meta/subscribe" || o.channel === "/meta/unsubscribe") && o.subscription && (me(o.subscription), Ee(o.subscription)), k(L, (m) => {
321
+ const I = m.callback;
322
+ w(I) && I(o);
323
+ });
324
+ }
325
+ function ie() {
326
+ if (_) {
327
+ const e = JSON.parse(JSON.stringify(_));
328
+ return d && (e.cometdState = window.localStorage.getItem(
329
+ r
330
+ )), e;
331
+ }
332
+ return {};
333
+ }
334
+ function ae(e) {
335
+ const t = {
336
+ eventType: "functionCall",
337
+ nodeId: f,
338
+ functionName: "subscribe",
339
+ functionParams: {
340
+ subscription: U(e),
341
+ config: ie()
342
+ }
343
+ };
344
+ c().log("[Emp] subscribe with ", t), W(t);
345
+ }
346
+ function se() {
347
+ k(u, ae);
348
+ }
349
+ function _e(e, t, o, m) {
350
+ const I = {}, q = j();
351
+ I.id = q, I.channel = e, I.replayId = t, I.callback = o, w(m) && (I.subscribeCallback = m), u[q] = I;
352
+ const Pe = U(I);
353
+ return F() ? ae(I) : ee(), Pe;
354
+ }
355
+ function he(e, t) {
356
+ if (e) {
357
+ const o = u[e.id];
358
+ o && (delete u[e.id], p[o.id] = o, o.unsubscribeCallback = t, ce(o));
359
+ }
360
+ }
361
+ function ce(e) {
362
+ let t;
363
+ e && (t = {
364
+ eventType: "functionCall",
365
+ nodeId: f,
366
+ functionName: "unsubscribe",
367
+ functionParams: {
368
+ subscription: U(e)
369
+ }
370
+ }, c().log("[Emp] unsubscribe with ", t), W(t));
371
+ }
372
+ function Ie() {
373
+ k(u, ce);
374
+ }
375
+ function ye(e) {
376
+ let t, o;
377
+ e && e.subscription && R(e.subscription) && (t = e.subscription.id, o = u[t], o.cometdSubscription = e.subscription.cometdSubscription);
378
+ }
379
+ function Se(e) {
380
+ let t, o, m;
381
+ e && e.message && (t = e.subscription.id, o = p[t], o && (m = o.unsubscribeCallback, t && (e.message.successful && delete p[t], c().log(
382
+ "[Emp] unsubscribe callback called for subscription",
383
+ o
384
+ ), w(m) && m(e.message))));
385
+ const I = Object.keys(p).length, q = Object.keys(u).length;
386
+ c().log(
387
+ "[Emp] No. of unsubscribes = " + I + ", unsubscribes object:",
388
+ p
389
+ ), c().log(
390
+ "[Emp] No. of subscriptions = " + q + ", subscriptions object:",
391
+ u
392
+ );
393
+ }
394
+ function Ce(e) {
395
+ let t, o, m;
396
+ e && e.subscription && (t = e.subscription.id, o = u[t], m = e.message, o && o.callback && (Le(o, m), o.callback(m)));
397
+ }
398
+ function Le(e, t) {
399
+ t && t.data && t.data.event && t.data.event.replayId && (e.replayId = t.data.event.replayId);
400
+ }
401
+ function we(e) {
402
+ let t, o, m;
403
+ e && e.subscription && (t = e.subscription.id, o = u[t], m = e.message, o && o.subscribeCallback && o.subscribeCallback(m));
404
+ }
405
+ function ke() {
406
+ c().log("[Emp] Clearing state before unload..."), re();
407
+ }
408
+ function Te(e) {
409
+ if (!d)
410
+ return;
411
+ let t = null;
412
+ e && e.params && (t = e.params.state, window.localStorage.setItem(r, t), c().log("[Emp] Cometd state in main is " + t));
413
+ }
414
+ function Oe() {
415
+ d && window.localStorage.removeItem(r);
416
+ }
417
+ function De() {
418
+ c().log("[Emp] Terminating cometd worker..."), s && (S === y.LEADER_ELECTION && Je(), S === y.SHARED_WORKER ? s.port.close() : s.terminate(), c().log("[Emp] Set cometdWorker to null"), s = null);
419
+ }
420
+ function Z(e) {
421
+ if (c().log("[Emp] fromCometdWorker: ", e), e && e.data) {
422
+ if (e.data.eventType === "functionCall")
423
+ switch (e.data.functionName) {
424
+ case "subscribeCallback": {
425
+ R(e.data.subscription) ? we(e.data) : N(e.data);
426
+ return;
427
+ }
428
+ case "unsubscribeCallback": {
429
+ K(e.data.subscription) ? Se(e.data) : N(e.data);
430
+ return;
431
+ }
432
+ case "messageCallback": {
433
+ R(e.data.subscription) ? Ce(e.data) : N(e.data);
434
+ return;
435
+ }
436
+ case "onErrorCallback": {
437
+ A(e.data.listener) ? ge(e.data) : N(e.data);
438
+ return;
439
+ }
440
+ case "saveCometdState": {
441
+ Te(e.data);
442
+ return;
443
+ }
444
+ case "removeCometdState": {
445
+ Oe();
446
+ return;
447
+ }
448
+ case "terminateWorker": {
449
+ De();
450
+ return;
451
+ }
452
+ case "setDebugFlag":
453
+ return;
454
+ default:
455
+ c().log(
456
+ "[Emp] fromCometdWorker: No handler found for [" + e.data.functionName + "]."
457
+ );
458
+ }
459
+ e.data.eventType === "functionReturn" && e.data.functionName === "subscribe" && (R(e.data.subscription) ? ye(e.data) : N(e.data));
460
+ }
461
+ }
462
+ function Ne() {
463
+ return !H() && Re() ? y.SHARED_WORKER : We() ? y.LEADER_ELECTION : y.STANDALONE;
464
+ }
465
+ function We() {
466
+ return d && !!window.Worker;
467
+ }
468
+ function Re() {
469
+ let e = T && "SharedWorker" in window;
470
+ if (e)
471
+ try {
472
+ const t = new SharedWorker(T);
473
+ e = e && "port" in t, e = e && "postMessage" in t.port;
474
+ } catch (t) {
475
+ c().log(
476
+ "Unable to create SharedWorker instance because of ",
477
+ t
478
+ ), e = !1;
479
+ }
480
+ return e;
481
+ }
482
+ function Ae() {
483
+ return !s && S === y.SHARED_WORKER;
484
+ }
485
+ function ve() {
486
+ return !s && (v() || S === y.STANDALONE);
487
+ }
488
+ function ee() {
489
+ if (T) {
490
+ let e = !1;
491
+ Ae() ? (c().log("[Emp] Create new SharedWorker"), s = new SharedWorker(T), s.port.addEventListener(
492
+ "message",
493
+ Z
494
+ ), s.port.start(), e = !0) : ve() && (c().log("[Emp] Create new WebWorker"), s = new Worker(T), s.addEventListener("message", Z), e = !0), e && (c().log("[Emp] New Worker Created"), i(), z(), oe(), se());
495
+ }
496
+ }
497
+ function Me(e) {
498
+ f = e.nodeId, w(_.onNodeIdInit) && _.onNodeIdInit(f);
499
+ }
500
+ function Fe(e) {
501
+ C !== e.leaderId && (C = e.leaderId, _.onLeaderChange && _.onLeaderChange(C === f), v() ? ee() : (se(), oe()));
502
+ }
503
+ function Ue(e) {
504
+ const t = {};
505
+ let o;
506
+ e.newValue && e.key === a && (o = JSON.parse(e.newValue), t.data = o), o && o.eventType && (v() ? s ? s.postMessage(o) : c().log("[Emp] Cometd Worker is undefined!") : X(t) && Z(t));
507
+ }
508
+ function He() {
509
+ g || (window.addEventListener("storage", Ue), g = new Ve(Me, Fe), g.setDebugFlag(O), g.start());
510
+ }
511
+ function Je() {
512
+ g && v() && (c().log("[Emp] Stop sending heartbeats..."), g.stop(), c().log("[Emp] Leader stopped sending heartbeats"));
513
+ }
514
+ return window.addEventListener("unload", ke), {
515
+ init: x,
516
+ subscribe: _e,
517
+ unsubscribe: he,
518
+ onError: pe,
519
+ clearState: re,
520
+ setDebugFlag: n,
521
+ getState: $
522
+ };
523
+ })();
524
+ function ue(r) {
525
+ return typeof r == "object" && r !== null;
526
+ }
527
+ function qe(r) {
528
+ if (typeof r != "object" || r === null)
529
+ return !1;
530
+ const a = r.data;
531
+ if (typeof a != "object" || a === null)
532
+ return !1;
533
+ const l = a.payload, d = a.event;
534
+ return typeof r.channel == "string" && typeof l == "object" && l !== null && typeof d == "object" && d !== null;
535
+ }
536
+ let te = null;
537
+ function Ye(r) {
538
+ return te || (te = r().then((a) => {
539
+ Q.init({
540
+ cometdUrl: a.cometdUrl,
541
+ paths: { cometdWorkerJs: a.cometdWorkerJs }
542
+ });
543
+ })), te;
544
+ }
545
+ const Y = [];
546
+ let le = !1;
547
+ const Qe = 2e3, Xe = 200, M = /* @__PURE__ */ new Map();
548
+ function ze(r) {
549
+ return ue(r) ? r.id == null ? null : String(r.id) : null;
550
+ }
551
+ function ne(r) {
552
+ const a = ze(r);
553
+ if (a !== null) {
554
+ const l = Date.now(), d = M.get(a);
555
+ if (d !== void 0 && l - d < Qe)
556
+ return;
557
+ if (d !== void 0)
558
+ M.delete(a);
559
+ else if (M.size >= Xe) {
560
+ const b = M.keys().next().value;
561
+ M.delete(b);
562
+ }
563
+ M.set(a, l);
564
+ }
565
+ for (const l of [...Y])
566
+ try {
567
+ l(r);
568
+ } catch {
569
+ }
570
+ }
571
+ function de() {
572
+ le || (le = !0, Q.onError(ne));
573
+ }
574
+ function $e(r) {
575
+ return { id: r.id, channel: r.channel, replayId: r.replayId };
576
+ }
577
+ function xe(r) {
578
+ return {
579
+ id: r.id,
580
+ channel: r.channel,
581
+ replayId: r.replayId,
582
+ unsubscribe: () => et(r)
583
+ };
584
+ }
585
+ async function Ze(r, a, l, d = Be) {
586
+ await Ye(d), de();
587
+ const b = Q.subscribe(
588
+ r,
589
+ a,
590
+ (E) => {
591
+ qe(E) && l(E);
592
+ },
593
+ (E) => {
594
+ if (!ue(E)) {
595
+ ne({ successful: !1, error: "Invalid ack payload" });
596
+ return;
597
+ }
598
+ E.successful !== !0 && ne(E);
599
+ }
600
+ );
601
+ return xe(b);
602
+ }
603
+ function et(r) {
604
+ Q.unsubscribe($e(r));
605
+ }
606
+ function nt(r) {
607
+ de();
608
+ const a = (l) => r(l);
609
+ return Y.push(a), () => {
610
+ const l = Y.indexOf(a);
611
+ l !== -1 && Y.splice(l, 1);
612
+ };
613
+ }
614
+ function ot(r) {
615
+ return typeof r.data?.payload == "object" && r.data.payload !== null && "ChangeEventHeader" in r.data.payload;
616
+ }
617
+ async function rt(r, a, l) {
618
+ return Ze(r, a, l);
619
+ }
620
+ export {
621
+ ot as isChangeDataCaptureMessage,
622
+ nt as onError,
623
+ rt as subscribe,
624
+ et as unsubscribe
625
+ };
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+ /**
7
+ * A handle returned by {@link subscribe}. `unsubscribe()` is additive sugar
8
+ * delegating to the package-level `unsubscribe(subscription)`.
9
+ */
10
+ export interface Subscription {
11
+ id: string;
12
+ channel: string;
13
+ replayId: number;
14
+ unsubscribe(): void;
15
+ }
16
+ /**
17
+ * The header Salesforce attaches to every Change Data Capture event's
18
+ * `payload.ChangeEventHeader`. Source: Salesforce Change Data
19
+ * Capture Developer Guide, "ChangeEventHeader Fields" —
20
+ * https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_event_fields_header.htm
21
+ *
22
+ * `nulledFields`/`diffFields` are populated only via Apex triggers or the
23
+ * Pub/Sub API, never via this CometD-based client, but are kept optional
24
+ * here rather than omitted since a caller may still receive them relayed
25
+ * from another source.
26
+ */
27
+ export interface ChangeEventHeader {
28
+ entityName: string;
29
+ recordIds: string[];
30
+ changeType: "CREATE" | "UPDATE" | "DELETE" | "UNDELETE" | "SNAPSHOT" | "GAP_CREATE" | "GAP_UPDATE" | "GAP_DELETE" | "GAP_UNDELETE" | "GAP_OVERFLOW";
31
+ changeOrigin: string;
32
+ transactionKey: string;
33
+ sequenceNumber: number;
34
+ commitTimestamp: number;
35
+ commitUser: string;
36
+ commitNumber: number;
37
+ nulledFields?: string[];
38
+ diffFields?: string[];
39
+ changedFields?: string[];
40
+ }
41
+ /**
42
+ * A Change Data Capture message — a `StreamingMessage` whose payload carries
43
+ * `ChangeEventHeader`. Payload shape varies by
44
+ * `ChangeEventHeader.changeType`: CREATE/UNDELETE carry the full record,
45
+ * UPDATE carries only the fields listed in `changedFields`, and
46
+ * DELETE, the `GAP_*` types, and GAP_OVERFLOW carry no record fields beyond
47
+ * the header.
48
+ */
49
+ export interface ChangeDataCaptureMessage {
50
+ channel: string;
51
+ data: {
52
+ schema?: string;
53
+ payload: {
54
+ ChangeEventHeader: ChangeEventHeader;
55
+ } & Record<string, unknown>;
56
+ event: {
57
+ replayId: number;
58
+ };
59
+ };
60
+ }
61
+ /**
62
+ * A plain Platform Event message — a `StreamingMessage` whose payload is
63
+ * just the event's custom fields, with no `ChangeEventHeader`. `TPayload` is
64
+ * a caller-supplied shape for the specific event's custom fields (e.g. the
65
+ * fields defined on a `Foo__e` object); it is not validated at runtime.
66
+ */
67
+ export interface PlatformEventMessage<TPayload extends Record<string, unknown> = Record<string, unknown>> {
68
+ channel: string;
69
+ data: {
70
+ schema?: string;
71
+ payload: TPayload;
72
+ event: {
73
+ replayId: number;
74
+ EventUuid?: string;
75
+ };
76
+ };
77
+ }
78
+ /**
79
+ * A message delivered to a `subscribe` callback. Covers both Platform Events
80
+ * (`/event/*`) and CDC (`/data/*ChangeEvent`, including the aggregate
81
+ * `/data/ChangeEvents` channel) — use {@link isChangeDataCaptureMessage} to
82
+ * narrow, since the aggregate channel means the channel string alone can't
83
+ * reliably discriminate the two.
84
+ */
85
+ export type StreamingMessage = ChangeDataCaptureMessage | PlatformEventMessage;
86
+ /**
87
+ * Narrows a {@link StreamingMessage} to a {@link ChangeDataCaptureMessage} by
88
+ * checking for `ChangeEventHeader` on the payload, rather than the channel
89
+ * string — the aggregate `/data/ChangeEvents` channel carries CDC messages
90
+ * for multiple entities without a per-entity channel name to key off of.
91
+ *
92
+ * `StreamingMessage` guarantees `data.payload` is a non-null object at the
93
+ * type level, but this is a publicly exported function — a caller can still
94
+ * hand it an unvalidated value via `as StreamingMessage`, so the shape is
95
+ * checked defensively rather than assumed.
96
+ */
97
+ export declare function isChangeDataCaptureMessage(message: StreamingMessage): message is ChangeDataCaptureMessage;
98
+ /**
99
+ * Config resolved once per session and passed to the vendored engine's
100
+ * `init`. See {@link ../config.getStreamingConfig}.
101
+ */
102
+ export interface StreamingConfig {
103
+ cometdUrl: string;
104
+ cometdWorkerJs: string;
105
+ }
106
+ /**
107
+ * The CometD client's own failure diagnostics for a `/meta/connect` or
108
+ * `/meta/handshake` failure — not part of the Bayeux spec itself, but a
109
+ * shape the vendored engine's underlying CometD client constructs and
110
+ * passes through unmodified. `message` is the original outgoing Bayeux
111
+ * request that failed.
112
+ */
113
+ export interface BayeuxFailure {
114
+ reason?: string;
115
+ httpCode?: number;
116
+ exception?: unknown;
117
+ connectionType?: string;
118
+ transport?: unknown;
119
+ websocketCode?: number;
120
+ message?: EmpErrorMessage;
121
+ }
122
+ /**
123
+ * A Bayeux/CometD error or failed-ack message, as delivered by the vendored
124
+ * engine's `onError` broadcast or a subscribe's own failed ack (see
125
+ * `api.ts`'s `dispatchError`). Always arrives on a `/meta/*` channel
126
+ * (handshake/connect/subscribe/unsubscribe/disconnect) or `/meta/publish` —
127
+ * never on the caller's own subscribed data channel. All fields are optional
128
+ * because different `/meta/*` failures carry different subsets — a
129
+ * `/meta/subscribe` failure carries `subscription`/`id`/`successful`, while
130
+ * a `/meta/connect` failure carries a nested `failure` diagnostic instead.
131
+ */
132
+ export interface EmpErrorMessage {
133
+ id?: string | number | null;
134
+ channel?: string;
135
+ clientId?: string;
136
+ successful?: boolean;
137
+ error?: string;
138
+ subscription?: string;
139
+ failure?: BayeuxFailure;
140
+ }
141
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ /**
8
+ * Ambient type declaration for the vendored `emp.js` (see emp.js's own
9
+ * header for its original copyright). Not edited — this file only describes
10
+ * the surface this package wraps.
11
+ */
12
+ export interface EmpConfig {
13
+ cometdUrl?: string;
14
+ paths: {
15
+ cometdWorkerJs: string;
16
+ };
17
+ onNodeIdInit?: (nodeId: string) => void;
18
+ onLeaderChange?: (isLeader: boolean) => void;
19
+ }
20
+
21
+ export interface EmpSubscriptionHandle {
22
+ id: string;
23
+ channel: string;
24
+ replayId: number;
25
+ }
26
+
27
+ export interface EmpState {
28
+ subscriptions: Record<string, unknown>;
29
+ unsubscribes: Record<string, unknown>;
30
+ }
31
+
32
+ export const Emp: {
33
+ init(config: EmpConfig): void;
34
+ subscribe(
35
+ channel: string,
36
+ from: number,
37
+ msgCallback: (message: unknown) => void,
38
+ subscribeCallback?: (message: unknown) => void,
39
+ ): EmpSubscriptionHandle;
40
+ unsubscribe(subscription: EmpSubscriptionHandle, callback?: (message: unknown) => void): void;
41
+ onError(callback: (message: unknown) => void): void;
42
+ clearState(): void;
43
+ setDebugFlag(flag: boolean): void;
44
+ getState(): EmpState;
45
+ };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@salesforce/emp-api",
3
+ "version": "12.6.0",
4
+ "description": "empApi-shaped wrapper for UI Bundles over the platform CometD/Bayeux streaming engine, so a UI Bundle can react to Platform Events and Change Data Capture (CDC) events without polling.",
5
+ "license": "SEE LICENSE IN LICENSE.txt",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "sideEffects": true,
11
+ "exports": {
12
+ "./package.json": "./package.json",
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "build": "vite build",
24
+ "clean": "rm -rf dist",
25
+ "dev": "vite build --watch",
26
+ "test": "vitest run",
27
+ "test:watch": "vitest",
28
+ "test:coverage": "vitest run --coverage"
29
+ },
30
+ "peerDependencies": {
31
+ "@salesforce/platform-sdk": "^12.6.0"
32
+ },
33
+ "devDependencies": {
34
+ "@salesforce/platform-sdk": "^12.6.0",
35
+ "vite": "^7.3.5",
36
+ "vite-plugin-dts": "^4.5.4",
37
+ "vitest": "^4.0.6"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }