@sanity/sdk-react 0.0.0-alpha.25 → 0.0.0-alpha.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,256 @@
1
+ import { getDefaultExportFromCjs } from "./index.js";
2
+ import a from "url";
3
+ import require$$2 from "events";
4
+ import require$$2$1 from "https";
5
+ import require$$1$1 from "http";
6
+ import require$$1 from "util";
7
+ function _mergeNamespaces(n, m) {
8
+ return m.forEach(function(e) {
9
+ e && typeof e != "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
10
+ if (k !== "default" && !(k in n)) {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: !0,
14
+ get: function() {
15
+ return e[k];
16
+ }
17
+ });
18
+ }
19
+ });
20
+ }), Object.freeze(n);
21
+ }
22
+ var eventsource, hasRequiredEventsource;
23
+ function requireEventsource() {
24
+ if (hasRequiredEventsource) return eventsource;
25
+ hasRequiredEventsource = 1;
26
+ var parse = a.parse, events = require$$2, https = require$$2$1, http = require$$1$1, util = require$$1, httpsOptions = ["pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "secureProtocol", "servername", "checkServerIdentity"], bom = [239, 187, 191], colon = 58, space = 32, lineFeed = 10, carriageReturn = 13, maxBufferAheadAllocation = 1024 * 256, reUnsafeHeader = /^(cookie|authorization)$/i;
27
+ function hasBom(buf) {
28
+ return bom.every(function(charCode, index) {
29
+ return buf[index] === charCode;
30
+ });
31
+ }
32
+ function EventSource(url, eventSourceInitDict) {
33
+ var readyState = EventSource.CONNECTING, headers = eventSourceInitDict && eventSourceInitDict.headers, hasNewOrigin = !1;
34
+ Object.defineProperty(this, "readyState", {
35
+ get: function() {
36
+ return readyState;
37
+ }
38
+ }), Object.defineProperty(this, "url", {
39
+ get: function() {
40
+ return url;
41
+ }
42
+ });
43
+ var self = this;
44
+ self.reconnectInterval = 1e3, self.connectionInProgress = !1;
45
+ function onConnectionClosed(message) {
46
+ readyState !== EventSource.CLOSED && (readyState = EventSource.CONNECTING, _emit("error", new Event("error", {
47
+ message
48
+ })), reconnectUrl && (url = reconnectUrl, reconnectUrl = null, hasNewOrigin = !1), setTimeout(function() {
49
+ readyState !== EventSource.CONNECTING || self.connectionInProgress || (self.connectionInProgress = !0, connect());
50
+ }, self.reconnectInterval));
51
+ }
52
+ var req, lastEventId = "";
53
+ headers && headers["Last-Event-ID"] && (lastEventId = headers["Last-Event-ID"], delete headers["Last-Event-ID"]);
54
+ var discardTrailingNewline = !1, data = "", eventName = "", reconnectUrl = null;
55
+ function connect() {
56
+ var options = parse(url), isSecure = options.protocol === "https:";
57
+ if (options.headers = {
58
+ "Cache-Control": "no-cache",
59
+ Accept: "text/event-stream"
60
+ }, lastEventId && (options.headers["Last-Event-ID"] = lastEventId), headers) {
61
+ var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers;
62
+ for (var i in reqHeaders) {
63
+ var header = reqHeaders[i];
64
+ header && (options.headers[i] = header);
65
+ }
66
+ }
67
+ options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized), eventSourceInitDict && eventSourceInitDict.createConnection !== void 0 && (options.createConnection = eventSourceInitDict.createConnection);
68
+ var useProxy = eventSourceInitDict && eventSourceInitDict.proxy;
69
+ if (useProxy) {
70
+ var proxy = parse(eventSourceInitDict.proxy);
71
+ isSecure = proxy.protocol === "https:", options.protocol = isSecure ? "https:" : "http:", options.path = url, options.headers.Host = options.host, options.hostname = proxy.hostname, options.host = proxy.host, options.port = proxy.port;
72
+ }
73
+ if (eventSourceInitDict && eventSourceInitDict.https) {
74
+ for (var optName in eventSourceInitDict.https)
75
+ if (httpsOptions.indexOf(optName) !== -1) {
76
+ var option = eventSourceInitDict.https[optName];
77
+ option !== void 0 && (options[optName] = option);
78
+ }
79
+ }
80
+ eventSourceInitDict && eventSourceInitDict.withCredentials !== void 0 && (options.withCredentials = eventSourceInitDict.withCredentials), req = (isSecure ? https : http).request(options, function(res) {
81
+ if (self.connectionInProgress = !1, res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
82
+ _emit("error", new Event("error", {
83
+ status: res.statusCode,
84
+ message: res.statusMessage
85
+ })), onConnectionClosed();
86
+ return;
87
+ }
88
+ if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
89
+ var location = res.headers.location;
90
+ if (!location) {
91
+ _emit("error", new Event("error", {
92
+ status: res.statusCode,
93
+ message: res.statusMessage
94
+ }));
95
+ return;
96
+ }
97
+ var prevOrigin = new URL(url).origin, nextOrigin = new URL(location).origin;
98
+ hasNewOrigin = prevOrigin !== nextOrigin, res.statusCode === 307 && (reconnectUrl = url), url = location, process.nextTick(connect);
99
+ return;
100
+ }
101
+ if (res.statusCode !== 200)
102
+ return _emit("error", new Event("error", {
103
+ status: res.statusCode,
104
+ message: res.statusMessage
105
+ })), self.close();
106
+ readyState = EventSource.OPEN, res.on("close", function() {
107
+ res.removeAllListeners("close"), res.removeAllListeners("end"), onConnectionClosed();
108
+ }), res.on("end", function() {
109
+ res.removeAllListeners("close"), res.removeAllListeners("end"), onConnectionClosed();
110
+ }), _emit("open", new Event("open"));
111
+ var buf, newBuffer, startingPos = 0, startingFieldLength = -1, newBufferSize = 0, bytesUsed = 0;
112
+ res.on("data", function(chunk) {
113
+ buf ? (chunk.length > buf.length - bytesUsed && (newBufferSize = buf.length * 2 + chunk.length, newBufferSize > maxBufferAheadAllocation && (newBufferSize = buf.length + chunk.length + maxBufferAheadAllocation), newBuffer = Buffer.alloc(newBufferSize), buf.copy(newBuffer, 0, 0, bytesUsed), buf = newBuffer), chunk.copy(buf, bytesUsed), bytesUsed += chunk.length) : (buf = chunk, hasBom(buf) && (buf = buf.slice(bom.length)), bytesUsed = buf.length);
114
+ for (var pos = 0, length = bytesUsed; pos < length; ) {
115
+ discardTrailingNewline && (buf[pos] === lineFeed && ++pos, discardTrailingNewline = !1);
116
+ for (var lineLength = -1, fieldLength = startingFieldLength, c, i2 = startingPos; lineLength < 0 && i2 < length; ++i2)
117
+ c = buf[i2], c === colon ? fieldLength < 0 && (fieldLength = i2 - pos) : c === carriageReturn ? (discardTrailingNewline = !0, lineLength = i2 - pos) : c === lineFeed && (lineLength = i2 - pos);
118
+ if (lineLength < 0) {
119
+ startingPos = length - pos, startingFieldLength = fieldLength;
120
+ break;
121
+ } else
122
+ startingPos = 0, startingFieldLength = -1;
123
+ parseEventStreamLine(buf, pos, fieldLength, lineLength), pos += lineLength + 1;
124
+ }
125
+ pos === length ? (buf = void 0, bytesUsed = 0) : pos > 0 && (buf = buf.slice(pos, bytesUsed), bytesUsed = buf.length);
126
+ });
127
+ }), req.on("error", function(err) {
128
+ self.connectionInProgress = !1, onConnectionClosed(err.message);
129
+ }), req.setNoDelay && req.setNoDelay(!0), req.end();
130
+ }
131
+ connect();
132
+ function _emit() {
133
+ self.listeners(arguments[0]).length > 0 && self.emit.apply(self, arguments);
134
+ }
135
+ this._close = function() {
136
+ readyState !== EventSource.CLOSED && (readyState = EventSource.CLOSED, req.abort && req.abort(), req.xhr && req.xhr.abort && req.xhr.abort());
137
+ };
138
+ function parseEventStreamLine(buf, pos, fieldLength, lineLength) {
139
+ if (lineLength === 0) {
140
+ if (data.length > 0) {
141
+ var type = eventName || "message";
142
+ _emit(type, new MessageEvent(type, {
143
+ data: data.slice(0, -1),
144
+ // remove trailing newline
145
+ lastEventId,
146
+ origin: new URL(url).origin
147
+ })), data = "";
148
+ }
149
+ eventName = void 0;
150
+ } else if (fieldLength > 0) {
151
+ var noValue = fieldLength < 0, step = 0, field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString();
152
+ noValue ? step = lineLength : buf[pos + fieldLength + 1] !== space ? step = fieldLength + 1 : step = fieldLength + 2, pos += step;
153
+ var valueLength = lineLength - step, value = buf.slice(pos, pos + valueLength).toString();
154
+ if (field === "data")
155
+ data += value + `
156
+ `;
157
+ else if (field === "event")
158
+ eventName = value;
159
+ else if (field === "id")
160
+ lastEventId = value;
161
+ else if (field === "retry") {
162
+ var retry = parseInt(value, 10);
163
+ Number.isNaN(retry) || (self.reconnectInterval = retry);
164
+ }
165
+ }
166
+ }
167
+ }
168
+ eventsource = EventSource, util.inherits(EventSource, events.EventEmitter), EventSource.prototype.constructor = EventSource, ["open", "error", "message"].forEach(function(method) {
169
+ Object.defineProperty(EventSource.prototype, "on" + method, {
170
+ /**
171
+ * Returns the current listener
172
+ *
173
+ * @return {Mixed} the set function or undefined
174
+ * @api private
175
+ */
176
+ get: function() {
177
+ var listener = this.listeners(method)[0];
178
+ return listener ? listener._listener ? listener._listener : listener : void 0;
179
+ },
180
+ /**
181
+ * Start listening for events
182
+ *
183
+ * @param {Function} listener the listener
184
+ * @return {Mixed} the set function or undefined
185
+ * @api private
186
+ */
187
+ set: function(listener) {
188
+ this.removeAllListeners(method), this.addEventListener(method, listener);
189
+ }
190
+ });
191
+ }), Object.defineProperty(EventSource, "CONNECTING", {
192
+ enumerable: !0,
193
+ value: 0
194
+ }), Object.defineProperty(EventSource, "OPEN", {
195
+ enumerable: !0,
196
+ value: 1
197
+ }), Object.defineProperty(EventSource, "CLOSED", {
198
+ enumerable: !0,
199
+ value: 2
200
+ }), EventSource.prototype.CONNECTING = 0, EventSource.prototype.OPEN = 1, EventSource.prototype.CLOSED = 2, EventSource.prototype.close = function() {
201
+ this._close();
202
+ }, EventSource.prototype.addEventListener = function(type, listener) {
203
+ typeof listener == "function" && (listener._listener = listener, this.on(type, listener));
204
+ }, EventSource.prototype.dispatchEvent = function(event) {
205
+ if (!event.type)
206
+ throw new Error("UNSPECIFIED_EVENT_TYPE_ERR");
207
+ this.emit(event.type, event.detail);
208
+ }, EventSource.prototype.removeEventListener = function(type, listener) {
209
+ typeof listener == "function" && (listener._listener = void 0, this.removeListener(type, listener));
210
+ };
211
+ function Event(type, optionalProperties) {
212
+ if (Object.defineProperty(this, "type", {
213
+ writable: !1,
214
+ value: type,
215
+ enumerable: !0
216
+ }), optionalProperties)
217
+ for (var f in optionalProperties)
218
+ optionalProperties.hasOwnProperty(f) && Object.defineProperty(this, f, {
219
+ writable: !1,
220
+ value: optionalProperties[f],
221
+ enumerable: !0
222
+ });
223
+ }
224
+ function MessageEvent(type, eventInitDict) {
225
+ Object.defineProperty(this, "type", {
226
+ writable: !1,
227
+ value: type,
228
+ enumerable: !0
229
+ });
230
+ for (var f in eventInitDict)
231
+ eventInitDict.hasOwnProperty(f) && Object.defineProperty(this, f, {
232
+ writable: !1,
233
+ value: eventInitDict[f],
234
+ enumerable: !0
235
+ });
236
+ }
237
+ function removeUnsafeHeaders(headers) {
238
+ var safe = {};
239
+ for (var key in headers)
240
+ reUnsafeHeader.test(key) || (safe[key] = headers[key]);
241
+ return safe;
242
+ }
243
+ return eventsource;
244
+ }
245
+ var node$2, hasRequiredNode;
246
+ function requireNode() {
247
+ return hasRequiredNode || (hasRequiredNode = 1, node$2 = requireEventsource()), node$2;
248
+ }
249
+ var nodeExports = /* @__PURE__ */ requireNode(), node = /* @__PURE__ */ getDefaultExportFromCjs(nodeExports), node$1 = /* @__PURE__ */ _mergeNamespaces({
250
+ __proto__: null,
251
+ default: node
252
+ }, [nodeExports]);
253
+ export {
254
+ node$1 as node
255
+ };
256
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sources":["../../../../node_modules/.pnpm/eventsource@2.0.2/node_modules/eventsource/lib/eventsource.js","../../../../node_modules/.pnpm/@sanity+eventsource@5.0.2/node_modules/@sanity/eventsource/node.js"],"sourcesContent":["var parse = require('url').parse\nvar events = require('events')\nvar https = require('https')\nvar http = require('http')\nvar util = require('util')\n\nvar httpsOptions = [\n 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers',\n 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity'\n]\n\nvar bom = [239, 187, 191]\nvar colon = 58\nvar space = 32\nvar lineFeed = 10\nvar carriageReturn = 13\n// Beyond 256KB we could not observe any gain in performance\nvar maxBufferAheadAllocation = 1024 * 256\n// Headers matching the pattern should be removed when redirecting to different origin\nvar reUnsafeHeader = /^(cookie|authorization)$/i\n\nfunction hasBom (buf) {\n return bom.every(function (charCode, index) {\n return buf[index] === charCode\n })\n}\n\n/**\n * Creates a new EventSource object\n *\n * @param {String} url the URL to which to connect\n * @param {Object} [eventSourceInitDict] extra init params. See README for details.\n * @api public\n **/\nfunction EventSource (url, eventSourceInitDict) {\n var readyState = EventSource.CONNECTING\n var headers = eventSourceInitDict && eventSourceInitDict.headers\n var hasNewOrigin = false\n Object.defineProperty(this, 'readyState', {\n get: function () {\n return readyState\n }\n })\n\n Object.defineProperty(this, 'url', {\n get: function () {\n return url\n }\n })\n\n var self = this\n self.reconnectInterval = 1000\n self.connectionInProgress = false\n\n function onConnectionClosed (message) {\n if (readyState === EventSource.CLOSED) return\n readyState = EventSource.CONNECTING\n _emit('error', new Event('error', {message: message}))\n\n // The url may have been changed by a temporary redirect. If that's the case,\n // revert it now, and flag that we are no longer pointing to a new origin\n if (reconnectUrl) {\n url = reconnectUrl\n reconnectUrl = null\n hasNewOrigin = false\n }\n setTimeout(function () {\n if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {\n return\n }\n self.connectionInProgress = true\n connect()\n }, self.reconnectInterval)\n }\n\n var req\n var lastEventId = ''\n if (headers && headers['Last-Event-ID']) {\n lastEventId = headers['Last-Event-ID']\n delete headers['Last-Event-ID']\n }\n\n var discardTrailingNewline = false\n var data = ''\n var eventName = ''\n\n var reconnectUrl = null\n\n function connect () {\n var options = parse(url)\n var isSecure = options.protocol === 'https:'\n options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' }\n if (lastEventId) options.headers['Last-Event-ID'] = lastEventId\n if (headers) {\n var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers\n for (var i in reqHeaders) {\n var header = reqHeaders[i]\n if (header) {\n options.headers[i] = header\n }\n }\n }\n\n // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,\n // but for now exists as a backwards-compatibility layer\n options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized)\n\n if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) {\n options.createConnection = eventSourceInitDict.createConnection\n }\n\n // If specify http proxy, make the request to sent to the proxy server,\n // and include the original url in path and Host headers\n var useProxy = eventSourceInitDict && eventSourceInitDict.proxy\n if (useProxy) {\n var proxy = parse(eventSourceInitDict.proxy)\n isSecure = proxy.protocol === 'https:'\n\n options.protocol = isSecure ? 'https:' : 'http:'\n options.path = url\n options.headers.Host = options.host\n options.hostname = proxy.hostname\n options.host = proxy.host\n options.port = proxy.port\n }\n\n // If https options are specified, merge them into the request options\n if (eventSourceInitDict && eventSourceInitDict.https) {\n for (var optName in eventSourceInitDict.https) {\n if (httpsOptions.indexOf(optName) === -1) {\n continue\n }\n\n var option = eventSourceInitDict.https[optName]\n if (option !== undefined) {\n options[optName] = option\n }\n }\n }\n\n // Pass this on to the XHR\n if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) {\n options.withCredentials = eventSourceInitDict.withCredentials\n }\n\n req = (isSecure ? https : http).request(options, function (res) {\n self.connectionInProgress = false\n // Handle HTTP errors\n if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {\n _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))\n onConnectionClosed()\n return\n }\n\n // Handle HTTP redirects\n if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {\n var location = res.headers.location\n if (!location) {\n // Server sent redirect response without Location header.\n _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))\n return\n }\n var prevOrigin = new URL(url).origin\n var nextOrigin = new URL(location).origin\n hasNewOrigin = prevOrigin !== nextOrigin\n if (res.statusCode === 307) reconnectUrl = url\n url = location\n process.nextTick(connect)\n return\n }\n\n if (res.statusCode !== 200) {\n _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))\n return self.close()\n }\n\n readyState = EventSource.OPEN\n res.on('close', function () {\n res.removeAllListeners('close')\n res.removeAllListeners('end')\n onConnectionClosed()\n })\n\n res.on('end', function () {\n res.removeAllListeners('close')\n res.removeAllListeners('end')\n onConnectionClosed()\n })\n _emit('open', new Event('open'))\n\n // text/event-stream parser adapted from webkit's\n // Source/WebCore/page/EventSource.cpp\n var buf\n var newBuffer\n var startingPos = 0\n var startingFieldLength = -1\n var newBufferSize = 0\n var bytesUsed = 0\n\n res.on('data', function (chunk) {\n if (!buf) {\n buf = chunk\n if (hasBom(buf)) {\n buf = buf.slice(bom.length)\n }\n bytesUsed = buf.length\n } else {\n if (chunk.length > buf.length - bytesUsed) {\n newBufferSize = (buf.length * 2) + chunk.length\n if (newBufferSize > maxBufferAheadAllocation) {\n newBufferSize = buf.length + chunk.length + maxBufferAheadAllocation\n }\n newBuffer = Buffer.alloc(newBufferSize)\n buf.copy(newBuffer, 0, 0, bytesUsed)\n buf = newBuffer\n }\n chunk.copy(buf, bytesUsed)\n bytesUsed += chunk.length\n }\n\n var pos = 0\n var length = bytesUsed\n\n while (pos < length) {\n if (discardTrailingNewline) {\n if (buf[pos] === lineFeed) {\n ++pos\n }\n discardTrailingNewline = false\n }\n\n var lineLength = -1\n var fieldLength = startingFieldLength\n var c\n\n for (var i = startingPos; lineLength < 0 && i < length; ++i) {\n c = buf[i]\n if (c === colon) {\n if (fieldLength < 0) {\n fieldLength = i - pos\n }\n } else if (c === carriageReturn) {\n discardTrailingNewline = true\n lineLength = i - pos\n } else if (c === lineFeed) {\n lineLength = i - pos\n }\n }\n\n if (lineLength < 0) {\n startingPos = length - pos\n startingFieldLength = fieldLength\n break\n } else {\n startingPos = 0\n startingFieldLength = -1\n }\n\n parseEventStreamLine(buf, pos, fieldLength, lineLength)\n\n pos += lineLength + 1\n }\n\n if (pos === length) {\n buf = void 0\n bytesUsed = 0\n } else if (pos > 0) {\n buf = buf.slice(pos, bytesUsed)\n bytesUsed = buf.length\n }\n })\n })\n\n req.on('error', function (err) {\n self.connectionInProgress = false\n onConnectionClosed(err.message)\n })\n\n if (req.setNoDelay) req.setNoDelay(true)\n req.end()\n }\n\n connect()\n\n function _emit () {\n if (self.listeners(arguments[0]).length > 0) {\n self.emit.apply(self, arguments)\n }\n }\n\n this._close = function () {\n if (readyState === EventSource.CLOSED) return\n readyState = EventSource.CLOSED\n if (req.abort) req.abort()\n if (req.xhr && req.xhr.abort) req.xhr.abort()\n }\n\n function parseEventStreamLine (buf, pos, fieldLength, lineLength) {\n if (lineLength === 0) {\n if (data.length > 0) {\n var type = eventName || 'message'\n _emit(type, new MessageEvent(type, {\n data: data.slice(0, -1), // remove trailing newline\n lastEventId: lastEventId,\n origin: new URL(url).origin\n }))\n data = ''\n }\n eventName = void 0\n } else if (fieldLength > 0) {\n var noValue = fieldLength < 0\n var step = 0\n var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString()\n\n if (noValue) {\n step = lineLength\n } else if (buf[pos + fieldLength + 1] !== space) {\n step = fieldLength + 1\n } else {\n step = fieldLength + 2\n }\n pos += step\n\n var valueLength = lineLength - step\n var value = buf.slice(pos, pos + valueLength).toString()\n\n if (field === 'data') {\n data += value + '\\n'\n } else if (field === 'event') {\n eventName = value\n } else if (field === 'id') {\n lastEventId = value\n } else if (field === 'retry') {\n var retry = parseInt(value, 10)\n if (!Number.isNaN(retry)) {\n self.reconnectInterval = retry\n }\n }\n }\n }\n}\n\nmodule.exports = EventSource\n\nutil.inherits(EventSource, events.EventEmitter)\nEventSource.prototype.constructor = EventSource; // make stacktraces readable\n\n['open', 'error', 'message'].forEach(function (method) {\n Object.defineProperty(EventSource.prototype, 'on' + method, {\n /**\n * Returns the current listener\n *\n * @return {Mixed} the set function or undefined\n * @api private\n */\n get: function get () {\n var listener = this.listeners(method)[0]\n return listener ? (listener._listener ? listener._listener : listener) : undefined\n },\n\n /**\n * Start listening for events\n *\n * @param {Function} listener the listener\n * @return {Mixed} the set function or undefined\n * @api private\n */\n set: function set (listener) {\n this.removeAllListeners(method)\n this.addEventListener(method, listener)\n }\n })\n})\n\n/**\n * Ready states\n */\nObject.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0})\nObject.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1})\nObject.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2})\n\nEventSource.prototype.CONNECTING = 0\nEventSource.prototype.OPEN = 1\nEventSource.prototype.CLOSED = 2\n\n/**\n * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close\n * @api public\n */\nEventSource.prototype.close = function () {\n this._close()\n}\n\n/**\n * Emulates the W3C Browser based WebSocket interface using addEventListener.\n *\n * @param {String} type A string representing the event type to listen out for\n * @param {Function} listener callback\n * @see https://developer.mozilla.org/en/DOM/element.addEventListener\n * @see http://dev.w3.org/html5/websockets/#the-websocket-interface\n * @api public\n */\nEventSource.prototype.addEventListener = function addEventListener (type, listener) {\n if (typeof listener === 'function') {\n // store a reference so we can return the original function again\n listener._listener = listener\n this.on(type, listener)\n }\n}\n\n/**\n * Emulates the W3C Browser based WebSocket interface using dispatchEvent.\n *\n * @param {Event} event An event to be dispatched\n * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent\n * @api public\n */\nEventSource.prototype.dispatchEvent = function dispatchEvent (event) {\n if (!event.type) {\n throw new Error('UNSPECIFIED_EVENT_TYPE_ERR')\n }\n // if event is instance of an CustomEvent (or has 'details' property),\n // send the detail object as the payload for the event\n this.emit(event.type, event.detail)\n}\n\n/**\n * Emulates the W3C Browser based WebSocket interface using removeEventListener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {Function} listener callback\n * @see https://developer.mozilla.org/en/DOM/element.removeEventListener\n * @see http://dev.w3.org/html5/websockets/#the-websocket-interface\n * @api public\n */\nEventSource.prototype.removeEventListener = function removeEventListener (type, listener) {\n if (typeof listener === 'function') {\n listener._listener = undefined\n this.removeListener(type, listener)\n }\n}\n\n/**\n * W3C Event\n *\n * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event\n * @api private\n */\nfunction Event (type, optionalProperties) {\n Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })\n if (optionalProperties) {\n for (var f in optionalProperties) {\n if (optionalProperties.hasOwnProperty(f)) {\n Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true })\n }\n }\n }\n}\n\n/**\n * W3C MessageEvent\n *\n * @see http://www.w3.org/TR/webmessaging/#event-definitions\n * @api private\n */\nfunction MessageEvent (type, eventInitDict) {\n Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })\n for (var f in eventInitDict) {\n if (eventInitDict.hasOwnProperty(f)) {\n Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true })\n }\n }\n}\n\n/**\n * Returns a new object of headers that does not include any authorization and cookie headers\n *\n * @param {Object} headers An object of headers ({[headerName]: headerValue})\n * @return {Object} a new object of headers\n * @api private\n */\nfunction removeUnsafeHeaders (headers) {\n var safe = {}\n for (var key in headers) {\n if (reUnsafeHeader.test(key)) {\n continue\n }\n\n safe[key] = headers[key]\n }\n\n return safe\n}\n","module.exports = require('eventsource')\n"],"names":["parse","require$$0","events","require$$1","https","require$$2","http","require$$3","util","require$$4","httpsOptions","bom","colon","space","lineFeed","carriageReturn","maxBufferAheadAllocation","reUnsafeHeader","hasBom","buf","every","charCode","index","EventSource","url","eventSourceInitDict","readyState","CONNECTING","headers","hasNewOrigin","Object","defineProperty","get","self","reconnectInterval","connectionInProgress","onConnectionClosed","message","CLOSED","_emit","Event","reconnectUrl","setTimeout","connect","req","lastEventId","discardTrailingNewline","data","eventName","options","isSecure","protocol","reqHeaders","removeUnsafeHeaders","i","header","rejectUnauthorized","createConnection","undefined","useProxy","proxy","path","Host","host","hostname","port","optName","indexOf","option","withCredentials","request","res","statusCode","status","statusMessage","location","prevOrigin","URL","origin","nextOrigin","process","nextTick","close","OPEN","on","removeAllListeners","newBuffer","startingPos","startingFieldLength","newBufferSize","bytesUsed","chunk","length","Buffer","alloc","copy","slice","pos","lineLength","fieldLength","c","parseEventStreamLine","err","setNoDelay","end","listeners","arguments","emit","apply","_close","abort","xhr","type","MessageEvent","noValue","step","field","toString","valueLength","value","retry","parseInt","Number","isNaN","eventsource","inherits","EventEmitter","prototype","constructor","forEach","method","listener","_listener","set","addEventListener","enumerable","dispatchEvent","event","Error","detail","removeEventListener","removeListener","optionalProperties","writable","f","hasOwnProperty","eventInitDict","safe","key","test","node"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAIA,QAAQC,EAAeD,OACvBE,SAASC,YACTC,QAAQC,cACRC,OAAOC,cACPC,OAAOC,YAEPC,eAAe,CACjB,OAAO,OAAO,cAAc,QAAQ,MAAM,WAC1C,sBAAsB,kBAAkB,cAAc,qBAAA,GAGpDC,MAAM,CAAC,KAAK,KAAK,GAAG,GACpBC,QAAQ,IACRC,QAAQ,IACRC,WAAW,IACXC,iBAAiB,IAEjBC,2BAA2B,OAAO,KAElCC,iBAAiB;AAErB,WAASC,OAAQC,KAAK;AACpB,WAAOR,IAAIS,MAAM,SAAUC,UAAUC,OAAO;AAC1C,aAAOH,IAAIG,KAAK,MAAMD;AAAAA,IACvB,CAAA;AAAA,EACH;AASA,WAASE,YAAaC,KAAKC,qBAAqB;AAC9C,QAAIC,aAAaH,YAAYI,YACzBC,UAAUH,uBAAuBA,oBAAoBG,SACrDC,eAAe;AACnBC,WAAOC,eAAe,MAAM,cAAc;AAAA,MACxCC,KAAK,WAAY;AACf,eAAON;AAAAA,MACb;AAAA,IACG,CAAA,GAEDI,OAAOC,eAAe,MAAM,OAAO;AAAA,MACjCC,KAAK,WAAY;AACf,eAAOR;AAAAA,MACb;AAAA,IACG,CAAA;AAED,QAAIS,OAAO;AACXA,SAAKC,oBAAoB,KACzBD,KAAKE,uBAAuB;AAE5B,aAASC,mBAAoBC,SAA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Ua,sBAAsB,SAA8B5B,MAAMmB,UAAU;AACxF,IAAI,OAAOA,YAAa,eACtBA,SAASC,YAAY1E,QACrB,KAAKmF,eAAe7B,MAAMmB,QAAQ;AAAA,EAEtC;AAQA,WAAS3F,MAAOwE,MAAM8B,oBAAoB;AAExC,QADAhH,OAAOC,eAAe,MAAM,QAAQ;AAAA,MAAEgH,UAAU;AAAA,MAAOxB,OAAOP;AAAAA,MAAMuB,YAAY;AAAA,IAAM,CAAA,GAClFO;AACF,eAASE,KAAKF;AACZ,QAAIA,mBAAmBG,eAAeD,CAAC,KACrClH,OAAOC,eAAe,MAAMiH,GAAG;AAAA,UAAED,UAAU;AAAA,UAAOxB,OAAOuB,mBAAmBE,CAAC;AAAA,UAAGT,YAAY;AAAA,QAAM,CAAA;AAAA,EAI1G;AAQA,WAAStB,aAAcD,MAAMkC,eAAe;AAC1CpH,WAAOC,eAAe,MAAM,QAAQ;AAAA,MAAEgH,UAAU;AAAA,MAAOxB,OAAOP;AAAAA,MAAMuB,YAAY;AAAA,IAAM,CAAA;AACtF,aAASS,KAAKE;AACZ,MAAIA,cAAcD,eAAeD,CAAC,KAChClH,OAAOC,eAAe,MAAMiH,GAAG;AAAA,QAAED,UAAU;AAAA,QAAOxB,OAAO2B,cAAcF,CAAC;AAAA,QAAGT,YAAY;AAAA,MAAM,CAAA;AAAA,EAGnG;AASA,WAASlF,oBAAqBzB,SAAS;AACrC,QAAIuH,OAAO,CAAA;AACX,aAASC,OAAOxH;AACd,MAAIX,eAAeoI,KAAKD,GAAG,MAI3BD,KAAKC,GAAG,IAAIxH,QAAQwH,GAAG;AAGzB,WAAOD;AAAAA,EACT;;;;;kDC9eAG,SAAiBrJ,mBAAA;;;;;;","x_google_ignoreList":[0,1]}
@@ -0,0 +1,340 @@
1
+ import { C } from "./index.js";
2
+ const reKeySegment = /_key\s*==\s*['"](.*)['"]/;
3
+ function isKeySegment(segment) {
4
+ return typeof segment == "string" ? reKeySegment.test(segment.trim()) : typeof segment == "object" && "_key" in segment;
5
+ }
6
+ function toString(path) {
7
+ if (!Array.isArray(path)) throw new Error("Path is not an array");
8
+ return path.reduce((target, segment, i) => {
9
+ const segmentType = typeof segment;
10
+ if (segmentType === "number") return `${target}[${segment}]`;
11
+ if (segmentType === "string") return `${target}${i === 0 ? "" : "."}${segment}`;
12
+ if (isKeySegment(segment) && segment._key) return `${target}[_key=="${segment._key}"]`;
13
+ if (Array.isArray(segment)) {
14
+ const [from, to] = segment;
15
+ return `${target}[${from}:${to}]`;
16
+ }
17
+ throw new Error(`Unsupported path segment \`${JSON.stringify(segment)}\``);
18
+ }, "");
19
+ }
20
+ const ESCAPE = {
21
+ "\f": "\\f",
22
+ "\n": "\\n",
23
+ "\r": "\\r",
24
+ " ": "\\t",
25
+ "'": "\\'",
26
+ "\\": "\\\\"
27
+ }, UNESCAPE = {
28
+ "\\f": "\f",
29
+ "\\n": `
30
+ `,
31
+ "\\r": "\r",
32
+ "\\t": " ",
33
+ "\\'": "'",
34
+ "\\\\": "\\"
35
+ };
36
+ function jsonPath(path) {
37
+ return `$${path.map((segment) => typeof segment == "string" ? `['${segment.replace(/[\f\n\r\t'\\]/g, (match) => ESCAPE[match])}']` : typeof segment == "number" ? `[${segment}]` : segment._key !== "" ? `[?(@._key=='${segment._key.replace(/['\\]/g, (match) => ESCAPE[match])}')]` : `[${segment._index}]`).join("")}`;
38
+ }
39
+ function parseJsonPath(path) {
40
+ const parsed = [], parseRe = /\['(.*?)'\]|\[(\d+)\]|\[\?\(@\._key=='(.*?)'\)\]/g;
41
+ let match;
42
+ for (; (match = parseRe.exec(path)) !== null; ) {
43
+ if (match[1] !== void 0) {
44
+ const key = match[1].replace(/\\(\\|f|n|r|t|')/g, (m) => UNESCAPE[m]);
45
+ parsed.push(key);
46
+ continue;
47
+ }
48
+ if (match[2] !== void 0) {
49
+ parsed.push(parseInt(match[2], 10));
50
+ continue;
51
+ }
52
+ if (match[3] !== void 0) {
53
+ const _key = match[3].replace(/\\(\\')/g, (m) => UNESCAPE[m]);
54
+ parsed.push({
55
+ _key,
56
+ _index: -1
57
+ });
58
+ continue;
59
+ }
60
+ }
61
+ return parsed;
62
+ }
63
+ function jsonPathToStudioPath(path) {
64
+ return path.map((segment) => {
65
+ if (typeof segment == "string" || typeof segment == "number") return segment;
66
+ if (segment._key !== "") return {
67
+ _key: segment._key
68
+ };
69
+ if (segment._index !== -1) return segment._index;
70
+ throw new Error(`invalid segment:${JSON.stringify(segment)}`);
71
+ });
72
+ }
73
+ function jsonPathToMappingPath(path) {
74
+ return path.map((segment) => {
75
+ if (typeof segment == "string" || typeof segment == "number") return segment;
76
+ if (segment._index !== -1) return segment._index;
77
+ throw new Error(`invalid segment:${JSON.stringify(segment)}`);
78
+ });
79
+ }
80
+ function resolveMapping(resultPath, csm) {
81
+ if (!csm?.mappings) return;
82
+ const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath));
83
+ if (csm.mappings[resultMappingPath] !== void 0) return {
84
+ mapping: csm.mappings[resultMappingPath],
85
+ matchedPath: resultMappingPath,
86
+ pathSuffix: ""
87
+ };
88
+ const mappings = Object.entries(csm.mappings).filter(([key]) => resultMappingPath.startsWith(key)).sort(([key1], [key2]) => key2.length - key1.length);
89
+ if (mappings.length == 0) return;
90
+ const [matchedPath, mapping] = mappings[0], pathSuffix = resultMappingPath.substring(matchedPath.length);
91
+ return {
92
+ mapping,
93
+ matchedPath,
94
+ pathSuffix
95
+ };
96
+ }
97
+ function isArray(value) {
98
+ return value !== null && Array.isArray(value);
99
+ }
100
+ function isRecord(value) {
101
+ return typeof value == "object" && value !== null;
102
+ }
103
+ function walkMap(value, mappingFn, path = []) {
104
+ if (isArray(value)) return value.map((v, idx) => {
105
+ if (isRecord(v)) {
106
+ const _key = v._key;
107
+ if (typeof _key == "string") return walkMap(v, mappingFn, path.concat({
108
+ _key,
109
+ _index: idx
110
+ }));
111
+ }
112
+ return walkMap(v, mappingFn, path.concat(idx));
113
+ });
114
+ if (isRecord(value)) {
115
+ if (value._type === "block" || value._type === "span") {
116
+ const result = {
117
+ ...value
118
+ };
119
+ return value._type === "block" ? result.children = walkMap(value.children, mappingFn, path.concat("children")) : value._type === "span" && (result.text = walkMap(value.text, mappingFn, path.concat("text"))), result;
120
+ }
121
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]));
122
+ }
123
+ return mappingFn(value, path);
124
+ }
125
+ function encodeIntoResult(result, csm, encoder) {
126
+ return walkMap(result, (value, path) => {
127
+ if (typeof value != "string") return value;
128
+ const resolveMappingResult = resolveMapping(path, csm);
129
+ if (!resolveMappingResult) return value;
130
+ const {
131
+ mapping,
132
+ matchedPath
133
+ } = resolveMappingResult;
134
+ if (mapping.type !== "value" || mapping.source.type !== "documentValue") return value;
135
+ const sourceDocument = csm.documents[mapping.source.document], sourcePath = csm.paths[mapping.source.path], matchPathSegments = parseJsonPath(matchedPath), fullSourceSegments = parseJsonPath(sourcePath).concat(path.slice(matchPathSegments.length));
136
+ return encoder({
137
+ sourcePath: fullSourceSegments,
138
+ sourceDocument,
139
+ resultPath: path,
140
+ value
141
+ });
142
+ });
143
+ }
144
+ const DRAFTS_FOLDER = "drafts", VERSION_FOLDER = "versions", PATH_SEPARATOR = ".", DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`, VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`;
145
+ function isDraftId(id) {
146
+ return id.startsWith(DRAFTS_PREFIX);
147
+ }
148
+ function isVersionId(id) {
149
+ return id.startsWith(VERSION_PREFIX);
150
+ }
151
+ function isPublishedId(id) {
152
+ return !isDraftId(id) && !isVersionId(id);
153
+ }
154
+ function getVersionFromId(id) {
155
+ if (!isVersionId(id)) return;
156
+ const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR);
157
+ return versionId;
158
+ }
159
+ function getPublishedId(id) {
160
+ return isVersionId(id) ? id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR) : isDraftId(id) ? id.slice(DRAFTS_PREFIX.length) : id;
161
+ }
162
+ function createEditUrl(options) {
163
+ const {
164
+ baseUrl,
165
+ workspace: _workspace = "default",
166
+ tool: _tool = "default",
167
+ id: _id,
168
+ type,
169
+ path,
170
+ projectId,
171
+ dataset
172
+ } = options;
173
+ if (!baseUrl) throw new Error("baseUrl is required");
174
+ if (!path) throw new Error("path is required");
175
+ if (!_id) throw new Error("id is required");
176
+ if (baseUrl !== "/" && baseUrl.endsWith("/")) throw new Error("baseUrl must not end with a slash");
177
+ const workspace = _workspace === "default" ? void 0 : _workspace, tool = _tool === "default" ? void 0 : _tool, id = getPublishedId(_id), stringifiedPath = Array.isArray(path) ? toString(jsonPathToStudioPath(path)) : path, searchParams = new URLSearchParams({
178
+ baseUrl,
179
+ id,
180
+ type,
181
+ path: stringifiedPath
182
+ });
183
+ if (workspace && searchParams.set("workspace", workspace), tool && searchParams.set("tool", tool), projectId && searchParams.set("projectId", projectId), dataset && searchParams.set("dataset", dataset), isPublishedId(_id)) searchParams.set("perspective", "published");
184
+ else if (isVersionId(_id)) {
185
+ const versionId = getVersionFromId(_id);
186
+ searchParams.set("perspective", versionId);
187
+ }
188
+ const segments = [baseUrl === "/" ? "" : baseUrl];
189
+ workspace && segments.push(workspace);
190
+ const routerParams = ["mode=presentation", `id=${id}`, `type=${type}`, `path=${encodeURIComponent(stringifiedPath)}`];
191
+ return tool && routerParams.push(`tool=${tool}`), segments.push("intent", "edit", `${routerParams.join(";")}?${searchParams}`), segments.join("/");
192
+ }
193
+ function resolveStudioBaseRoute(studioUrl) {
194
+ let baseUrl = typeof studioUrl == "string" ? studioUrl : studioUrl.baseUrl;
195
+ return baseUrl !== "/" && (baseUrl = baseUrl.replace(/\/$/, "")), typeof studioUrl == "string" ? {
196
+ baseUrl
197
+ } : {
198
+ ...studioUrl,
199
+ baseUrl
200
+ };
201
+ }
202
+ const filterDefault = ({
203
+ sourcePath,
204
+ resultPath,
205
+ value
206
+ }) => {
207
+ if (isValidDate(value) || isValidURL(value)) return !1;
208
+ const endPath = sourcePath.at(-1);
209
+ return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && (endPath.startsWith("_") || endPath.endsWith("Id")) || sourcePath.some((path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo") || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath));
210
+ }, denylist = /* @__PURE__ */ new Set(["color", "colour", "currency", "email", "format", "gid", "hex", "href", "hsl", "hsla", "icon", "id", "index", "key", "language", "layout", "link", "linkAction", "locale", "lqip", "page", "path", "ref", "rgb", "rgba", "route", "secret", "slug", "status", "tag", "template", "theme", "type", "textTheme", "unit", "url", "username", "variant", "website"]);
211
+ function isValidDate(dateString) {
212
+ return /^\d{4}-\d{2}-\d{2}/.test(dateString) ? !!Date.parse(dateString) : !1;
213
+ }
214
+ function isValidURL(url) {
215
+ try {
216
+ new URL(url, url.startsWith("/") ? "https://acme.com" : void 0);
217
+ } catch {
218
+ return !1;
219
+ }
220
+ return !0;
221
+ }
222
+ function hasTypeLike(path) {
223
+ return path.some((segment) => typeof segment == "string" && segment.match(/type/i) !== null);
224
+ }
225
+ const TRUNCATE_LENGTH = 20;
226
+ function stegaEncodeSourceMap(result, resultSourceMap, config) {
227
+ const {
228
+ filter,
229
+ logger,
230
+ enabled
231
+ } = config;
232
+ if (!enabled) {
233
+ const msg = "config.enabled must be true, don't call this function otherwise";
234
+ throw logger?.error?.(`[@sanity/client]: ${msg}`, {
235
+ result,
236
+ resultSourceMap,
237
+ config
238
+ }), new TypeError(msg);
239
+ }
240
+ if (!resultSourceMap) return logger?.error?.("[@sanity/client]: Missing Content Source Map from response body", {
241
+ result,
242
+ resultSourceMap,
243
+ config
244
+ }), result;
245
+ if (!config.studioUrl) {
246
+ const msg = "config.studioUrl must be defined";
247
+ throw logger?.error?.(`[@sanity/client]: ${msg}`, {
248
+ result,
249
+ resultSourceMap,
250
+ config
251
+ }), new TypeError(msg);
252
+ }
253
+ const report = {
254
+ encoded: [],
255
+ skipped: []
256
+ }, resultWithStega = encodeIntoResult(result, resultSourceMap, ({
257
+ sourcePath,
258
+ sourceDocument,
259
+ resultPath,
260
+ value
261
+ }) => {
262
+ if ((typeof filter == "function" ? filter({
263
+ sourcePath,
264
+ resultPath,
265
+ filterDefault,
266
+ sourceDocument,
267
+ value
268
+ }) : filterDefault({
269
+ sourcePath,
270
+ resultPath,
271
+ value
272
+ })) === !1) return logger && report.skipped.push({
273
+ path: prettyPathForLogging(sourcePath),
274
+ value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? "..." : ""}`,
275
+ length: value.length
276
+ }), value;
277
+ logger && report.encoded.push({
278
+ path: prettyPathForLogging(sourcePath),
279
+ value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? "..." : ""}`,
280
+ length: value.length
281
+ });
282
+ const {
283
+ baseUrl,
284
+ workspace,
285
+ tool
286
+ } = resolveStudioBaseRoute(typeof config.studioUrl == "function" ? config.studioUrl(sourceDocument) : config.studioUrl);
287
+ if (!baseUrl) return value;
288
+ const {
289
+ _id: id,
290
+ _type: type,
291
+ _projectId: projectId,
292
+ _dataset: dataset
293
+ } = sourceDocument;
294
+ return C(
295
+ value,
296
+ {
297
+ origin: "sanity.io",
298
+ href: createEditUrl({
299
+ baseUrl,
300
+ workspace,
301
+ tool,
302
+ id,
303
+ type,
304
+ path: sourcePath,
305
+ ...!config.omitCrossDatasetReferenceData && {
306
+ dataset,
307
+ projectId
308
+ }
309
+ })
310
+ },
311
+ // We use custom logic to determine if we should skip encoding
312
+ !1
313
+ );
314
+ });
315
+ if (logger) {
316
+ const isSkipping = report.skipped.length, isEncoding = report.encoded.length;
317
+ if ((isSkipping || isEncoding) && ((logger?.groupCollapsed || logger.log)?.("[@sanity/client]: Encoding source map into result"), logger.log?.(`[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`)), report.encoded.length > 0 && (logger?.log?.("[@sanity/client]: Table of encoded paths"), (logger?.table || logger.log)?.(report.encoded)), report.skipped.length > 0) {
318
+ const skipped = /* @__PURE__ */ new Set();
319
+ for (const {
320
+ path
321
+ } of report.skipped) skipped.add(path.replace(reKeySegment, "0").replace(/\[\d+\]/g, "[]"));
322
+ logger?.log?.("[@sanity/client]: List of skipped paths", [...skipped.values()]);
323
+ }
324
+ (isSkipping || isEncoding) && logger?.groupEnd?.();
325
+ }
326
+ return resultWithStega;
327
+ }
328
+ function prettyPathForLogging(path) {
329
+ return toString(jsonPathToStudioPath(path));
330
+ }
331
+ var stegaEncodeSourceMap$1 = /* @__PURE__ */ Object.freeze({
332
+ __proto__: null,
333
+ stegaEncodeSourceMap
334
+ });
335
+ export {
336
+ encodeIntoResult,
337
+ stegaEncodeSourceMap,
338
+ stegaEncodeSourceMap$1
339
+ };
340
+ //# sourceMappingURL=stegaEncodeSourceMap.js.map