@conduit-client/service-pubsub 2.0.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,27 @@
1
+ *Attorney/Client Privileged + Confidential*
2
+
3
+ Terms of Use for Public Code (Non-OSS)
4
+
5
+ *NOTE:* Before publishing code under this license/these Terms of Use, please review https://salesforce.quip.com/WFfvAMKB18AL and confirm that you’ve completed all prerequisites described therein. *These Terms of Use may not be used or modified without input from IP and Product Legal.*
6
+
7
+ *Terms of Use*
8
+
9
+ Copyright 2022 Salesforce, Inc. All rights reserved.
10
+
11
+ These Terms of Use govern the download, installation, and/or use of this software provided by Salesforce, Inc. (“Salesforce”) (the “Software”), were last updated on April 15, 2022, ** and constitute a legally binding agreement between you and Salesforce. If you do not agree to these Terms of Use, do not install or use the Software.
12
+
13
+ Salesforce grants you a worldwide, non-exclusive, no-charge, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the Software and derivative works subject to these Terms. These Terms shall be included in all copies or substantial portions of the Software.
14
+
15
+ Subject to the limited rights expressly granted hereunder, Salesforce reserves all rights, title, and interest in and to all intellectual property subsisting in the Software. No rights are granted to you hereunder other than as expressly set forth herein. Users residing in countries on the United States Office of Foreign Assets Control sanction list, or which are otherwise subject to a US export embargo, may not use the Software.
16
+
17
+ Implementation of the Software may require development work, for which you are responsible. The Software may contain bugs, errors and incompatibilities and is made available on an AS IS basis without support, updates, or service level commitments.
18
+
19
+ Salesforce reserves the right at any time to modify, suspend, or discontinue, the Software (or any part thereof) with or without notice. You agree that Salesforce shall not be liable to you or to any third party for any modification, suspension, or discontinuance.
20
+
21
+ You agree to defend Salesforce against any claim, demand, suit or proceeding made or brought against Salesforce by a third party arising out of or accruing from (a) your use of the Software, and (b) any application you develop with the Software that infringes any copyright, trademark, trade secret, trade dress, patent, or other intellectual property right of any person or defames any person or violates their rights of publicity or privacy (each a “Claim Against Salesforce”), and will indemnify Salesforce from any damages, attorney fees, and costs finally awarded against Salesforce as a result of, or for any amounts paid by Salesforce under a settlement approved by you in writing of, a Claim Against Salesforce, provided Salesforce (x) promptly gives you written notice of the Claim Against Salesforce, (y) gives you sole control of the defense and settlement of the Claim Against Salesforce (except that you may not settle any Claim Against Salesforce unless it unconditionally releases Salesforce of all liability), and (z) gives you all reasonable assistance, at your expense.
22
+
23
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE SOFTWARE IS NOT SUPPORTED AND IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL SALESFORCE HAVE ANY LIABILITY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL, INCIDENTAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR DAMAGES BASED ON LOST PROFITS, DATA, OR USE, IN CONNECTION WITH THE SOFTWARE, HOWEVER CAUSED AND WHETHER IN CONTRACT, TORT, OR UNDER ANY OTHER THEORY OF LIABILITY, WHETHER OR NOT YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
24
+
25
+ These Terms of Use shall be governed exclusively by the internal laws of the State of California, without regard to its conflicts of laws rules. Each party hereby consents to the exclusive jurisdiction of the state and federal courts located in San Francisco County, California to adjudicate any dispute arising out of or relating to these Terms of Use and the download, installation, and/or use of the Software. Except as expressly stated herein, these Terms of Use constitute the entire agreement between the parties, and supersede all prior and contemporaneous agreements, proposals, or representations, written or oral, concerning their subject matter. No modification, amendment, or waiver of any provision of these Terms of Use shall be effective unless it is by an update to these Terms of Use that Salesforce makes available, or is in writing and signed by the party against whom the modification, amendment, or waiver is to be asserted.
26
+
27
+ _*Data Privacy*_: Salesforce may collect, process, and store device, system, and other information related to your use of the Software. This information includes, but is not limited to, IP address, user metrics, and other data (“Usage Data”). Salesforce may use Usage Data for analytics, product development, and marketing purposes. You acknowledge that files generated in conjunction with the Software may contain sensitive or confidential data, and you are solely responsible for anonymizing and protecting such data.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ This software is provided as-is with no support provided.
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
File without changes
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export { type NamedPubSubService, type PubSubService, type PubSubServiceDescriptor, buildServiceDescriptor, } from './pub-sub-service';
2
+ export { EventTypeWildcard, type Event, type EventSubscription } from './pubsub';
@@ -0,0 +1,15 @@
1
+ import { type PubSub } from './pubsub';
2
+ import type { NamedService, ServiceDescriptor } from '@conduit-client/utils';
3
+ /**
4
+ * An PubSubService tracks event topics and calls callbacks when
5
+ * a matching event is fired.
6
+ */
7
+ export type PubSubService = PubSub;
8
+ export type NamedPubSubService<Name extends string = 'pubSub'> = NamedService<Name, PubSubService>;
9
+ export type PubSubServiceDescriptor = ServiceDescriptor<PubSubService, 'pubSub', '1.0'>;
10
+ /**
11
+ * Constructs a default PubSubService
12
+ *
13
+ * @returns default PubSubServiceDescriptor
14
+ */
15
+ export declare function buildServiceDescriptor(): PubSubServiceDescriptor;
@@ -0,0 +1,51 @@
1
+ import type { SyncOrAsync, Unsubscribe } from '@conduit-client/utils';
2
+ export declare const EventTypeWildcard: unique symbol;
3
+ export type Event<Data = unknown> = {
4
+ type: string | typeof EventTypeWildcard;
5
+ data: Data;
6
+ };
7
+ export type EventSubscription<Data = unknown> = {
8
+ type: Event['type'];
9
+ callback: (event: Event<Data>) => void | PromiseLike<void>;
10
+ predicate?: (event: Event<Data>) => boolean;
11
+ };
12
+ /**
13
+ * A subscription callback function.
14
+ *
15
+ * @typeParam CallbackArg type of the single argument passed to the callback function
16
+ * @typeParam ReturnVal expected return type of the callback function
17
+ */
18
+ export type SubscriptionCallback<CallbackArgs extends Array<unknown>, ReturnVal = void> = (...arg: CallbackArgs) => ReturnVal;
19
+ /**
20
+ * A PubSub is a simple pub/sub mechanism. Callers can subscribe a
21
+ * callback function to be invoked when a token is published.
22
+ *
23
+ * @typeParam PublishType type of token that can be published
24
+ * @typeParam CallbackArg type of the single argument passed to the callback
25
+ * @typeParam SubscribeType type that can be subscribed to; defaults to
26
+ * PublishType, but can be set to a different type in cases where broader
27
+ * semantics would be useful (eg Set<PublishType>)
28
+ * @typeParam PulishOptions options that can be passed during publish
29
+ * @typeParam CallbackReturnVal return type expected from callbacks
30
+ */
31
+ export interface PubSub {
32
+ /**
33
+ * Creates a subscription that will invoke the specified callback when
34
+ * PublishTypes matching the subscription are published.
35
+ *
36
+ * @param options.subscription specification of PublishTypes to be matched
37
+ * @param options.callback callback to be invoked
38
+ * @returns function that can be invoked to cancel the subscription
39
+ */
40
+ subscribe<Data = unknown>(subscription: EventSubscription<Data>): Unsubscribe;
41
+ /**
42
+ * Publishes the specified PublishType and invokes the callbacks of all
43
+ * matching subscriptions.
44
+ *
45
+ * @param publishData PublishType to be published
46
+ * @param options
47
+ * @returns SyncOrAsync that can be used to determine when all callbacks
48
+ * have been called
49
+ */
50
+ publish(publishData: Event): SyncOrAsync<void>;
51
+ }
@@ -0,0 +1,114 @@
1
+ /*!
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+ /*!
7
+ * Copyright (c) 2022, Salesforce, Inc.,
8
+ * All rights reserved.
9
+ * For full license text, see the LICENSE.txt file
10
+ */
11
+ function resolvedPromiseLike(result) {
12
+ if (isPromiseLike(result)) {
13
+ return result.then((nextResult) => nextResult);
14
+ }
15
+ return {
16
+ then: (onFulfilled, _onRejected) => {
17
+ try {
18
+ return resolvedPromiseLike(onFulfilled(result));
19
+ } catch (e) {
20
+ if (onFulfilled === void 0) {
21
+ return resolvedPromiseLike(result);
22
+ }
23
+ return rejectedPromiseLike(e);
24
+ }
25
+ }
26
+ };
27
+ }
28
+ function rejectedPromiseLike(reason) {
29
+ if (isPromiseLike(reason)) {
30
+ return reason.then((nextResult) => nextResult);
31
+ }
32
+ return {
33
+ then: (_onFulfilled, onRejected) => {
34
+ if (typeof onRejected === "function") {
35
+ try {
36
+ return resolvedPromiseLike(onRejected(reason));
37
+ } catch (e) {
38
+ return rejectedPromiseLike(e);
39
+ }
40
+ }
41
+ return rejectedPromiseLike(reason);
42
+ }
43
+ };
44
+ }
45
+ function isPromiseLike(x) {
46
+ return typeof (x == null ? void 0 : x.then) === "function";
47
+ }
48
+ const EventTypeWildcard = Symbol("EventTypeWildcard");
49
+ class DefaultPubSubService {
50
+ constructor() {
51
+ this.subscriptions = /* @__PURE__ */ new Map();
52
+ }
53
+ subscribe(subscription) {
54
+ let eventTypeSubscriptions = this.subscriptions.get(subscription.type);
55
+ if (eventTypeSubscriptions === void 0) {
56
+ eventTypeSubscriptions = [];
57
+ this.subscriptions.set(subscription.type, eventTypeSubscriptions);
58
+ }
59
+ eventTypeSubscriptions.push(subscription);
60
+ return () => {
61
+ this.subscriptions.set(
62
+ subscription.type,
63
+ this.subscriptions.get(subscription.type).filter((value) => value !== subscription)
64
+ );
65
+ };
66
+ }
67
+ publish(event) {
68
+ const promises = [];
69
+ const subscriptions = this.getSubscriptions(event);
70
+ subscriptions.forEach((subscription) => {
71
+ if (!this.getSubscriptions(event).includes(subscription)) {
72
+ return;
73
+ }
74
+ const returnVal = subscription.callback.call(subscription, event);
75
+ if (isPromiseLike(returnVal)) {
76
+ promises.push(returnVal);
77
+ }
78
+ });
79
+ if (promises.length > 0) {
80
+ return Promise.all(promises).then(() => void 0);
81
+ }
82
+ return resolvedPromiseLike(void 0);
83
+ }
84
+ getSubscriptions(event) {
85
+ const eventTypeSubscriptions = this.subscriptions.get(event.type);
86
+ const wildcardSubscriptions = this.subscriptions.get(EventTypeWildcard);
87
+ if (eventTypeSubscriptions === void 0 && wildcardSubscriptions === void 0) {
88
+ return [];
89
+ }
90
+ let matchingSubscriptions = [];
91
+ if (eventTypeSubscriptions !== void 0) {
92
+ matchingSubscriptions = eventTypeSubscriptions.filter((subscription) => {
93
+ if (subscription.predicate) {
94
+ return subscription.predicate(event);
95
+ }
96
+ return true;
97
+ });
98
+ }
99
+ matchingSubscriptions = [...matchingSubscriptions, ...wildcardSubscriptions || []];
100
+ return matchingSubscriptions;
101
+ }
102
+ }
103
+ function buildServiceDescriptor() {
104
+ return {
105
+ type: "pubSub",
106
+ version: "1.0",
107
+ service: new DefaultPubSubService()
108
+ };
109
+ }
110
+ export {
111
+ EventTypeWildcard,
112
+ buildServiceDescriptor
113
+ };
114
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../utils/dist/index.js","../../src/v1/pubsub.ts","../../src/v1/pub-sub-service.ts"],"sourcesContent":["/*!\n * Copyright (c) 2022, Salesforce, Inc.,\n * All rights reserved.\n * For full license text, see the LICENSE.txt file\n */\nfunction bfs(start, predicate, getChildren) {\n const queue = [...start];\n const visited = /* @__PURE__ */ new Set([...start]);\n const matches2 = /* @__PURE__ */ new Set();\n while (queue.length) {\n const curr = queue.shift();\n if (predicate(curr)) {\n matches2.add(curr);\n }\n const children = getChildren(curr);\n for (const child of children) {\n if (!visited.has(child)) {\n visited.add(child);\n queue.push(child);\n }\n }\n }\n return matches2;\n}\nfunction lineFormatter(position, message, filePath) {\n return `${message} (${filePath}:${position.line}:${position.column})`;\n}\nclass DefaultFileParserLogger {\n constructor(services, filePath) {\n this.services = services;\n this.filePath = filePath;\n }\n trace(position, message) {\n this.services.logger.trace(this.format(position, message));\n }\n debug(position, message) {\n this.services.logger.debug(this.format(position, message));\n }\n info(position, message) {\n this.services.logger.info(this.format(position, message));\n }\n warn(position, message) {\n this.services.logger.warn(this.format(position, message));\n }\n error(position, message) {\n this.services.logger.error(this.format(position, message));\n }\n format(position, message) {\n return lineFormatter(position, message, this.filePath);\n }\n}\nfunction matches(test, s) {\n if (test === void 0) {\n return false;\n } else if (typeof test === \"string\") {\n return s === test;\n } else if (test instanceof RegExp) {\n return test.test(s);\n } else if (typeof test === \"function\") {\n return test(s);\n }\n return test.some((m) => matches(m, s));\n}\nfunction includes(incexc, s) {\n if (matches(incexc.exclude, s)) {\n return false;\n }\n if (matches(incexc.include, s)) {\n return true;\n }\n if (incexc.include) {\n return false;\n }\n return true;\n}\nconst { create, freeze, keys, entries } = Object;\nconst { hasOwnProperty } = Object.prototype;\nconst { isArray } = Array;\nconst { push, indexOf, slice } = Array.prototype;\nconst { stringify, parse } = JSON;\nconst WeakSetConstructor = WeakSet;\nconst LogLevelMap = {\n TRACE: 4,\n DEBUG: 3,\n INFO: 2,\n WARN: 1,\n ERROR: 0\n};\nclass ConsoleLogger {\n constructor(level = \"WARN\", printer = console.log, formatter = (level2, message) => `${level2}: ${message}`) {\n this.level = level;\n this.printer = printer;\n this.formatter = formatter;\n this.messages = [];\n }\n trace(message) {\n this.log(\"TRACE\", message);\n }\n debug(message) {\n this.log(\"DEBUG\", message);\n }\n info(message) {\n this.log(\"INFO\", message);\n }\n warn(message) {\n this.log(\"WARN\", message);\n }\n error(message) {\n this.log(\"ERROR\", message);\n }\n log(level, message) {\n if (LogLevelMap[level] > LogLevelMap[this.level]) {\n return;\n }\n this.printer(this.formatter(level, message));\n }\n}\nfunction loggerService(level, printer, formatter) {\n return new ConsoleLogger(level, printer, formatter);\n}\nclass Ok {\n constructor(value) {\n this.value = value;\n }\n isOk() {\n return true;\n }\n isErr() {\n return !this.isOk();\n }\n}\nclass Err {\n constructor(error) {\n this.error = error;\n }\n isOk() {\n return false;\n }\n isErr() {\n return !this.isOk();\n }\n}\nconst ok = (value) => new Ok(value);\nconst err = (err2) => new Err(err2);\nclass DataNotFoundError extends Error {\n constructor(message) {\n super(message);\n this.name = \"DataNotFoundError\";\n }\n}\nclass DataIncompleteError extends Error {\n constructor(message, partialData) {\n super(message);\n this.partialData = partialData;\n this.name = \"DataIncompleteError\";\n }\n}\nfunction isDataNotFoundError(error) {\n return error instanceof DataNotFoundError || error.name === \"DataNotFoundError\";\n}\nfunction isDataIncompleteError(error) {\n return error instanceof DataIncompleteError || error.name === \"DataIncompleteError\";\n}\nfunction isCacheHitOrError(value) {\n if (value.isErr() && (isDataIncompleteError(value.error) || isDataNotFoundError(value.error))) {\n return false;\n }\n return true;\n}\nfunction isCacheMiss(value) {\n return !isCacheHitOrError(value);\n}\nfunction isResult(value) {\n return value != null && typeof value === \"object\" && \"isOk\" in value && \"isErr\" in value && typeof value.isOk === \"function\" && typeof value.isErr === \"function\" && (value.isOk() === true && value.isErr() === false && \"value\" in value || value.isOk() === false && value.isErr() === true && \"error\" in value);\n}\nfunction setOverlaps(setA, setB) {\n for (const element of setA) {\n if (setB.has(element)) {\n return true;\n }\n }\n return false;\n}\nfunction setDifference(setA, setB) {\n const differenceSet = /* @__PURE__ */ new Set();\n for (const element of setA) {\n if (!setB.has(element)) {\n differenceSet.add(element);\n }\n }\n return differenceSet;\n}\nfunction addAllToSet(targetSet, sourceSet) {\n for (const element of sourceSet) {\n targetSet.add(element);\n }\n}\nconst toTypeScriptSafeIdentifier = (s) => s.length >= 1 ? s[0].replace(/[^$_\\p{ID_Start}]/u, \"_\") + s.slice(1).replace(/[^$\\u200c\\u200d\\p{ID_Continue}]/gu, \"_\") : \"\";\nfunction isSubscribable(obj) {\n return typeof obj === \"object\" && obj !== null && \"subscribe\" in obj && typeof obj.subscribe === \"function\" && \"refresh\" in obj && typeof obj.refresh === \"function\";\n}\nfunction isSubscribableResult(x) {\n if (!isResult(x)) {\n return false;\n }\n return isSubscribable(x.isOk() ? x.value : x.error);\n}\nfunction buildSubscribableResult(result, subscribe, refresh) {\n if (result.isOk()) {\n return ok({ data: result.value, subscribe, refresh });\n } else {\n return err({ failure: result.error, subscribe, refresh });\n }\n}\nfunction resolvedPromiseLike(result) {\n if (isPromiseLike(result)) {\n return result.then((nextResult) => nextResult);\n }\n return {\n then: (onFulfilled, _onRejected) => {\n try {\n return resolvedPromiseLike(onFulfilled(result));\n } catch (e) {\n if (onFulfilled === void 0) {\n return resolvedPromiseLike(result);\n }\n return rejectedPromiseLike(e);\n }\n }\n };\n}\nfunction rejectedPromiseLike(reason) {\n if (isPromiseLike(reason)) {\n return reason.then((nextResult) => nextResult);\n }\n return {\n then: (_onFulfilled, onRejected) => {\n if (typeof onRejected === \"function\") {\n try {\n return resolvedPromiseLike(onRejected(reason));\n } catch (e) {\n return rejectedPromiseLike(e);\n }\n }\n return rejectedPromiseLike(reason);\n }\n };\n}\nfunction isPromiseLike(x) {\n return typeof (x == null ? void 0 : x.then) === \"function\";\n}\nfunction racesync(values) {\n for (const value of values) {\n let settled = void 0;\n if (isPromiseLike(value)) {\n value.then(\n (_) => {\n settled = value;\n },\n (_) => {\n settled = value;\n }\n );\n } else {\n settled = resolvedPromiseLike(value);\n }\n if (settled !== void 0) {\n return settled;\n }\n }\n return Promise.race(values);\n}\nfunction withResolvers() {\n let resolve, reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\nfunction deepEquals(x, y) {\n if (x === void 0) {\n return y === void 0;\n } else if (x === null) {\n return y === null;\n } else if (y === null) {\n return x === null;\n } else if (isArray(x)) {\n if (!isArray(y) || x.length !== y.length) {\n return false;\n }\n for (let i = 0; i < x.length; ++i) {\n if (!deepEquals(x[i], y[i])) {\n return false;\n }\n }\n return true;\n } else if (typeof x === \"object\") {\n if (typeof y !== \"object\") {\n return false;\n }\n const xkeys = Object.keys(x);\n const ykeys = Object.keys(y);\n if (xkeys.length !== ykeys.length) {\n return false;\n }\n for (let i = 0; i < xkeys.length; ++i) {\n const key = xkeys[i];\n if (!deepEquals(x[key], y[key])) {\n return false;\n }\n }\n return true;\n }\n return x === y;\n}\nfunction stableJSONStringify(node) {\n if (node && node.toJSON && typeof node.toJSON === \"function\") {\n node = node.toJSON();\n }\n if (node === void 0) {\n return;\n }\n if (typeof node === \"number\") {\n return isFinite(node) ? \"\" + node : \"null\";\n }\n if (typeof node !== \"object\") {\n return stringify(node);\n }\n let i;\n let out;\n if (isArray(node)) {\n out = \"[\";\n for (i = 0; i < node.length; i++) {\n if (i) {\n out += \",\";\n }\n out += stableJSONStringify(node[i]) || \"null\";\n }\n return out + \"]\";\n }\n if (node === null) {\n return \"null\";\n }\n const objKeys = keys(node).sort();\n out = \"\";\n for (i = 0; i < objKeys.length; i++) {\n const key = objKeys[i];\n const value = stableJSONStringify(node[key]);\n if (!value) {\n continue;\n }\n if (out) {\n out += \",\";\n }\n out += stringify(key) + \":\" + value;\n }\n return \"{\" + out + \"}\";\n}\nfunction toError(x) {\n if (x instanceof Error) {\n return x;\n }\n return new Error(typeof x === \"string\" ? x : JSON.stringify(x));\n}\nfunction deepCopy(x) {\n const stringified = stringify(x);\n return stringified ? parse(stringified) : void 0;\n}\nfunction readableStreamToAsyncIterable(stream) {\n if (stream.locked) {\n return err(new Error(\"ReadableStream is already locked\"));\n }\n if (Symbol.asyncIterator in stream) {\n return ok(stream);\n }\n const reader = stream.getReader();\n return ok({\n [Symbol.asyncIterator]: () => ({\n next: async () => {\n try {\n const result = await reader.read();\n if (result.done) {\n try {\n reader.releaseLock();\n } catch {\n }\n return { done: true, value: void 0 };\n }\n return {\n done: false,\n value: result.value\n };\n } catch (e) {\n try {\n reader.releaseLock();\n } catch {\n }\n throw e;\n }\n },\n return: async (value) => {\n try {\n await reader.cancel();\n } catch {\n }\n try {\n reader.releaseLock();\n } catch {\n }\n return { done: true, value };\n },\n throw: async (exception) => {\n try {\n await reader.cancel();\n } catch {\n }\n try {\n reader.releaseLock();\n } catch {\n }\n throw exception;\n }\n })\n });\n}\nfunction satisfies(provided, requested) {\n const providedN = provided.split(\".\").map((s) => parseInt(s));\n const requestedN = requested.split(\".\").map((s) => parseInt(s));\n return providedN[0] === requestedN[0] && providedN[1] >= requestedN[1];\n}\nfunction stringIsVersion(s) {\n const versionParts = s.split(\".\");\n return (versionParts.length === 2 || versionParts.length === 3) && versionParts.every((part) => part.match(/^\\d+$/));\n}\nvar HttpStatusCode = /* @__PURE__ */ ((HttpStatusCode2) => {\n HttpStatusCode2[HttpStatusCode2[\"Ok\"] = 200] = \"Ok\";\n HttpStatusCode2[HttpStatusCode2[\"Created\"] = 201] = \"Created\";\n HttpStatusCode2[HttpStatusCode2[\"NoContent\"] = 204] = \"NoContent\";\n HttpStatusCode2[HttpStatusCode2[\"NotModified\"] = 304] = \"NotModified\";\n HttpStatusCode2[HttpStatusCode2[\"BadRequest\"] = 400] = \"BadRequest\";\n HttpStatusCode2[HttpStatusCode2[\"Unauthorized\"] = 401] = \"Unauthorized\";\n HttpStatusCode2[HttpStatusCode2[\"Forbidden\"] = 403] = \"Forbidden\";\n HttpStatusCode2[HttpStatusCode2[\"NotFound\"] = 404] = \"NotFound\";\n HttpStatusCode2[HttpStatusCode2[\"ServerError\"] = 500] = \"ServerError\";\n HttpStatusCode2[HttpStatusCode2[\"GatewayTimeout\"] = 504] = \"GatewayTimeout\";\n return HttpStatusCode2;\n})(HttpStatusCode || {});\nfunction getFetchResponseFromAuraError(err2) {\n if (err2.data !== void 0 && err2.data.statusCode !== void 0) {\n let data = {};\n data = err2.data;\n if (err2.id !== void 0) {\n data.id = err2.id;\n }\n return new FetchResponse(data.statusCode, data);\n }\n return new FetchResponse(500, {\n error: err2.message\n });\n}\nasync function coerceResponseToFetchResponse(response) {\n const { status } = response;\n const responseHeaders = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n let responseBody = null;\n if (status !== 204) {\n const contentType = responseHeaders[\"content-type\"];\n responseBody = contentType && contentType.startsWith(\"application/json\") ? await response.json() : await response.text();\n }\n return new FetchResponse(status, responseBody, responseHeaders);\n}\nfunction getStatusText(status) {\n switch (status) {\n case 200:\n return \"OK\";\n case 201:\n return \"Created\";\n case 304:\n return \"Not Modified\";\n case 400:\n return \"Bad Request\";\n case 404:\n return \"Not Found\";\n case 500:\n return \"Server Error\";\n default:\n return `Unexpected HTTP Status Code: ${status}`;\n }\n}\nclass FetchResponse extends Error {\n constructor(status, body, headers) {\n super();\n this.status = status;\n this.body = body;\n this.headers = headers || {};\n this.ok = status >= 200 && this.status <= 299;\n this.statusText = getStatusText(status);\n }\n}\nconst deeplyFrozen = new WeakSetConstructor();\nfunction deepFreeze(value) {\n if (typeof value !== \"object\" || value === null || deeplyFrozen.has(value)) {\n return;\n }\n deeplyFrozen.add(value);\n if (isArray(value)) {\n for (let i = 0, len = value.length; i < len; i += 1) {\n deepFreeze(value[i]);\n }\n } else {\n const keys$1 = keys(value);\n for (let i = 0, len = keys$1.length; i < len; i += 1) {\n deepFreeze(value[keys$1[i]]);\n }\n }\n freeze(value);\n}\nfunction isScalar(value) {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || value === null || value === void 0;\n}\nfunction isScalarObject(value) {\n return Object.values(value).every((value2) => isScalar(value2));\n}\nfunction isScalarArray(value) {\n return value.every((item) => isScalar(item));\n}\nfunction encodeQueryParam(paramName, value, explode) {\n switch (typeof value) {\n case \"string\":\n return [`${paramName}=${encodeURIComponent(value)}`];\n case \"number\":\n case \"boolean\":\n return [`${paramName}=${value}`];\n case \"object\":\n if (value === null) {\n return [];\n }\n if (isArray(value)) {\n if (!isScalarArray(value)) {\n throw new Error(`Unsupported non-scalar array type for ${paramName}`);\n }\n if (explode) {\n return value.map(\n (item) => `${paramName}=${item ? encodeURIComponent(item) : item}`\n );\n }\n return [\n `${paramName}=${value.map((item) => item ? encodeURIComponent(item) : item).join(\",\")}`\n ];\n }\n if (!isScalarObject(value)) {\n throw new Error(`Unsupported non-scalar object type for ${paramName}`);\n }\n if (explode) {\n return entries(value).map(\n ([key, value2]) => `${key}=${value2 ? encodeURIComponent(value2) : value2}`\n );\n }\n return [\n `${paramName}=${entries(value).flat().map((item) => item ? encodeURIComponent(item) : item).join(\",\")}`\n ];\n default:\n return [];\n }\n}\nclass InternalError extends Error {\n constructor(data) {\n super();\n this.data = data;\n this.type = \"internal\";\n }\n}\nclass UserVisibleError extends Error {\n constructor(data) {\n super();\n this.data = data;\n this.type = \"user-visible\";\n }\n}\nfunction applyDecorators(baseCommand, decorators, options) {\n if (!decorators || decorators.length === 0) {\n return baseCommand;\n }\n return decorators.reduce((command, decorator) => decorator(command, options), baseCommand);\n}\nexport {\n isArray as ArrayIsArray,\n indexOf as ArrayPrototypeIndexOf,\n push as ArrayPrototypePush,\n slice as ArrayPrototypeSlice,\n ConsoleLogger,\n DataIncompleteError,\n DataNotFoundError,\n DefaultFileParserLogger,\n Err,\n FetchResponse,\n HttpStatusCode,\n InternalError,\n parse as JSONParse,\n stringify as JSONStringify,\n LogLevelMap,\n create as ObjectCreate,\n entries as ObjectEntries,\n freeze as ObjectFreeze,\n keys as ObjectKeys,\n hasOwnProperty as ObjectPrototypeHasOwnProperty,\n Ok,\n UserVisibleError,\n WeakSetConstructor,\n addAllToSet,\n applyDecorators,\n bfs,\n buildSubscribableResult,\n coerceResponseToFetchResponse,\n deepCopy,\n deepEquals,\n deepFreeze,\n encodeQueryParam,\n err,\n getFetchResponseFromAuraError,\n includes,\n isCacheHitOrError,\n isCacheMiss,\n isDataIncompleteError,\n isDataNotFoundError,\n isPromiseLike,\n isResult,\n isSubscribable,\n isSubscribableResult,\n lineFormatter,\n loggerService,\n ok,\n racesync,\n readableStreamToAsyncIterable,\n rejectedPromiseLike,\n resolvedPromiseLike,\n satisfies,\n setDifference,\n setOverlaps,\n stableJSONStringify,\n stringIsVersion,\n toError,\n toTypeScriptSafeIdentifier,\n withResolvers\n};\n//# sourceMappingURL=index.js.map\n","import type { SyncOrAsync, Unsubscribe } from '@conduit-client/utils';\n\nexport const EventTypeWildcard = Symbol('EventTypeWildcard');\n\nexport type Event<Data = unknown> = {\n type: string | typeof EventTypeWildcard;\n data: Data;\n};\n\nexport type EventSubscription<Data = unknown> = {\n type: Event['type'];\n callback: (event: Event<Data>) => void | PromiseLike<void>;\n predicate?: (event: Event<Data>) => boolean;\n};\n\n/**\n * A subscription callback function.\n *\n * @typeParam CallbackArg type of the single argument passed to the callback function\n * @typeParam ReturnVal expected return type of the callback function\n */\nexport type SubscriptionCallback<CallbackArgs extends Array<unknown>, ReturnVal = void> = (\n ...arg: CallbackArgs\n) => ReturnVal;\n\n/**\n * A PubSub is a simple pub/sub mechanism. Callers can subscribe a\n * callback function to be invoked when a token is published.\n *\n * @typeParam PublishType type of token that can be published\n * @typeParam CallbackArg type of the single argument passed to the callback\n * @typeParam SubscribeType type that can be subscribed to; defaults to\n * PublishType, but can be set to a different type in cases where broader\n * semantics would be useful (eg Set<PublishType>)\n * @typeParam PulishOptions options that can be passed during publish\n * @typeParam CallbackReturnVal return type expected from callbacks\n */\nexport interface PubSub {\n /**\n * Creates a subscription that will invoke the specified callback when\n * PublishTypes matching the subscription are published.\n *\n * @param options.subscription specification of PublishTypes to be matched\n * @param options.callback callback to be invoked\n * @returns function that can be invoked to cancel the subscription\n */\n subscribe<Data = unknown>(subscription: EventSubscription<Data>): Unsubscribe;\n\n /**\n * Publishes the specified PublishType and invokes the callbacks of all\n * matching subscriptions.\n *\n * @param publishData PublishType to be published\n * @param options\n * @returns SyncOrAsync that can be used to determine when all callbacks\n * have been called\n */\n publish(publishData: Event): SyncOrAsync<void>;\n}\n","import { isPromiseLike, resolvedPromiseLike } from '@conduit-client/utils';\nimport { type EventSubscription, type Event, type PubSub, EventTypeWildcard } from './pubsub';\nimport type { NamedService, ServiceDescriptor, Unsubscribe } from '@conduit-client/utils';\n\n/**\n * An PubSubService tracks event topics and calls callbacks when\n * a matching event is fired.\n */\nexport type PubSubService = PubSub;\n\nexport type NamedPubSubService<Name extends string = 'pubSub'> = NamedService<Name, PubSubService>;\n\nexport type PubSubServiceDescriptor = ServiceDescriptor<PubSubService, 'pubSub', '1.0'>;\n\n/**\n * A simple implementation of PubSubService.\n */\nclass DefaultPubSubService implements PubSubService {\n private subscriptions = new Map<\n Event['type'], // event type acts as an index so that we don't have to search every subscription\n EventSubscription[]\n >();\n\n subscribe(subscription: EventSubscription): Unsubscribe {\n let eventTypeSubscriptions = this.subscriptions.get(subscription.type);\n if (eventTypeSubscriptions === undefined) {\n eventTypeSubscriptions = [];\n this.subscriptions.set(subscription.type, eventTypeSubscriptions);\n }\n\n eventTypeSubscriptions!.push(subscription);\n\n return () => {\n this.subscriptions.set(\n subscription.type,\n this.subscriptions.get(subscription.type)!.filter((value) => value !== subscription)\n );\n };\n }\n\n publish(event: Event): PromiseLike<void> {\n const promises: PromiseLike<void>[] = [];\n const subscriptions = this.getSubscriptions(event);\n\n subscriptions.forEach((subscription) => {\n // need to check that the subscription hasn't been unsubscribed during one of the callbacks\n if (!this.getSubscriptions(event).includes(subscription)) {\n return;\n }\n // Ensure callback maintains its context\n const returnVal = subscription.callback.call(subscription, event);\n\n if (isPromiseLike(returnVal)) {\n promises.push(returnVal);\n }\n });\n\n if (promises.length > 0) {\n return Promise.all(promises).then(() => undefined);\n }\n\n return resolvedPromiseLike(undefined);\n }\n\n getSubscriptions(event: Event) {\n const eventTypeSubscriptions = this.subscriptions.get(event.type);\n const wildcardSubscriptions = this.subscriptions.get(EventTypeWildcard);\n if (eventTypeSubscriptions === undefined && wildcardSubscriptions === undefined) {\n return [];\n }\n let matchingSubscriptions: EventSubscription[] = [];\n\n if (eventTypeSubscriptions !== undefined) {\n matchingSubscriptions = eventTypeSubscriptions.filter((subscription) => {\n if (subscription.predicate) {\n return subscription.predicate(event);\n }\n\n return true;\n });\n }\n matchingSubscriptions = [...matchingSubscriptions, ...(wildcardSubscriptions || [])];\n return matchingSubscriptions;\n }\n}\n\n/**\n * Constructs a default PubSubService\n *\n * @returns default PubSubServiceDescriptor\n */\nexport function buildServiceDescriptor(): PubSubServiceDescriptor {\n return {\n type: 'pubSub',\n version: '1.0',\n service: new DefaultPubSubService(),\n };\n}\n"],"names":[],"mappings":";;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAsNA,SAAS,o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0",
4
+ "private": false,
5
+ "description": "Luvio PubSub Service definition",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/salesforce-experience-platform-emu/luvio-next.git",
10
+ "directory": "packages/@conduit-client/services/pubsub"
11
+ },
12
+ "license": "SEE LICENSE IN LICENSE.txt",
13
+ "exports": {
14
+ "./v1": {
15
+ "import": "./dist/v1/index.js",
16
+ "types": "./dist/types/v1/index.d.ts",
17
+ "require": "./dist/v1/index.js"
18
+ }
19
+ },
20
+ "main": "./dist/main/index.js",
21
+ "module": "./dist/main/index.js",
22
+ "types": "./dist/main/index.d.ts",
23
+ "files": [
24
+ "dist/"
25
+ ],
26
+ "scripts": {
27
+ "build": "vite build && tsc --build --emitDeclarationOnly",
28
+ "clean": "rm -rf dist",
29
+ "test": "vitest run",
30
+ "test:size": "size-limit",
31
+ "watch": "npm run build --watch"
32
+ },
33
+ "dependencies": {
34
+ "@conduit-client/utils": "2.0.0"
35
+ },
36
+ "volta": {
37
+ "extends": "../../../../package.json"
38
+ },
39
+ "size-limit": [
40
+ {
41
+ "path": "./dist/v1/index.js",
42
+ "limit": "900 B"
43
+ }
44
+ ]
45
+ }