@salesforce/storefront-next-runtime 0.1.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 +181 -0
- package/README.md +158 -0
- package/dist/ComponentContext.js +14 -0
- package/dist/ComponentContext.js.map +1 -0
- package/dist/DesignContext.js +769 -0
- package/dist/DesignContext.js.map +1 -0
- package/dist/DesignContext2.js +6 -0
- package/dist/PageDesignerProvider.js +53 -0
- package/dist/PageDesignerProvider.js.map +1 -0
- package/dist/PageRegistration.js +29 -0
- package/dist/PageRegistration.js.map +1 -0
- package/dist/PreviewContext.js +18 -0
- package/dist/PreviewContext.js.map +1 -0
- package/dist/design-messaging.d.ts +3 -0
- package/dist/design-messaging.js +3 -0
- package/dist/design-mode.d.ts +40 -0
- package/dist/design-mode.d.ts.map +1 -0
- package/dist/design-mode.js +3 -0
- package/dist/design-react-core.d.ts +69 -0
- package/dist/design-react-core.d.ts.map +1 -0
- package/dist/design-react-core.js +23 -0
- package/dist/design-react-core.js.map +1 -0
- package/dist/design-react.d.ts +130 -0
- package/dist/design-react.d.ts.map +1 -0
- package/dist/design-react.js +488 -0
- package/dist/design-react.js.map +1 -0
- package/dist/design-styles.css +232 -0
- package/dist/design.d.ts +2 -0
- package/dist/design.js +219 -0
- package/dist/design.js.map +1 -0
- package/dist/events.d.ts +208 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +104 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +215 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index2.d.ts +1171 -0
- package/dist/index2.d.ts.map +1 -0
- package/dist/messaging-api.js +340 -0
- package/dist/messaging-api.js.map +1 -0
- package/dist/modeDetection.js +50 -0
- package/dist/modeDetection.js.map +1 -0
- package/dist/scapi.d.ts +29278 -0
- package/dist/scapi.d.ts.map +1 -0
- package/dist/scapi.js +2 -0
- package/dist/scapi.js.map +1 -0
- package/dist/types.d.ts +13293 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +108 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index2.d.ts","names":[],"sources":["../src/design/messaging-api/domain-types.ts","../src/design/messaging-api/api-types.ts","../src/design/messaging-api/client.ts","../src/design/messaging-api/host.ts"],"sourcesContent":[],"mappings":";;;;AAyGA,UAjFU,aAAA,CAiFoB;EA8Db,SAAA,EAAA,MAAA;AAiBjB;AAeA;AAkBA;AAiBA;AAUA;AASA,UA7NU,eAAA,CA6NO;EASA;AAQjB;;EAAmE,WAAA,EAAA,MAAA;;UAvOzD,iBAAA,CAuO4F;EAQrF;AAQjB;AAQA;EAAgE,aAAA,EAAA,MAAA;;;;;;AAchE,UAlQU,gBAAA,CAkQO;EAWA;;;;EAAqF,CAAA,EAAA,MAAA;EASrF;;;;EACL,CAAA,EAAA,MAAA;;AAUK,UApRA,yBAAA,CAoR0B;EAa1B;AAiBjB;AAqCA;EAQiB,UAAA,EA3VD,MA2VC,CAAA,MAAA,EA3Vc,aA2VmB,CAAA;EAQjC;AAQjB;AAQA;EAiBiB,cAAA,EAhYG,MAgYH,CAAA,MAAA,EAhYkB,aAgYS,CAAA;EAAgB;;;EAChD,MAAA,EA7XA,MA6XA,CAAA,MAAA,EAAA,MAAA,CAAA;EAAa;AA2CzB;AAYA;;;;AC7eA;AAQA;AA0BA;AAMiB,KD4BL,oBAAA,GC5B+B,SAAA,GAAA,WAAA,GAAA,WAAA,GAAA,YAAA,GAAA,QAAA;;;;AAIpB,UD6BN,aAAA,CC7BM;EACE;;;EAGG,EAAA,EAAA,MAAA;EACH;;;EAQR,IAAA,EAAA,MAAA;;;;;AAA6B,UD8B7B,aAAA,CC9B6B;EAA0B;AAWxE;;EAEyB,EAAA,EAAA,MAAA;EACL;;;EAGS,IAAA,EAAA,MAAA;EACF;;;EAGK,KAAA,EAAA,MAAA;EACT;;;EAXmD,KAAA,EAAA,MAAA;AAkB1E;AAIA;AAIA;AAOA;;;;;AAcA;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wCAkCZ,0BAA0B,gCACrD,aAAa,gCAAuC;;;;;;;;wBAUzC,aAAa;;;;;;;;;;;;gCAYL,aAAa;;;;ADnnB/C;AA8DA;AAiBA;AAeA;AAkBA;AAiBA;AAUA;AASiB,iBE7ND,eAAA,CF6NiC;EAAA,OAAA;EAAQ,EAAA;EAAA,aAAe;EAAA;AAAyB,CAAzB,EE7NK,mBF6NoB,CAAA,EE7NE,SF6NF;;;AApJjG;AA8DA;AAiBA;AAeA;AAkBA;AAiBA;AAUA;AASiB,iBG3ND,aAAA,CH2NiC;EAAA,OAAA;EAAA,EAAQ;EAAA;AAAe,CAAf,EG3NF,iBH2NiB,CAAA,EG3NG,OH2NH"}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
//#region src/design/messaging-api/messenger.ts
|
|
2
|
+
/**
|
|
3
|
+
* Handles the basic logic for event emitting and receiving between a client and a host.
|
|
4
|
+
*
|
|
5
|
+
* The `Messenger` class manages a single connection to a source event emitter,
|
|
6
|
+
* allowing for the sending and receiving of typed events between two parties (e.g., client and host).
|
|
7
|
+
* It distinguishes events based on their source, ensuring that only events from the opposite source are processed.
|
|
8
|
+
*
|
|
9
|
+
* @template TInMapping - The mapping of incoming event names to their payload types.
|
|
10
|
+
* @template TOutMapping - The mapping of outgoing event names to their payload types.
|
|
11
|
+
*/
|
|
12
|
+
var Messenger = class {
|
|
13
|
+
source;
|
|
14
|
+
id;
|
|
15
|
+
emitter;
|
|
16
|
+
handlers = /* @__PURE__ */ new Map();
|
|
17
|
+
remoteId;
|
|
18
|
+
logger;
|
|
19
|
+
_isReady = false;
|
|
20
|
+
unsubscribe;
|
|
21
|
+
queue = [];
|
|
22
|
+
constructor({ source, id, emitter, logger = () => {} }) {
|
|
23
|
+
this.source = source;
|
|
24
|
+
this.id = id;
|
|
25
|
+
this.emitter = emitter;
|
|
26
|
+
this.logger = logger;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Connects the given emitter. This ensures only a single connection to the provided emitter.
|
|
30
|
+
*
|
|
31
|
+
* This method registers a listener for events from the opposite source.
|
|
32
|
+
* It ensures that only events from the opposite source are processed.
|
|
33
|
+
*/
|
|
34
|
+
connect() {
|
|
35
|
+
this.unsubscribe?.();
|
|
36
|
+
this._isReady = false;
|
|
37
|
+
this.unsubscribe = this.emitter.addEventListener((event) => {
|
|
38
|
+
if (event.meta?.pdMessagingApi && event.meta.source !== this.source) {
|
|
39
|
+
this.logger(event, this.source === "host" ? "client" : "host");
|
|
40
|
+
[event.eventType, "Event"].forEach((eventType) => {
|
|
41
|
+
this.handlers.get(eventType)?.forEach((handler) => handler(event));
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
markIsReady: () => {
|
|
47
|
+
this._isReady = true;
|
|
48
|
+
},
|
|
49
|
+
emptyQueue: () => {
|
|
50
|
+
this.queue.forEach(({ eventType, data }) => this.emit(eventType, data));
|
|
51
|
+
this.queue = [];
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Returns the id of the connected remote.
|
|
57
|
+
*/
|
|
58
|
+
getRemoteId() {
|
|
59
|
+
return this.remoteId;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Sets the id of the connected remote.
|
|
63
|
+
*/
|
|
64
|
+
setRemoteId(remoteId) {
|
|
65
|
+
this.remoteId = remoteId;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Emits an event to the connected remote.
|
|
69
|
+
* This attaches metadata to each event that is emitted.
|
|
70
|
+
*
|
|
71
|
+
* @param eventName - The event to emit.
|
|
72
|
+
* @param data - The data to emit.
|
|
73
|
+
* @param options - The options for the event.
|
|
74
|
+
* @param options.requireRemoteId - Whether to require a remote id to be set before emitting the event.
|
|
75
|
+
*/
|
|
76
|
+
emit(eventType, data, { requireRemoteId = true } = {}) {
|
|
77
|
+
if (requireRemoteId && !this._isReady) {
|
|
78
|
+
this.queue.push({
|
|
79
|
+
eventType,
|
|
80
|
+
data
|
|
81
|
+
});
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const event = {
|
|
85
|
+
...data,
|
|
86
|
+
eventType,
|
|
87
|
+
meta: {
|
|
88
|
+
hostId: this.source === "host" ? this.id : this.remoteId,
|
|
89
|
+
clientId: this.source === "client" ? this.id : this.remoteId,
|
|
90
|
+
source: this.source,
|
|
91
|
+
pdMessagingApi: true
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
this.logger(event, this.source);
|
|
95
|
+
this.emitter.postMessage(event);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Subscribes to an event from the connected remote.
|
|
99
|
+
*
|
|
100
|
+
* @param event - The event to subscribe to.
|
|
101
|
+
* @param handler - The handler to call when the event is emitted.
|
|
102
|
+
* @returns A function to unsubscribe from the event.
|
|
103
|
+
*/
|
|
104
|
+
on(event, handler) {
|
|
105
|
+
const handlers = this.handlers.get(event) ?? [];
|
|
106
|
+
handlers.push(handler);
|
|
107
|
+
this.handlers.set(event, handlers);
|
|
108
|
+
return () => {
|
|
109
|
+
const eventHandlers = this.handlers.get(event) ?? [];
|
|
110
|
+
const index = eventHandlers.indexOf(handler);
|
|
111
|
+
if (index > -1) eventHandlers.splice(index, 1);
|
|
112
|
+
if (eventHandlers.length === 0) this.handlers.delete(event);
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Returns a function that emits an event to the connected remote.
|
|
117
|
+
*
|
|
118
|
+
* @param eventName - The event to emit.
|
|
119
|
+
* @returns A function that emits an event to the connected remote.
|
|
120
|
+
*/
|
|
121
|
+
toEmitter(eventName) {
|
|
122
|
+
return (event) => {
|
|
123
|
+
this.emit(eventName, event);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
toPromise(eventName) {
|
|
127
|
+
return new Promise((resolve) => {
|
|
128
|
+
const unsub = this.on(eventName, (event) => {
|
|
129
|
+
unsub();
|
|
130
|
+
resolve(event);
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Disconnects the messenger.
|
|
136
|
+
*/
|
|
137
|
+
disconnect() {
|
|
138
|
+
this.unsubscribe?.();
|
|
139
|
+
this.handlers.clear();
|
|
140
|
+
this.remoteId = void 0;
|
|
141
|
+
this.unsubscribe = void 0;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Returns whether the messenger is ready to emit events.
|
|
145
|
+
*
|
|
146
|
+
* @returns Whether the messenger is ready.
|
|
147
|
+
*/
|
|
148
|
+
isReady() {
|
|
149
|
+
return this._isReady;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region src/design/messaging-api/client.ts
|
|
155
|
+
/**
|
|
156
|
+
* Factory function to create a ClientApi instance.
|
|
157
|
+
*
|
|
158
|
+
* @public
|
|
159
|
+
* @param _config - Configuration object for the client API (currently unused).
|
|
160
|
+
* @returns {ClientApi} An instance of the ClientApi interface.
|
|
161
|
+
*/
|
|
162
|
+
function createClientApi({ emitter, id, forwardedKeys = [], logger }) {
|
|
163
|
+
const messenger = new Messenger({
|
|
164
|
+
source: "client",
|
|
165
|
+
id,
|
|
166
|
+
emitter,
|
|
167
|
+
logger
|
|
168
|
+
});
|
|
169
|
+
const subscriptions = [];
|
|
170
|
+
let isConnected = false;
|
|
171
|
+
let connectionTimeoutId = null;
|
|
172
|
+
let hostConfig = null;
|
|
173
|
+
const clearConnectionTimeout = () => {
|
|
174
|
+
if (connectionTimeoutId) {
|
|
175
|
+
clearTimeout(connectionTimeoutId);
|
|
176
|
+
connectionTimeoutId = null;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
const disconnect = ({ isReconnecting = false } = {}) => {
|
|
180
|
+
clearConnectionTimeout();
|
|
181
|
+
isConnected = false;
|
|
182
|
+
subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
183
|
+
messenger.disconnect();
|
|
184
|
+
messenger.emit("ClientDisconnected", {
|
|
185
|
+
clientId: id,
|
|
186
|
+
reconnect: isReconnecting
|
|
187
|
+
});
|
|
188
|
+
};
|
|
189
|
+
const connect = ({ interval = 1e3, timeout = 6e4, prepareClient = () => Promise.resolve(), onHostConnected, onHostDisconnected, onError, usid } = {}) => {
|
|
190
|
+
if (isConnected) disconnect({ isReconnecting: true });
|
|
191
|
+
const expirationTime = Date.now() + timeout;
|
|
192
|
+
const { markIsReady, emptyQueue } = messenger.connect();
|
|
193
|
+
subscriptions.push(messenger.on("ClientAcknowledged", async (event) => {
|
|
194
|
+
if (event.meta.hostId === messenger.getRemoteId()) return;
|
|
195
|
+
hostConfig = event;
|
|
196
|
+
messenger.setRemoteId(event.meta.hostId);
|
|
197
|
+
clearConnectionTimeout();
|
|
198
|
+
try {
|
|
199
|
+
await prepareClient();
|
|
200
|
+
markIsReady();
|
|
201
|
+
messenger.emit("ClientReady", { clientId: id });
|
|
202
|
+
onHostConnected?.(hostConfig);
|
|
203
|
+
emptyQueue();
|
|
204
|
+
} catch (error) {
|
|
205
|
+
onError?.(error);
|
|
206
|
+
}
|
|
207
|
+
}), messenger.on("ClientConfigurationChanged", (event) => {
|
|
208
|
+
hostConfig = event;
|
|
209
|
+
onHostConnected?.(hostConfig);
|
|
210
|
+
}), messenger.on("HostDisconnected", () => {
|
|
211
|
+
disconnect();
|
|
212
|
+
onHostDisconnected?.(() => connect({
|
|
213
|
+
interval,
|
|
214
|
+
timeout,
|
|
215
|
+
prepareClient,
|
|
216
|
+
onHostConnected,
|
|
217
|
+
onHostDisconnected,
|
|
218
|
+
onError,
|
|
219
|
+
usid
|
|
220
|
+
}));
|
|
221
|
+
}));
|
|
222
|
+
const checkInitialization = () => {
|
|
223
|
+
if (Date.now() > expirationTime) throw new Error(`Timed out after waiting ${timeout}ms for host connection`);
|
|
224
|
+
messenger.emit("ClientInitialized", {
|
|
225
|
+
clientId: id,
|
|
226
|
+
forwardedKeys,
|
|
227
|
+
usid
|
|
228
|
+
}, { requireRemoteId: false });
|
|
229
|
+
connectionTimeoutId = setTimeout(() => checkInitialization(), interval);
|
|
230
|
+
};
|
|
231
|
+
isConnected = true;
|
|
232
|
+
checkInitialization();
|
|
233
|
+
};
|
|
234
|
+
return {
|
|
235
|
+
addComponentToRegion: messenger.toEmitter("ComponentAddedToRegion"),
|
|
236
|
+
moveComponentToRegion: messenger.toEmitter("ComponentMovedToRegion"),
|
|
237
|
+
startComponentDrag: messenger.toEmitter("ComponentDragStarted"),
|
|
238
|
+
hoverInToComponent: messenger.toEmitter("ComponentHoveredIn"),
|
|
239
|
+
hoverOutOfComponent: messenger.toEmitter("ComponentHoveredOut"),
|
|
240
|
+
selectComponent: messenger.toEmitter("ComponentSelected"),
|
|
241
|
+
deselectComponent: messenger.toEmitter("ComponentDeselected"),
|
|
242
|
+
deleteComponent: messenger.toEmitter("ComponentDeleted"),
|
|
243
|
+
notifyWindowScrollChanged: messenger.toEmitter("WindowScrollChanged"),
|
|
244
|
+
notifyClientReady: messenger.toEmitter("ClientReady"),
|
|
245
|
+
notifyError: messenger.toEmitter("Error"),
|
|
246
|
+
notifyClientPageChanged: messenger.toEmitter("ClientPageChanged"),
|
|
247
|
+
connect,
|
|
248
|
+
on: (eventName, handler) => messenger.on(eventName, (event) => {
|
|
249
|
+
if (eventName === "ClientAcknowledged" || messenger.isReady()) handler(event);
|
|
250
|
+
}),
|
|
251
|
+
disconnect,
|
|
252
|
+
getRemoteId: () => messenger.getRemoteId()
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/design/messaging-api/host.ts
|
|
258
|
+
const defaultConfigFactory = () => Promise.resolve({
|
|
259
|
+
components: {},
|
|
260
|
+
componentTypes: {},
|
|
261
|
+
labels: {}
|
|
262
|
+
});
|
|
263
|
+
/**
|
|
264
|
+
* Factory function to create a HostApi instance.
|
|
265
|
+
*
|
|
266
|
+
* @public
|
|
267
|
+
* @param {HostConfiguration} config - Configuration object for the host API.
|
|
268
|
+
* @returns {HostApi} An instance of the HostApi interface.
|
|
269
|
+
*/
|
|
270
|
+
function createHostApi({ emitter, id, logger }) {
|
|
271
|
+
const messenger = new Messenger({
|
|
272
|
+
source: "host",
|
|
273
|
+
id,
|
|
274
|
+
emitter,
|
|
275
|
+
logger
|
|
276
|
+
});
|
|
277
|
+
const subscriptions = [];
|
|
278
|
+
let isConnected = false;
|
|
279
|
+
const disconnect = () => {
|
|
280
|
+
isConnected = false;
|
|
281
|
+
messenger.disconnect();
|
|
282
|
+
subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
283
|
+
messenger.emit("HostDisconnected", {});
|
|
284
|
+
};
|
|
285
|
+
return {
|
|
286
|
+
addComponentToRegion: messenger.toEmitter("ComponentAddedToRegion"),
|
|
287
|
+
moveComponentToRegion: messenger.toEmitter("ComponentMovedToRegion"),
|
|
288
|
+
startComponentDrag: messenger.toEmitter("ComponentDragStarted"),
|
|
289
|
+
hoverInToComponent: messenger.toEmitter("ComponentHoveredIn"),
|
|
290
|
+
hoverOutOfComponent: messenger.toEmitter("ComponentHoveredOut"),
|
|
291
|
+
selectComponent: messenger.toEmitter("ComponentSelected"),
|
|
292
|
+
deselectComponent: messenger.toEmitter("ComponentDeselected"),
|
|
293
|
+
deleteComponent: messenger.toEmitter("ComponentDeleted"),
|
|
294
|
+
forwardKeyPress: messenger.toEmitter("HostKeyPressed"),
|
|
295
|
+
notifyClientWindowDragDropped: messenger.toEmitter("ClientWindowDragDropped"),
|
|
296
|
+
notifyClientWindowDragEntered: messenger.toEmitter("ClientWindowDragEntered"),
|
|
297
|
+
notifyClientWindowDragMoved: messenger.toEmitter("ClientWindowDragMoved"),
|
|
298
|
+
notifyClientWindowDragExited: messenger.toEmitter("ClientWindowDragExited"),
|
|
299
|
+
setComponentProperties: messenger.toEmitter("ComponentPropertiesChanged"),
|
|
300
|
+
notifyWindowScrollChanged: messenger.toEmitter("WindowScrollChanged"),
|
|
301
|
+
notifyPageSettingsChanged: messenger.toEmitter("PageSettingsChanged"),
|
|
302
|
+
notifyMediaChanged: () => messenger.emit("MediaChangedEvent", {}),
|
|
303
|
+
notifyError: messenger.toEmitter("Error"),
|
|
304
|
+
focusComponent: messenger.toEmitter("ComponentFocused"),
|
|
305
|
+
setClientConfiguration: messenger.toEmitter("ClientConfigurationChanged"),
|
|
306
|
+
connect: ({ configFactory = defaultConfigFactory, onClientConnected, onClientDisconnected, onError }) => {
|
|
307
|
+
if (isConnected) disconnect();
|
|
308
|
+
const { markIsReady, emptyQueue } = messenger.connect();
|
|
309
|
+
subscriptions.push(messenger.on("ClientDisconnected", (event) => {
|
|
310
|
+
if (event.meta.clientId === messenger.getRemoteId()) messenger.setRemoteId(void 0);
|
|
311
|
+
onClientDisconnected?.(event.meta.clientId ?? "");
|
|
312
|
+
}));
|
|
313
|
+
subscriptions.push(messenger.on("ClientInitialized", async (event) => {
|
|
314
|
+
const remoteId = messenger.getRemoteId();
|
|
315
|
+
if (remoteId && event.meta.clientId === remoteId || !remoteId) {
|
|
316
|
+
messenger.setRemoteId(event.meta.clientId);
|
|
317
|
+
try {
|
|
318
|
+
const config = await configFactory();
|
|
319
|
+
messenger.emit("ClientAcknowledged", config, { requireRemoteId: false });
|
|
320
|
+
const { clientId } = await messenger.toPromise("ClientReady");
|
|
321
|
+
if (clientId !== messenger.getRemoteId()) throw new Error("Client id mismatch");
|
|
322
|
+
markIsReady();
|
|
323
|
+
onClientConnected?.(clientId, event);
|
|
324
|
+
emptyQueue();
|
|
325
|
+
} catch (error) {
|
|
326
|
+
onError?.(error);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}));
|
|
330
|
+
isConnected = true;
|
|
331
|
+
},
|
|
332
|
+
on: (event, handler) => messenger.on(event, handler),
|
|
333
|
+
disconnect,
|
|
334
|
+
getRemoteId: () => messenger.getRemoteId()
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
//#endregion
|
|
339
|
+
export { createClientApi as n, createHostApi as t };
|
|
340
|
+
//# sourceMappingURL=messaging-api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messaging-api.js","names":["subscriptions: (() => void)[]","connectionTimeoutId: number | null","hostConfig: HostToClientConfiguration | null","defaultConfigFactory: ConfigFactory","subscriptions: (() => void)[]"],"sources":["../src/design/messaging-api/messenger.ts","../src/design/messaging-api/client.ts","../src/design/messaging-api/host.ts"],"sourcesContent":["/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { EventHandler, MessageEmitter, Source } from './api-types';\n\nexport type Logger = (message: unknown, source: 'host' | 'client') => void;\n\n/**\n * Handles the basic logic for event emitting and receiving between a client and a host.\n *\n * The `Messenger` class manages a single connection to a source event emitter,\n * allowing for the sending and receiving of typed events between two parties (e.g., client and host).\n * It distinguishes events based on their source, ensuring that only events from the opposite source are processed.\n *\n * @template TInMapping - The mapping of incoming event names to their payload types.\n * @template TOutMapping - The mapping of outgoing event names to their payload types.\n */\nexport class Messenger<TInMapping, TOutMapping> {\n private readonly source: Source;\n\n private readonly id: string;\n\n private readonly emitter: MessageEmitter<TInMapping, TOutMapping>;\n\n private readonly handlers = new Map<keyof TInMapping, EventHandler<TInMapping>[]>();\n\n private remoteId?: string;\n\n private readonly logger: Logger;\n\n private _isReady = false;\n\n private unsubscribe?: () => void;\n private queue: { eventType: keyof TOutMapping; data: Omit<TOutMapping[keyof TOutMapping], 'eventType'> }[] = [];\n\n constructor({\n source,\n id,\n emitter,\n logger = () => {\n // Noop\n },\n }: {\n source: Source;\n id: string;\n emitter: MessageEmitter<TInMapping, TOutMapping>;\n logger?: Logger;\n }) {\n this.source = source;\n this.id = id;\n this.emitter = emitter;\n this.logger = logger;\n }\n\n /**\n * Connects the given emitter. This ensures only a single connection to the provided emitter.\n *\n * This method registers a listener for events from the opposite source.\n * It ensures that only events from the opposite source are processed.\n */\n connect(): { markIsReady: () => void; emptyQueue: () => void } {\n // Unsubscribe if this is called again.\n this.unsubscribe?.();\n this._isReady = false;\n\n this.unsubscribe = this.emitter.addEventListener((event) => {\n if (event.meta?.pdMessagingApi && event.meta.source !== this.source) {\n this.logger(event, this.source === 'host' ? 'client' : 'host');\n\n [event.eventType, 'Event'].forEach((eventType) => {\n this.handlers\n .get(eventType as keyof TInMapping)\n ?.forEach((handler) => handler(event as Parameters<EventHandler<TInMapping>>[0]));\n });\n }\n });\n\n return {\n markIsReady: () => {\n this._isReady = true;\n },\n emptyQueue: () => {\n this.queue.forEach(({ eventType, data }) => this.emit(eventType, data));\n this.queue = [];\n },\n };\n }\n\n /**\n * Returns the id of the connected remote.\n */\n getRemoteId(): string | undefined {\n return this.remoteId;\n }\n\n /**\n * Sets the id of the connected remote.\n */\n setRemoteId(remoteId: string | undefined): void {\n this.remoteId = remoteId;\n }\n\n /**\n * Emits an event to the connected remote.\n * This attaches metadata to each event that is emitted.\n *\n * @param eventName - The event to emit.\n * @param data - The data to emit.\n * @param options - The options for the event.\n * @param options.requireRemoteId - Whether to require a remote id to be set before emitting the event.\n */\n emit<TEvent extends keyof TOutMapping>(\n eventType: TEvent,\n data: Omit<TOutMapping[TEvent], 'eventType'>,\n { requireRemoteId = true }: { requireRemoteId?: boolean } = {}\n ): void {\n if (requireRemoteId && !this._isReady) {\n this.queue.push({ eventType, data });\n\n return;\n }\n\n const event = {\n ...data,\n eventType,\n meta: {\n hostId: this.source === 'host' ? this.id : this.remoteId,\n clientId: this.source === 'client' ? this.id : this.remoteId,\n source: this.source,\n pdMessagingApi: true as const,\n },\n };\n\n this.logger(event, this.source);\n\n this.emitter.postMessage(event);\n }\n\n /**\n * Subscribes to an event from the connected remote.\n *\n * @param event - The event to subscribe to.\n * @param handler - The handler to call when the event is emitted.\n * @returns A function to unsubscribe from the event.\n */\n on<TEvent extends keyof TInMapping>(event: TEvent, handler: EventHandler<TInMapping, TEvent>): () => void {\n const handlers = this.handlers.get(event) ?? [];\n\n handlers.push(handler as EventHandler<TInMapping>);\n this.handlers.set(event, handlers);\n\n return () => {\n const eventHandlers = this.handlers.get(event) ?? [];\n const index = eventHandlers.indexOf(handler as EventHandler<TInMapping>);\n\n if (index > -1) {\n eventHandlers.splice(index, 1);\n }\n\n if (eventHandlers.length === 0) {\n this.handlers.delete(event);\n }\n };\n }\n\n /**\n * Returns a function that emits an event to the connected remote.\n *\n * @param eventName - The event to emit.\n * @returns A function that emits an event to the connected remote.\n */\n toEmitter<TEvent extends keyof TOutMapping>(\n eventName: TEvent\n ): (event: Omit<TOutMapping[TEvent], 'eventType'>) => void {\n return (event: Omit<TOutMapping[TEvent], 'eventType'>) => {\n this.emit(eventName, event);\n };\n }\n\n toPromise<TEvent extends keyof TInMapping>(eventName: TEvent): Promise<TInMapping[TEvent]> {\n return new Promise<TInMapping[TEvent]>((resolve) => {\n const unsub = this.on(eventName, (event) => {\n unsub();\n resolve(event as unknown as TInMapping[TEvent]);\n });\n });\n }\n\n /**\n * Disconnects the messenger.\n */\n disconnect(): void {\n this.unsubscribe?.();\n this.handlers.clear();\n this.remoteId = undefined;\n this.unsubscribe = undefined;\n }\n\n /**\n * Returns whether the messenger is ready to emit events.\n *\n * @returns Whether the messenger is ready.\n */\n isReady(): boolean {\n return this._isReady;\n }\n}\n","/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type {\n ClientApi,\n ClientConfiguration,\n ClientEventNameMapping,\n HostEventNameMapping,\n WithMeta,\n} from './api-types';\nimport type { HostToClientConfiguration } from './domain-types';\nimport { Messenger } from './messenger';\n\n/**\n * Factory function to create a ClientApi instance.\n *\n * @public\n * @param _config - Configuration object for the client API (currently unused).\n * @returns {ClientApi} An instance of the ClientApi interface.\n */\nexport function createClientApi({ emitter, id, forwardedKeys = [], logger }: ClientConfiguration): ClientApi {\n const messenger = new Messenger<ClientEventNameMapping, HostEventNameMapping>({\n source: 'client',\n id,\n emitter,\n logger,\n });\n const subscriptions: (() => void)[] = [];\n\n let isConnected = false;\n let connectionTimeoutId: number | null = null;\n let hostConfig: HostToClientConfiguration | null = null;\n\n const clearConnectionTimeout = () => {\n if (connectionTimeoutId) {\n clearTimeout(connectionTimeoutId);\n connectionTimeoutId = null;\n }\n };\n\n const disconnect = ({ isReconnecting = false }: { isReconnecting?: boolean } = {}) => {\n clearConnectionTimeout();\n isConnected = false;\n subscriptions.forEach((unsubscribe) => unsubscribe());\n messenger.disconnect();\n messenger.emit('ClientDisconnected', { clientId: id, reconnect: isReconnecting });\n };\n\n const connect = ({\n interval = 1_000,\n timeout = 60_000,\n prepareClient = () => Promise.resolve(),\n onHostConnected,\n onHostDisconnected,\n onError,\n usid,\n }: {\n interval?: number;\n timeout?: number;\n prepareClient?: () => Promise<void>;\n onHostConnected?: (configuration: HostToClientConfiguration) => void;\n onHostDisconnected?: (reconnect: () => void) => void;\n onError?: (error: Error) => void;\n usid?: string;\n } = {}) => {\n if (isConnected) {\n disconnect({ isReconnecting: true });\n }\n\n const expirationTime = Date.now() + timeout;\n const { markIsReady, emptyQueue } = messenger.connect();\n\n subscriptions.push(\n messenger.on('ClientAcknowledged', async (event) => {\n if (event.meta.hostId === messenger.getRemoteId()) {\n // We've already been acknowledged by the host in this case.\n return;\n }\n\n hostConfig = event;\n messenger.setRemoteId(event.meta.hostId);\n clearConnectionTimeout();\n\n try {\n await prepareClient();\n\n markIsReady();\n messenger.emit('ClientReady', { clientId: id });\n onHostConnected?.(hostConfig);\n emptyQueue();\n } catch (error) {\n onError?.(error as Error);\n }\n }),\n messenger.on('ClientConfigurationChanged', (event) => {\n hostConfig = event;\n onHostConnected?.(hostConfig);\n }),\n messenger.on('HostDisconnected', () => {\n disconnect();\n onHostDisconnected?.(() =>\n connect({\n interval,\n timeout,\n prepareClient,\n onHostConnected,\n onHostDisconnected,\n onError,\n usid,\n })\n );\n })\n );\n\n const checkInitialization = () => {\n if (Date.now() > expirationTime) {\n throw new Error(`Timed out after waiting ${timeout}ms for host connection`);\n }\n\n messenger.emit('ClientInitialized', { clientId: id, forwardedKeys, usid }, { requireRemoteId: false });\n connectionTimeoutId = setTimeout(() => checkInitialization(), interval) as unknown as number;\n };\n\n isConnected = true;\n checkInitialization();\n };\n\n return {\n addComponentToRegion: messenger.toEmitter('ComponentAddedToRegion'),\n moveComponentToRegion: messenger.toEmitter('ComponentMovedToRegion'),\n startComponentDrag: messenger.toEmitter('ComponentDragStarted'),\n hoverInToComponent: messenger.toEmitter('ComponentHoveredIn'),\n hoverOutOfComponent: messenger.toEmitter('ComponentHoveredOut'),\n selectComponent: messenger.toEmitter('ComponentSelected'),\n deselectComponent: messenger.toEmitter('ComponentDeselected'),\n deleteComponent: messenger.toEmitter('ComponentDeleted'),\n notifyWindowScrollChanged: messenger.toEmitter('WindowScrollChanged'),\n notifyClientReady: messenger.toEmitter('ClientReady'),\n notifyError: messenger.toEmitter('Error'),\n notifyClientPageChanged: messenger.toEmitter('ClientPageChanged'),\n connect,\n on: <TEvent extends keyof ClientEventNameMapping>(\n eventName: TEvent,\n handler: (handlerEvent: Readonly<WithMeta & ClientEventNameMapping[TEvent]>) => void\n ) =>\n messenger.on(eventName, (event) => {\n // Don't receive any events besides the acknowledged event until the client is ready\n if (eventName === 'ClientAcknowledged' || messenger.isReady()) {\n handler(event);\n }\n }),\n disconnect,\n getRemoteId: () => messenger.getRemoteId(),\n };\n}\n","/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type {\n HostApi,\n HostConfiguration,\n ClientEventNameMapping,\n HostEventNameMapping,\n WithMeta,\n ConfigFactory,\n} from './api-types';\nimport type { ClientInitializedEvent } from './domain-types';\nimport { Messenger } from './messenger';\n\nconst defaultConfigFactory: ConfigFactory = () => Promise.resolve({ components: {}, componentTypes: {}, labels: {} });\n/**\n * Factory function to create a HostApi instance.\n *\n * @public\n * @param {HostConfiguration} config - Configuration object for the host API.\n * @returns {HostApi} An instance of the HostApi interface.\n */\nexport function createHostApi({ emitter, id, logger }: HostConfiguration): HostApi {\n const messenger = new Messenger<HostEventNameMapping, ClientEventNameMapping>({\n source: 'host',\n id,\n emitter,\n logger,\n });\n const subscriptions: (() => void)[] = [];\n let isConnected = false;\n const disconnect = () => {\n isConnected = false;\n messenger.disconnect();\n subscriptions.forEach((unsubscribe) => unsubscribe());\n messenger.emit('HostDisconnected', {});\n };\n\n return {\n addComponentToRegion: messenger.toEmitter('ComponentAddedToRegion'),\n moveComponentToRegion: messenger.toEmitter('ComponentMovedToRegion'),\n startComponentDrag: messenger.toEmitter('ComponentDragStarted'),\n hoverInToComponent: messenger.toEmitter('ComponentHoveredIn'),\n hoverOutOfComponent: messenger.toEmitter('ComponentHoveredOut'),\n selectComponent: messenger.toEmitter('ComponentSelected'),\n deselectComponent: messenger.toEmitter('ComponentDeselected'),\n deleteComponent: messenger.toEmitter('ComponentDeleted'),\n forwardKeyPress: messenger.toEmitter('HostKeyPressed'),\n notifyClientWindowDragDropped: messenger.toEmitter('ClientWindowDragDropped'),\n notifyClientWindowDragEntered: messenger.toEmitter('ClientWindowDragEntered'),\n notifyClientWindowDragMoved: messenger.toEmitter('ClientWindowDragMoved'),\n notifyClientWindowDragExited: messenger.toEmitter('ClientWindowDragExited'),\n setComponentProperties: messenger.toEmitter('ComponentPropertiesChanged'),\n notifyWindowScrollChanged: messenger.toEmitter('WindowScrollChanged'),\n notifyPageSettingsChanged: messenger.toEmitter('PageSettingsChanged'),\n notifyMediaChanged: () => messenger.emit('MediaChangedEvent', {}),\n notifyError: messenger.toEmitter('Error'),\n focusComponent: messenger.toEmitter('ComponentFocused'),\n setClientConfiguration: messenger.toEmitter('ClientConfigurationChanged'),\n connect: ({\n configFactory = defaultConfigFactory,\n onClientConnected,\n onClientDisconnected,\n onError,\n }: {\n configFactory: ConfigFactory;\n onClientConnected?: (clientId: string, config: ClientInitializedEvent) => void;\n onClientDisconnected?: (clientId: string) => void;\n onError?: (error: Error) => void;\n }) => {\n if (isConnected) {\n disconnect();\n }\n\n const { markIsReady, emptyQueue } = messenger.connect();\n\n subscriptions.push(\n messenger.on('ClientDisconnected', (event) => {\n if (event.meta.clientId === messenger.getRemoteId()) {\n messenger.setRemoteId(undefined);\n }\n\n onClientDisconnected?.(event.meta.clientId ?? '');\n })\n );\n\n subscriptions.push(\n messenger.on('ClientInitialized', async (event) => {\n const remoteId = messenger.getRemoteId();\n\n // If the same client tries reconnecting, we should allow it.\n // If there is no remote id, we should allow any client to connect.\n if ((remoteId && event.meta.clientId === remoteId) || !remoteId) {\n messenger.setRemoteId(event.meta.clientId);\n\n try {\n const config = await configFactory();\n\n messenger.emit('ClientAcknowledged', config, { requireRemoteId: false });\n\n const { clientId } = await messenger.toPromise('ClientReady');\n\n if (clientId !== messenger.getRemoteId()) {\n throw new Error('Client id mismatch');\n }\n\n markIsReady();\n onClientConnected?.(clientId, event);\n emptyQueue();\n } catch (error) {\n onError?.(error as Error);\n }\n }\n })\n );\n\n isConnected = true;\n },\n on: <TEvent extends keyof HostEventNameMapping>(\n event: TEvent,\n handler: (handlerEvent: Readonly<WithMeta & HostEventNameMapping[TEvent]>) => void\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) => messenger.on(event as any, handler as any),\n disconnect,\n getRemoteId: () => messenger.getRemoteId(),\n };\n}\n"],"mappings":";;;;;;;;;;;AA6BA,IAAa,YAAb,MAAgD;CAC5C,AAAiB;CAEjB,AAAiB;CAEjB,AAAiB;CAEjB,AAAiB,2BAAW,IAAI,KAAmD;CAEnF,AAAQ;CAER,AAAiB;CAEjB,AAAQ,WAAW;CAEnB,AAAQ;CACR,AAAQ,QAAqG,EAAE;CAE/G,YAAY,EACR,QACA,IACA,SACA,eAAe,MAQhB;AACC,OAAK,SAAS;AACd,OAAK,KAAK;AACV,OAAK,UAAU;AACf,OAAK,SAAS;;;;;;;;CASlB,UAA+D;AAE3D,OAAK,eAAe;AACpB,OAAK,WAAW;AAEhB,OAAK,cAAc,KAAK,QAAQ,kBAAkB,UAAU;AACxD,OAAI,MAAM,MAAM,kBAAkB,MAAM,KAAK,WAAW,KAAK,QAAQ;AACjE,SAAK,OAAO,OAAO,KAAK,WAAW,SAAS,WAAW,OAAO;AAE9D,KAAC,MAAM,WAAW,QAAQ,CAAC,SAAS,cAAc;AAC9C,UAAK,SACA,IAAI,UAA8B,EACjC,SAAS,YAAY,QAAQ,MAAiD,CAAC;MACvF;;IAER;AAEF,SAAO;GACH,mBAAmB;AACf,SAAK,WAAW;;GAEpB,kBAAkB;AACd,SAAK,MAAM,SAAS,EAAE,WAAW,WAAW,KAAK,KAAK,WAAW,KAAK,CAAC;AACvE,SAAK,QAAQ,EAAE;;GAEtB;;;;;CAML,cAAkC;AAC9B,SAAO,KAAK;;;;;CAMhB,YAAY,UAAoC;AAC5C,OAAK,WAAW;;;;;;;;;;;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,OAAO,CAAC;MAExE,MAAM,EAAE,aAAa,MAAM,UAAU,UAAU,cAAc;AAE7D,UAAI,aAAa,UAAU,aAAa,CACpC,OAAM,IAAI,MAAM,qBAAqB;AAGzC,mBAAa;AACb,0BAAoB,UAAU,MAAM;AACpC,kBAAY;cACP,OAAO;AACZ,gBAAU,MAAe;;;KAGnC,CACL;AAED,iBAAc;;EAElB,KACI,OACA,YAEC,UAAU,GAAG,OAAc,QAAe;EAC/C;EACA,mBAAmB,UAAU,aAAa;EAC7C"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
//#region src/design/modeDetection.ts
|
|
2
|
+
/**
|
|
3
|
+
* Copyright 2026 Salesforce, Inc.
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Utility functions for detecting active design/preview modes
|
|
19
|
+
*/
|
|
20
|
+
/**
|
|
21
|
+
* Get the mode parameter from URL search params
|
|
22
|
+
* @param url - Optional URL string or Request object for server-side usage. If not provided, uses window.location on client-side
|
|
23
|
+
* @returns The mode parameter value or null if not found
|
|
24
|
+
*/
|
|
25
|
+
const getUrlMode = (url) => {
|
|
26
|
+
let searchParams;
|
|
27
|
+
if (url) if (url instanceof Request) searchParams = new URL(url.url).searchParams;
|
|
28
|
+
else searchParams = new URL(url).searchParams;
|
|
29
|
+
else {
|
|
30
|
+
if (typeof window === "undefined") return null;
|
|
31
|
+
searchParams = new URLSearchParams(window.location.search);
|
|
32
|
+
}
|
|
33
|
+
return searchParams.get("mode");
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Check if design mode is active
|
|
37
|
+
* @param url - Optional URL string or Request object for server-side usage
|
|
38
|
+
* @returns True if mode=EDIT is present in URL
|
|
39
|
+
*/
|
|
40
|
+
const isDesignModeActive = (url) => getUrlMode(url) === "EDIT";
|
|
41
|
+
/**
|
|
42
|
+
* Check if preview mode is active
|
|
43
|
+
* @param url - Optional URL string or Request object for server-side usage
|
|
44
|
+
* @returns True if mode=PREVIEW is present in URL
|
|
45
|
+
*/
|
|
46
|
+
const isPreviewModeActive = (url) => getUrlMode(url) === "PREVIEW";
|
|
47
|
+
|
|
48
|
+
//#endregion
|
|
49
|
+
export { isDesignModeActive as n, isPreviewModeActive as r, getUrlMode as t };
|
|
50
|
+
//# sourceMappingURL=modeDetection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modeDetection.js","names":["searchParams: URLSearchParams"],"sources":["../src/design/modeDetection.ts"],"sourcesContent":["/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Utility functions for detecting active design/preview modes\n */\n\n/**\n * Get the mode parameter from URL search params\n * @param url - Optional URL string or Request object for server-side usage. If not provided, uses window.location on client-side\n * @returns The mode parameter value or null if not found\n */\nexport const getUrlMode = (url?: string | URL | Request): string | null => {\n let searchParams: URLSearchParams;\n\n if (url) {\n // Server-side: extract search params from provided URL or Request\n if (url instanceof Request) {\n searchParams = new URL(url.url).searchParams;\n } else {\n searchParams = new URL(url).searchParams;\n }\n } else {\n // Client-side: use window.location\n if (typeof window === 'undefined') {\n return null;\n }\n searchParams = new URLSearchParams(window.location.search);\n }\n\n return searchParams.get('mode');\n};\n\n/**\n * Check if design mode is active\n * @param url - Optional URL string or Request object for server-side usage\n * @returns True if mode=EDIT is present in URL\n */\nexport const isDesignModeActive = (url?: string | URL | Request): boolean => getUrlMode(url) === 'EDIT';\n\n/**\n * Check if preview mode is active\n * @param url - Optional URL string or Request object for server-side usage\n * @returns True if mode=PREVIEW is present in URL\n */\nexport const isPreviewModeActive = (url?: string | URL | Request): boolean => getUrlMode(url) === 'PREVIEW';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,cAAc,QAAgD;CACvE,IAAIA;AAEJ,KAAI,IAEA,KAAI,eAAe,QACf,gBAAe,IAAI,IAAI,IAAI,IAAI,CAAC;KAEhC,gBAAe,IAAI,IAAI,IAAI,CAAC;MAE7B;AAEH,MAAI,OAAO,WAAW,YAClB,QAAO;AAEX,iBAAe,IAAI,gBAAgB,OAAO,SAAS,OAAO;;AAG9D,QAAO,aAAa,IAAI,OAAO;;;;;;;AAQnC,MAAa,sBAAsB,QAA0C,WAAW,IAAI,KAAK;;;;;;AAOjG,MAAa,uBAAuB,QAA0C,WAAW,IAAI,KAAK"}
|