@sanity/sdk 0.0.0-chore-react-18-compat.0 → 0.0.0-chore-react-18-compat.1
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/dist/index.cjs +4888 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2121 -0
- package/dist/index.js +1 -1
- package/package.json +3 -2
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,4888 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
3
|
+
var client = require("@sanity/client"), rxjs = require("rxjs"), middleware = require("zustand/middleware"), vanilla = require("zustand/vanilla"), reselect = require("reselect"), lodashEs = require("lodash-es"), comlink = require("@sanity/comlink"), operators = require("rxjs/operators"), mutate = require("@sanity/mutate"), csm = require("@sanity/client/csm"), diffMatchPatch$1 = require("@sanity/diff-match-patch"), types = require("@sanity/types"), _unstable_store = require("@sanity/mutate/_unstable_store"), _documentCurrentScript = typeof document < "u" ? document.currentScript : null, AuthStateType = /* @__PURE__ */ ((AuthStateType2) => (AuthStateType2.LOGGED_IN = "logged-in", AuthStateType2.LOGGING_IN = "logging-in", AuthStateType2.ERROR = "error", AuthStateType2.LOGGED_OUT = "logged-out", AuthStateType2))(AuthStateType || {});
|
|
4
|
+
function getEnv(key) {
|
|
5
|
+
if (typeof { url: typeof document > "u" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href } < "u", typeof process < "u" && process.env)
|
|
6
|
+
return process.env[key];
|
|
7
|
+
if (typeof window < "u" && window.ENV)
|
|
8
|
+
return window.ENV?.[key];
|
|
9
|
+
}
|
|
10
|
+
const resourceCache = /* @__PURE__ */ new WeakMap();
|
|
11
|
+
function createResourceState(initialState, devToolsOptions) {
|
|
12
|
+
const store = vanilla.createStore()(middleware.devtools(() => initialState, devToolsOptions));
|
|
13
|
+
return {
|
|
14
|
+
get: store.getState,
|
|
15
|
+
set: (actionKey, updatedState) => {
|
|
16
|
+
store.getState() !== updatedState && store.setState(updatedState, !1, actionKey);
|
|
17
|
+
},
|
|
18
|
+
observable: new rxjs.Observable((observer) => {
|
|
19
|
+
const emit = () => observer.next(store.getState());
|
|
20
|
+
return emit(), store.subscribe(emit);
|
|
21
|
+
})
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function initializeResource(instance, resource) {
|
|
25
|
+
const fullName = resource.name === "Auth" ? "Auth-global" : `${resource.name}-${instance.identity.resourceId}`, initialState = resource.getInitialState(instance), state = createResourceState(initialState, {
|
|
26
|
+
name: fullName,
|
|
27
|
+
enabled: !!getEnv("DEV")
|
|
28
|
+
}), dispose = resource.initialize?.call({ instance, state }, instance) ?? (() => {
|
|
29
|
+
});
|
|
30
|
+
return { state, dispose };
|
|
31
|
+
}
|
|
32
|
+
function getOrCreateResource(instance, resource) {
|
|
33
|
+
const fullName = resource.name === "Auth" ? "Auth-global" : `${resource.name}-${instance.identity.resourceId}`;
|
|
34
|
+
resourceCache.has(instance.identity) || resourceCache.set(instance.identity, /* @__PURE__ */ new Map());
|
|
35
|
+
const initializedResources = resourceCache.get(instance.identity), cached = initializedResources.get(fullName);
|
|
36
|
+
if (cached) return cached;
|
|
37
|
+
const result = initializeResource(instance, resource);
|
|
38
|
+
return initializedResources.set(fullName, result), result;
|
|
39
|
+
}
|
|
40
|
+
function disposeResources(identity) {
|
|
41
|
+
const resources = resourceCache.get(identity);
|
|
42
|
+
if (resources)
|
|
43
|
+
for (const resource of resources.values())
|
|
44
|
+
resource.dispose();
|
|
45
|
+
}
|
|
46
|
+
function createAction(resource, actionDefinition) {
|
|
47
|
+
return (dependencies, ...args) => {
|
|
48
|
+
const instance = "state" in dependencies ? dependencies.instance : dependencies, { state } = "state" in dependencies ? dependencies : getOrCreateResource(dependencies, resource), actionContext = { instance, state };
|
|
49
|
+
return actionDefinition(actionContext).bind(actionContext)(...args);
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function createInternalAction(actionDefinition) {
|
|
53
|
+
return (actionContext, ...args) => actionDefinition(actionContext).bind(actionContext)(...args);
|
|
54
|
+
}
|
|
55
|
+
function createStateSourceAction(resource, options) {
|
|
56
|
+
const selector = typeof options == "function" ? options : options.selector, subscribeHandler = options && "onSubscribe" in options ? options.onSubscribe : void 0, isEqual = options && "isEqual" in options ? options.isEqual ?? Object.is : Object.is;
|
|
57
|
+
return createAction(resource, ({ state }) => function(...args) {
|
|
58
|
+
const getCurrent = () => selector(state.get(), ...args), subscribe = (onStoreChanged) => {
|
|
59
|
+
const cleanup = subscribeHandler?.(this, ...args), subscription = state.observable.pipe(
|
|
60
|
+
rxjs.map(getCurrent),
|
|
61
|
+
rxjs.distinctUntilChanged(isEqual),
|
|
62
|
+
// skip the first emission because we only want to emit when the
|
|
63
|
+
// value changes. `distinctUntilChanged` will always emit the first
|
|
64
|
+
// the first value so we skip this emission
|
|
65
|
+
rxjs.skip(1)
|
|
66
|
+
).subscribe({
|
|
67
|
+
next: () => onStoreChanged?.(),
|
|
68
|
+
// the convention is to have the selector throw the error so we
|
|
69
|
+
// invoke onStoreChanged on error as well. this will cause the
|
|
70
|
+
// observable code path below to emit an error because the selector
|
|
71
|
+
// will throw and that will be used to emit an .error on the observer
|
|
72
|
+
error: () => onStoreChanged?.()
|
|
73
|
+
});
|
|
74
|
+
return () => {
|
|
75
|
+
subscription.unsubscribe(), cleanup?.();
|
|
76
|
+
};
|
|
77
|
+
}, observable = new rxjs.Observable((observer) => {
|
|
78
|
+
const emitCurrent = () => {
|
|
79
|
+
try {
|
|
80
|
+
observer.next(getCurrent());
|
|
81
|
+
} catch (error) {
|
|
82
|
+
observer.error(error);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
return emitCurrent(), subscribe(emitCurrent);
|
|
86
|
+
}).pipe(rxjs.share());
|
|
87
|
+
return {
|
|
88
|
+
getCurrent,
|
|
89
|
+
subscribe,
|
|
90
|
+
observable
|
|
91
|
+
};
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
const DEFAULT_BASE = "http://localhost", AUTH_CODE_PARAM = "sid", DEFAULT_API_VERSION$1 = "2021-06-07", REQUEST_TAG_PREFIX = "sanity.sdk.auth", refreshStampedToken = createInternalAction(
|
|
95
|
+
({ state }) => {
|
|
96
|
+
const { clientFactory, apiHost, storageArea, storageKey } = state.get().options, refreshToken$ = state.observable.pipe(
|
|
97
|
+
rxjs.map(({ authState }) => authState),
|
|
98
|
+
rxjs.filter(
|
|
99
|
+
(authState) => authState.type === AuthStateType.LOGGED_IN
|
|
100
|
+
),
|
|
101
|
+
rxjs.distinctUntilChanged(),
|
|
102
|
+
rxjs.filter((authState) => authState.token.includes("-st")),
|
|
103
|
+
// Ensure we only try to refresh stamped tokens
|
|
104
|
+
rxjs.switchMap(
|
|
105
|
+
(authState) => rxjs.interval(10 * 60 * 1e3).pipe(
|
|
106
|
+
rxjs.takeWhile(() => state.get().authState.type === AuthStateType.LOGGED_IN),
|
|
107
|
+
rxjs.map(() => authState.token),
|
|
108
|
+
rxjs.distinctUntilChanged(),
|
|
109
|
+
rxjs.map(
|
|
110
|
+
(token) => clientFactory({
|
|
111
|
+
apiVersion: DEFAULT_API_VERSION$1,
|
|
112
|
+
requestTagPrefix: "sdk.token-refresh",
|
|
113
|
+
useProjectHostname: !1,
|
|
114
|
+
token,
|
|
115
|
+
ignoreBrowserTokenWarning: !0,
|
|
116
|
+
...apiHost && { apiHost }
|
|
117
|
+
})
|
|
118
|
+
),
|
|
119
|
+
rxjs.switchMap(
|
|
120
|
+
(client2) => client2.observable.request({
|
|
121
|
+
uri: "auth/refresh-token",
|
|
122
|
+
method: "POST",
|
|
123
|
+
body: {
|
|
124
|
+
token: authState.token
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
);
|
|
131
|
+
return function() {
|
|
132
|
+
return refreshToken$.subscribe({
|
|
133
|
+
next: (response) => {
|
|
134
|
+
state.set("setRefreshStampedToken", (prev) => ({
|
|
135
|
+
authState: prev.authState.type === AuthStateType.LOGGED_IN ? { ...prev.authState, token: response.token } : prev.authState
|
|
136
|
+
})), storageArea?.setItem(storageKey, JSON.stringify({ token: response.token }));
|
|
137
|
+
},
|
|
138
|
+
error: (error) => {
|
|
139
|
+
state.set("setRefreshStampedTokenError", { authState: { type: AuthStateType.ERROR, error } });
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
), subscribeToStateAndFetchCurrentUser = createInternalAction(
|
|
145
|
+
({ state }) => {
|
|
146
|
+
const { clientFactory, apiHost } = state.get().options, currentUser$ = state.observable.pipe(
|
|
147
|
+
rxjs.map(({ authState }) => authState),
|
|
148
|
+
rxjs.filter(
|
|
149
|
+
(authState) => authState.type === AuthStateType.LOGGED_IN && !authState.currentUser
|
|
150
|
+
),
|
|
151
|
+
rxjs.map((authState) => authState.token),
|
|
152
|
+
rxjs.distinctUntilChanged()
|
|
153
|
+
).pipe(
|
|
154
|
+
rxjs.map(
|
|
155
|
+
(token) => clientFactory({
|
|
156
|
+
apiVersion: DEFAULT_API_VERSION$1,
|
|
157
|
+
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
158
|
+
token,
|
|
159
|
+
ignoreBrowserTokenWarning: !0,
|
|
160
|
+
useProjectHostname: !1,
|
|
161
|
+
...apiHost && { apiHost }
|
|
162
|
+
})
|
|
163
|
+
),
|
|
164
|
+
rxjs.switchMap(
|
|
165
|
+
(client2) => client2.observable.request({ uri: "/users/me", method: "GET" })
|
|
166
|
+
)
|
|
167
|
+
);
|
|
168
|
+
return function() {
|
|
169
|
+
return currentUser$.subscribe({
|
|
170
|
+
next: (currentUser) => {
|
|
171
|
+
state.set("setCurrentUser", (prev) => ({
|
|
172
|
+
authState: prev.authState.type === AuthStateType.LOGGED_IN ? { ...prev.authState, currentUser } : prev.authState
|
|
173
|
+
}));
|
|
174
|
+
},
|
|
175
|
+
error: (error) => {
|
|
176
|
+
state.set("setError", { authState: { type: AuthStateType.ERROR, error } });
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
);
|
|
182
|
+
function getAuthCode(callbackUrl, locationHref) {
|
|
183
|
+
const loc = new URL(locationHref, DEFAULT_BASE), callbackLocation = callbackUrl ? new URL(callbackUrl, DEFAULT_BASE) : void 0, callbackLocationMatches = callbackLocation ? loc.pathname.toLowerCase().startsWith(callbackLocation.pathname.toLowerCase()) : !0, authCode = new URLSearchParams(loc.hash.slice(1)).get(AUTH_CODE_PARAM) || new URLSearchParams(loc.search).get(AUTH_CODE_PARAM);
|
|
184
|
+
return authCode && callbackLocationMatches ? authCode : null;
|
|
185
|
+
}
|
|
186
|
+
function getTokenFromStorage(storageArea, storageKey) {
|
|
187
|
+
if (!storageArea) return null;
|
|
188
|
+
const item = storageArea.getItem(storageKey);
|
|
189
|
+
if (item === null) return null;
|
|
190
|
+
try {
|
|
191
|
+
const parsed = JSON.parse(item);
|
|
192
|
+
if (typeof parsed != "object" || parsed === null || !("token" in parsed) || typeof parsed.token != "string")
|
|
193
|
+
throw new Error("Invalid stored auth data structure");
|
|
194
|
+
return parsed.token;
|
|
195
|
+
} catch {
|
|
196
|
+
return storageArea.removeItem(storageKey), null;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function getStorageEvents() {
|
|
200
|
+
return typeof window < "u" && typeof window.addEventListener == "function" ? rxjs.fromEvent(window, "storage") : rxjs.EMPTY;
|
|
201
|
+
}
|
|
202
|
+
function getDefaultStorage() {
|
|
203
|
+
try {
|
|
204
|
+
return typeof localStorage < "u" && typeof localStorage.getItem == "function" ? localStorage : void 0;
|
|
205
|
+
} catch {
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function getDefaultLocation() {
|
|
210
|
+
try {
|
|
211
|
+
return typeof location > "u" ? DEFAULT_BASE : typeof location.href == "string" ? location.href : DEFAULT_BASE;
|
|
212
|
+
} catch {
|
|
213
|
+
return DEFAULT_BASE;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const subscribeToStorageEventsAndSetToken = createInternalAction(
|
|
217
|
+
({ state }) => {
|
|
218
|
+
const { storageArea, storageKey } = state.get().options, tokenFromStorage$ = rxjs.defer(getStorageEvents).pipe(
|
|
219
|
+
rxjs.filter(
|
|
220
|
+
(e3) => e3.storageArea === storageArea && e3.key === storageKey
|
|
221
|
+
),
|
|
222
|
+
rxjs.map(() => getTokenFromStorage(storageArea, storageKey)),
|
|
223
|
+
rxjs.distinctUntilChanged()
|
|
224
|
+
);
|
|
225
|
+
return function() {
|
|
226
|
+
return tokenFromStorage$.subscribe((token) => {
|
|
227
|
+
state.set("updateTokenFromStorageEvent", {
|
|
228
|
+
authState: token ? { type: AuthStateType.LOGGED_IN, token, currentUser: null } : { type: AuthStateType.LOGGED_OUT, isDestroyingSession: !1 }
|
|
229
|
+
});
|
|
230
|
+
});
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
);
|
|
234
|
+
let tokenRefresherRunning = !1;
|
|
235
|
+
const authStore = {
|
|
236
|
+
name: "Auth",
|
|
237
|
+
getInitialState(instance) {
|
|
238
|
+
const {
|
|
239
|
+
apiHost,
|
|
240
|
+
callbackUrl,
|
|
241
|
+
providers: customProviders,
|
|
242
|
+
token: providedToken,
|
|
243
|
+
clientFactory = client.createClient,
|
|
244
|
+
initialLocationHref = getDefaultLocation(),
|
|
245
|
+
storageArea = getDefaultStorage()
|
|
246
|
+
} = instance.config.auth ?? {}, storageKey = "__sanity_auth_token";
|
|
247
|
+
let authState;
|
|
248
|
+
const token = getTokenFromStorage(storageArea, storageKey);
|
|
249
|
+
return providedToken ? authState = { type: AuthStateType.LOGGED_IN, token: providedToken, currentUser: null } : getAuthCode(callbackUrl, initialLocationHref) ? authState = { type: AuthStateType.LOGGING_IN, isExchangingToken: !1 } : token ? authState = { type: AuthStateType.LOGGED_IN, token, currentUser: null } : authState = { type: AuthStateType.LOGGED_OUT, isDestroyingSession: !1 }, {
|
|
250
|
+
authState,
|
|
251
|
+
options: {
|
|
252
|
+
apiHost,
|
|
253
|
+
callbackUrl,
|
|
254
|
+
customProviders,
|
|
255
|
+
providedToken,
|
|
256
|
+
clientFactory,
|
|
257
|
+
initialLocationHref,
|
|
258
|
+
storageKey,
|
|
259
|
+
storageArea
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
},
|
|
263
|
+
initialize() {
|
|
264
|
+
const stateSubscription = subscribeToStateAndFetchCurrentUser(this);
|
|
265
|
+
let storageEventsSubscription;
|
|
266
|
+
this.state.get().options?.storageArea && (storageEventsSubscription = subscribeToStorageEventsAndSetToken(this));
|
|
267
|
+
let refreshStampedTokenSubscription;
|
|
268
|
+
return tokenRefresherRunning || (tokenRefresherRunning = !0, refreshStampedTokenSubscription = refreshStampedToken(this)), () => {
|
|
269
|
+
stateSubscription.unsubscribe(), storageEventsSubscription?.unsubscribe(), refreshStampedTokenSubscription?.unsubscribe();
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
}, getCurrentUserState = createStateSourceAction(
|
|
273
|
+
authStore,
|
|
274
|
+
({ authState }) => authState.type === AuthStateType.LOGGED_IN ? authState.currentUser : null
|
|
275
|
+
), getTokenState = createStateSourceAction(
|
|
276
|
+
authStore,
|
|
277
|
+
({ authState }) => authState.type === AuthStateType.LOGGED_IN ? authState.token : null
|
|
278
|
+
), getLoginUrlsState = createStateSourceAction(
|
|
279
|
+
authStore,
|
|
280
|
+
({ providers }) => providers ?? null
|
|
281
|
+
), getAuthState = createStateSourceAction(authStore, ({ authState }) => authState), getDashboardOrganizationId = createStateSourceAction(
|
|
282
|
+
authStore,
|
|
283
|
+
({ dashboardContext }) => dashboardContext?.orgId
|
|
284
|
+
), fetchLoginUrls = createAction(authStore, ({ state }) => {
|
|
285
|
+
const { callbackUrl, clientFactory, apiHost, customProviders } = state.get().options, client2 = clientFactory({
|
|
286
|
+
apiVersion: DEFAULT_API_VERSION$1,
|
|
287
|
+
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
288
|
+
useProjectHostname: !1,
|
|
289
|
+
...apiHost && { apiHost }
|
|
290
|
+
});
|
|
291
|
+
return async function() {
|
|
292
|
+
const cachedProviders = state.get().providers;
|
|
293
|
+
if (cachedProviders) return cachedProviders;
|
|
294
|
+
const { providers: defaultProviders } = await client2.request({
|
|
295
|
+
uri: "/auth/providers",
|
|
296
|
+
tag: "fetch-providers"
|
|
297
|
+
});
|
|
298
|
+
let providers;
|
|
299
|
+
if (typeof customProviders == "function")
|
|
300
|
+
providers = await customProviders(defaultProviders);
|
|
301
|
+
else if (!customProviders?.length)
|
|
302
|
+
providers = defaultProviders;
|
|
303
|
+
else {
|
|
304
|
+
const customProviderUrls = new Set(customProviders.map((p2) => p2.url));
|
|
305
|
+
providers = defaultProviders.filter((official) => !customProviderUrls.has(official.url)).concat(customProviders);
|
|
306
|
+
}
|
|
307
|
+
const configuredProviders = providers.map((provider) => {
|
|
308
|
+
const url = new URL(provider.url), origin = new URL(
|
|
309
|
+
callbackUrl ? new URL(callbackUrl, new URL(getDefaultLocation()).origin).toString() : getDefaultLocation()
|
|
310
|
+
), hashParams = new URLSearchParams(origin.hash.slice(1));
|
|
311
|
+
return hashParams.delete("sid"), origin.hash = hashParams.toString(), origin.searchParams.delete("sid"), origin.searchParams.delete("url"), origin.searchParams.delete("error"), url.searchParams.set("origin", origin.toString()), url.searchParams.set("withSid", "true"), url.searchParams.set("type", "stampedToken"), { ...provider, url: url.toString() };
|
|
312
|
+
});
|
|
313
|
+
return state.set("fetchedLoginUrls", { providers: configuredProviders }), configuredProviders;
|
|
314
|
+
};
|
|
315
|
+
}), handleAuthCallback = createAction(authStore, ({ state }) => {
|
|
316
|
+
const { providedToken, callbackUrl, clientFactory, apiHost, storageArea, storageKey } = state.get().options;
|
|
317
|
+
return async function(locationHref = getDefaultLocation()) {
|
|
318
|
+
if (providedToken) return !1;
|
|
319
|
+
const { authState } = state.get();
|
|
320
|
+
if (authState.type === AuthStateType.LOGGING_IN && authState.isExchangingToken) return !1;
|
|
321
|
+
const authCode = getAuthCode(callbackUrl, locationHref);
|
|
322
|
+
if (!authCode) return !1;
|
|
323
|
+
const parsedUrl = new URL(locationHref);
|
|
324
|
+
let dashboardContext = {};
|
|
325
|
+
try {
|
|
326
|
+
const contextParam = parsedUrl.searchParams.get("_context") ?? "{}";
|
|
327
|
+
dashboardContext = JSON.parse(contextParam);
|
|
328
|
+
} catch (err) {
|
|
329
|
+
console.error("Failed to parse dashboard context:", err);
|
|
330
|
+
}
|
|
331
|
+
const { mode, env, orgId } = dashboardContext;
|
|
332
|
+
state.set("exchangeSessionForToken", {
|
|
333
|
+
authState: { type: AuthStateType.LOGGING_IN, isExchangingToken: !0 },
|
|
334
|
+
dashboardContext: { mode, env, orgId }
|
|
335
|
+
});
|
|
336
|
+
try {
|
|
337
|
+
const client2 = clientFactory({
|
|
338
|
+
apiVersion: DEFAULT_API_VERSION$1,
|
|
339
|
+
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
340
|
+
useProjectHostname: !1,
|
|
341
|
+
...apiHost && { apiHost }
|
|
342
|
+
}), { token } = await client2.request({
|
|
343
|
+
method: "GET",
|
|
344
|
+
uri: "/auth/fetch",
|
|
345
|
+
query: { sid: authCode },
|
|
346
|
+
tag: "fetch-token"
|
|
347
|
+
});
|
|
348
|
+
storageArea?.setItem(storageKey, JSON.stringify({ token })), state.set("setToken", { authState: { type: AuthStateType.LOGGED_IN, token, currentUser: null } });
|
|
349
|
+
const loc = new URL(locationHref);
|
|
350
|
+
return loc.hash = "", loc.searchParams.delete("sid"), loc.searchParams.delete("url"), loc.toString();
|
|
351
|
+
} catch (error) {
|
|
352
|
+
return state.set("exchangeSessionForTokenError", { authState: { type: AuthStateType.ERROR, error } }), !1;
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
}), logout = createAction(authStore, ({ state }) => {
|
|
356
|
+
const { clientFactory, apiHost, providedToken, storageArea, storageKey } = state.get().options;
|
|
357
|
+
return async function() {
|
|
358
|
+
if (providedToken) return;
|
|
359
|
+
const { authState } = state.get();
|
|
360
|
+
if (authState.type === AuthStateType.LOGGED_OUT && authState.isDestroyingSession) return;
|
|
361
|
+
const token = authState.type === AuthStateType.LOGGED_IN && authState.token;
|
|
362
|
+
try {
|
|
363
|
+
token && (state.set("loggingOut", {
|
|
364
|
+
authState: { type: AuthStateType.LOGGED_OUT, isDestroyingSession: !0 }
|
|
365
|
+
}), await clientFactory({
|
|
366
|
+
token,
|
|
367
|
+
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
368
|
+
apiVersion: DEFAULT_API_VERSION$1,
|
|
369
|
+
...apiHost && { apiHost },
|
|
370
|
+
useProjectHostname: !1
|
|
371
|
+
}).request({ uri: "/auth/logout", method: "POST" }));
|
|
372
|
+
} finally {
|
|
373
|
+
state.set("logoutSuccess", {
|
|
374
|
+
authState: { type: AuthStateType.LOGGED_OUT, isDestroyingSession: !1 }
|
|
375
|
+
}), storageArea?.removeItem(storageKey);
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
});
|
|
379
|
+
function getResourceId(documentResourceId) {
|
|
380
|
+
if (documentResourceId)
|
|
381
|
+
return documentResourceId.split(":")[1];
|
|
382
|
+
}
|
|
383
|
+
function parseBracketContent(content) {
|
|
384
|
+
const rangeMatch = content.match(/^(\d*):(\d*)$/);
|
|
385
|
+
if (rangeMatch) {
|
|
386
|
+
const startStr = rangeMatch[1], endStr = rangeMatch[2], start = startStr === "" ? "" : parseInt(startStr, 10), end = endStr === "" ? "" : parseInt(endStr, 10);
|
|
387
|
+
return [start, end];
|
|
388
|
+
}
|
|
389
|
+
const keyedMatch = content.match(/^_key==["'](.+)["']$/);
|
|
390
|
+
if (keyedMatch)
|
|
391
|
+
return { _key: keyedMatch[1] };
|
|
392
|
+
const index = parseInt(content, 10);
|
|
393
|
+
if (!isNaN(index))
|
|
394
|
+
return index;
|
|
395
|
+
throw new Error(`Invalid bracket content: \u201C[${content}]\u201D`);
|
|
396
|
+
}
|
|
397
|
+
function parseSegment(segment) {
|
|
398
|
+
const segments = [];
|
|
399
|
+
let idx = 0;
|
|
400
|
+
function pushIfNotEmpty(text) {
|
|
401
|
+
text && segments.push(text);
|
|
402
|
+
}
|
|
403
|
+
for (; idx < segment.length; ) {
|
|
404
|
+
const openIndex = segment.indexOf("[", idx);
|
|
405
|
+
if (openIndex === -1) {
|
|
406
|
+
const remaining = segment.slice(idx);
|
|
407
|
+
pushIfNotEmpty(remaining);
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
const before = segment.slice(idx, openIndex);
|
|
411
|
+
pushIfNotEmpty(before);
|
|
412
|
+
const closeIndex = segment.indexOf("]", openIndex);
|
|
413
|
+
if (closeIndex === -1)
|
|
414
|
+
throw new Error(`Unmatched "[" in segment: "${segment}"`);
|
|
415
|
+
const bracketContent = segment.slice(openIndex + 1, closeIndex);
|
|
416
|
+
segments.push(parseBracketContent(bracketContent)), idx = closeIndex + 1;
|
|
417
|
+
}
|
|
418
|
+
return segments;
|
|
419
|
+
}
|
|
420
|
+
function parsePath(path) {
|
|
421
|
+
const result = [];
|
|
422
|
+
let buffer = "", bracketDepth = 0;
|
|
423
|
+
for (let i2 = 0; i2 < path.length; i2++) {
|
|
424
|
+
const ch = path[i2];
|
|
425
|
+
ch === "[" ? (bracketDepth++, buffer += ch) : ch === "]" ? (bracketDepth--, buffer += ch) : ch === "." && bracketDepth === 0 ? buffer && (result.push(...parseSegment(buffer)), buffer = "") : buffer += ch;
|
|
426
|
+
}
|
|
427
|
+
return buffer && result.push(...parseSegment(buffer)), result;
|
|
428
|
+
}
|
|
429
|
+
function stringifyPath(path) {
|
|
430
|
+
let result = "";
|
|
431
|
+
for (let i2 = 0; i2 < path.length; i2++) {
|
|
432
|
+
const segment = path[i2];
|
|
433
|
+
if (typeof segment == "string")
|
|
434
|
+
result && (result += "."), result += segment;
|
|
435
|
+
else if (typeof segment == "number")
|
|
436
|
+
result += `[${segment}]`;
|
|
437
|
+
else if (Array.isArray(segment)) {
|
|
438
|
+
const [start, end] = segment, startStr = start === "" ? "" : String(start), endStr = end === "" ? "" : String(end);
|
|
439
|
+
result += `[${startStr}:${endStr}]`;
|
|
440
|
+
} else
|
|
441
|
+
result += `[_key=="${segment._key}"]`;
|
|
442
|
+
}
|
|
443
|
+
return result;
|
|
444
|
+
}
|
|
445
|
+
function jsonMatch(input, pathExpression) {
|
|
446
|
+
return matchRecursive(input, parsePath(pathExpression), []);
|
|
447
|
+
}
|
|
448
|
+
function matchRecursive(value, path, currentPath) {
|
|
449
|
+
if (path.length === 0)
|
|
450
|
+
return [{ value, path: currentPath }];
|
|
451
|
+
const [head, ...rest] = path;
|
|
452
|
+
if (typeof head == "string") {
|
|
453
|
+
if (value && typeof value == "object" && !Array.isArray(value)) {
|
|
454
|
+
const nextValue = value[head];
|
|
455
|
+
return matchRecursive(nextValue, rest, [...currentPath, head]);
|
|
456
|
+
}
|
|
457
|
+
return [];
|
|
458
|
+
}
|
|
459
|
+
if (typeof head == "number") {
|
|
460
|
+
if (Array.isArray(value)) {
|
|
461
|
+
const nextValue = value.at(head);
|
|
462
|
+
return matchRecursive(nextValue, rest, [...currentPath, head]);
|
|
463
|
+
}
|
|
464
|
+
return [];
|
|
465
|
+
}
|
|
466
|
+
if (Array.isArray(head)) {
|
|
467
|
+
if (!Array.isArray(value))
|
|
468
|
+
return [];
|
|
469
|
+
const [start, end] = head, startIndex = start === "" ? 0 : start, endIndex = end === "" ? value.length : end;
|
|
470
|
+
let results = [];
|
|
471
|
+
for (let i2 = startIndex; i2 < endIndex; i2++)
|
|
472
|
+
results = results.concat(matchRecursive(value[i2], rest, [...currentPath, i2]));
|
|
473
|
+
return results;
|
|
474
|
+
}
|
|
475
|
+
const arrIndex = getIndexForKey(value, head._key);
|
|
476
|
+
if (arrIndex === void 0 || !Array.isArray(value))
|
|
477
|
+
return [];
|
|
478
|
+
const nextVal = value[arrIndex];
|
|
479
|
+
return matchRecursive(nextVal, rest, [...currentPath, arrIndex]);
|
|
480
|
+
}
|
|
481
|
+
function generateArrayKey(length = 12) {
|
|
482
|
+
const numBytes = Math.ceil(length / 2), bytes = crypto.getRandomValues(new Uint8Array(numBytes));
|
|
483
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, length);
|
|
484
|
+
}
|
|
485
|
+
function memoize(fn) {
|
|
486
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
487
|
+
return (input) => {
|
|
488
|
+
if (!input || typeof input != "object") return fn(input);
|
|
489
|
+
const cached = cache.get(input);
|
|
490
|
+
if (cached) return cached;
|
|
491
|
+
const result = fn(input);
|
|
492
|
+
return cache.set(input, result), result;
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
const ensureArrayKeysDeep = memoize((input) => {
|
|
496
|
+
if (!input || typeof input != "object") return input;
|
|
497
|
+
if (Array.isArray(input))
|
|
498
|
+
return !input.length || typeof input[0] != "object" || input.every(types.isKeyedObject) ? input : input.map((item) => !item || typeof item != "object" ? item : types.isKeyedObject(item) ? ensureArrayKeysDeep(item) : { ...ensureArrayKeysDeep(item), _key: generateArrayKey() });
|
|
499
|
+
const entries = Object.entries(input).map(([key, value]) => [key, ensureArrayKeysDeep(value)]);
|
|
500
|
+
return entries.every(([key, value]) => input[key] === value) ? input : Object.fromEntries(entries);
|
|
501
|
+
});
|
|
502
|
+
function set(input, pathExpressionValues) {
|
|
503
|
+
const result = Object.entries(pathExpressionValues).flatMap(
|
|
504
|
+
([pathExpression, replacementValue]) => jsonMatch(input, pathExpression).map((matchEntry) => ({
|
|
505
|
+
...matchEntry,
|
|
506
|
+
replacementValue
|
|
507
|
+
}))
|
|
508
|
+
).reduce((acc, { path, replacementValue }) => setDeep(acc, path, replacementValue), input);
|
|
509
|
+
return ensureArrayKeysDeep(result);
|
|
510
|
+
}
|
|
511
|
+
function setIfMissing(input, pathExpressionValues) {
|
|
512
|
+
const result = Object.entries(pathExpressionValues).flatMap(([pathExpression, replacementValue]) => jsonMatch(input, pathExpression).map((matchEntry) => ({
|
|
513
|
+
...matchEntry,
|
|
514
|
+
replacementValue
|
|
515
|
+
}))).filter((matchEntry) => matchEntry.value === null || matchEntry.value === void 0).reduce((acc, { path, replacementValue }) => setDeep(acc, path, replacementValue), input);
|
|
516
|
+
return ensureArrayKeysDeep(result);
|
|
517
|
+
}
|
|
518
|
+
function unset(input, pathExpressions) {
|
|
519
|
+
const result = pathExpressions.flatMap((pathExpression) => jsonMatch(input, pathExpression)).reduce((acc, { path }) => unsetDeep(acc, path), input);
|
|
520
|
+
return ensureArrayKeysDeep(result);
|
|
521
|
+
}
|
|
522
|
+
const operations = ["before", "after", "replace"];
|
|
523
|
+
function insert(input, insertPatch) {
|
|
524
|
+
const operation = operations.find((op) => op in insertPatch);
|
|
525
|
+
if (!operation) return input;
|
|
526
|
+
const { items } = insertPatch, pathExpression = insertPatch[operation];
|
|
527
|
+
if (typeof pathExpression != "string") return input;
|
|
528
|
+
function normalizeIndex(index, parentLength) {
|
|
529
|
+
switch (operation) {
|
|
530
|
+
case "before":
|
|
531
|
+
return index < 0 ? parentLength : index;
|
|
532
|
+
case "after":
|
|
533
|
+
return index < 0 ? -1 : index;
|
|
534
|
+
default:
|
|
535
|
+
return index < 0 ? parentLength + index : index;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
539
|
+
jsonMatch(input, pathExpression).map(({ path }) => {
|
|
540
|
+
const segment = path[path.length - 1];
|
|
541
|
+
let index;
|
|
542
|
+
if (types.isKeySegment(segment) ? index = getIndexForKey(input, segment._key) : typeof segment == "number" && (index = segment), typeof index != "number") return null;
|
|
543
|
+
const parentPath = path.slice(0, path.length - 1), parent = getDeep(input, parentPath);
|
|
544
|
+
if (!Array.isArray(parent)) return null;
|
|
545
|
+
const normalizedIndex = normalizeIndex(index, parent.length);
|
|
546
|
+
return { parent, parentPath, normalizedIndex };
|
|
547
|
+
}).filter(isNonNullable).forEach(({ parent, parentPath, normalizedIndex }) => {
|
|
548
|
+
grouped.has(parent) ? grouped.get(parent).indexes.push(normalizedIndex) : grouped.set(parent, { array: parent, pathToArray: parentPath, indexes: [normalizedIndex] });
|
|
549
|
+
});
|
|
550
|
+
const result = Array.from(grouped.values()).map((entry) => ({
|
|
551
|
+
...entry,
|
|
552
|
+
indexes: entry.indexes.sort((a2, b2) => a2 - b2)
|
|
553
|
+
})).reduce((acc, { array, indexes, pathToArray }) => {
|
|
554
|
+
switch (operation) {
|
|
555
|
+
case "before": {
|
|
556
|
+
const firstIndex = indexes[0];
|
|
557
|
+
return setDeep(acc, pathToArray, [
|
|
558
|
+
...array.slice(0, firstIndex),
|
|
559
|
+
...items,
|
|
560
|
+
...array.slice(firstIndex)
|
|
561
|
+
]);
|
|
562
|
+
}
|
|
563
|
+
case "after": {
|
|
564
|
+
const lastIndex = indexes[indexes.length - 1] + 1;
|
|
565
|
+
return setDeep(acc, pathToArray, [
|
|
566
|
+
...array.slice(0, lastIndex),
|
|
567
|
+
...items,
|
|
568
|
+
...array.slice(lastIndex)
|
|
569
|
+
]);
|
|
570
|
+
}
|
|
571
|
+
// default to 'replace' behavior
|
|
572
|
+
default: {
|
|
573
|
+
const firstIndex = indexes[0], indexSet = new Set(indexes);
|
|
574
|
+
return setDeep(acc, pathToArray, [
|
|
575
|
+
...array.slice(0, firstIndex),
|
|
576
|
+
...items,
|
|
577
|
+
...array.slice(firstIndex).filter((_2, idx) => !indexSet.has(idx + firstIndex))
|
|
578
|
+
]);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}, input);
|
|
582
|
+
return ensureArrayKeysDeep(result);
|
|
583
|
+
}
|
|
584
|
+
function inc(input, pathExpressionValues) {
|
|
585
|
+
const result = Object.entries(pathExpressionValues).flatMap(
|
|
586
|
+
([pathExpression, valueToAdd]) => jsonMatch(input, pathExpression).map((matchEntry) => ({
|
|
587
|
+
...matchEntry,
|
|
588
|
+
valueToAdd
|
|
589
|
+
}))
|
|
590
|
+
).filter(
|
|
591
|
+
(matchEntry) => typeof matchEntry.value == "number"
|
|
592
|
+
).reduce((acc, { path, value, valueToAdd }) => setDeep(acc, path, value + valueToAdd), input);
|
|
593
|
+
return ensureArrayKeysDeep(result);
|
|
594
|
+
}
|
|
595
|
+
function dec(input, pathExpressionValues) {
|
|
596
|
+
const result = inc(
|
|
597
|
+
input,
|
|
598
|
+
Object.fromEntries(
|
|
599
|
+
Object.entries(pathExpressionValues).filter(([, value]) => typeof value == "number").map(([key, value]) => [key, -value])
|
|
600
|
+
)
|
|
601
|
+
);
|
|
602
|
+
return ensureArrayKeysDeep(result);
|
|
603
|
+
}
|
|
604
|
+
function diffMatchPatch(input, pathExpressionValues) {
|
|
605
|
+
const result = Object.entries(pathExpressionValues).flatMap(([pathExpression, dmp]) => jsonMatch(input, pathExpression).map((m2) => ({ ...m2, dmp }))).filter((i2) => i2.value !== void 0).map(({ path, value, dmp }) => {
|
|
606
|
+
if (typeof value != "string")
|
|
607
|
+
throw new Error(
|
|
608
|
+
`Can't diff-match-patch \`${JSON.stringify(value)}\` at path \`${stringifyPath(path)}\`, because it is not a string`
|
|
609
|
+
);
|
|
610
|
+
const [nextValue] = diffMatchPatch$1.applyPatches(diffMatchPatch$1.parsePatch(dmp), value);
|
|
611
|
+
return { path, value: nextValue };
|
|
612
|
+
}).reduce((acc, { path, value }) => setDeep(acc, path, value), input);
|
|
613
|
+
return ensureArrayKeysDeep(result);
|
|
614
|
+
}
|
|
615
|
+
function ifRevisionID(input, revisionId) {
|
|
616
|
+
const inputRev = typeof input == "object" && input && "_rev" in input && typeof input._rev == "string" ? input._rev : void 0;
|
|
617
|
+
if (typeof inputRev != "string")
|
|
618
|
+
throw new Error("Patch specified `ifRevisionID` but could not find document's revision ID.");
|
|
619
|
+
if (revisionId !== inputRev)
|
|
620
|
+
throw new Error(
|
|
621
|
+
`Patch's \`ifRevisionID\` \`${revisionId}\` does not match document's revision ID \`${inputRev}\``
|
|
622
|
+
);
|
|
623
|
+
return input;
|
|
624
|
+
}
|
|
625
|
+
function isNonNullable(t2) {
|
|
626
|
+
return t2 != null;
|
|
627
|
+
}
|
|
628
|
+
const indexCache = /* @__PURE__ */ new WeakMap();
|
|
629
|
+
function getIndexForKey(input, key) {
|
|
630
|
+
if (!Array.isArray(input)) return;
|
|
631
|
+
const cached = indexCache.get(input);
|
|
632
|
+
if (cached) return cached[key];
|
|
633
|
+
const lookup = input.reduce((acc, next, index) => (typeof next?._key == "string" && (acc[next._key] = index), acc), {});
|
|
634
|
+
return indexCache.set(input, lookup), lookup[key];
|
|
635
|
+
}
|
|
636
|
+
function getDeep(input, path) {
|
|
637
|
+
const [currentSegment, ...restOfPath] = path;
|
|
638
|
+
if (currentSegment === void 0) return input;
|
|
639
|
+
if (typeof input != "object" || input === null) return;
|
|
640
|
+
let key;
|
|
641
|
+
if (types.isKeySegment(currentSegment) ? key = getIndexForKey(input, currentSegment._key) : (typeof currentSegment == "string" || typeof currentSegment == "number") && (key = currentSegment), key === void 0) return;
|
|
642
|
+
const nestedInput = typeof key == "number" && Array.isArray(input) ? input.at(key) : input[key];
|
|
643
|
+
return getDeep(nestedInput, restOfPath);
|
|
644
|
+
}
|
|
645
|
+
function setDeep(input, path, value) {
|
|
646
|
+
const [currentSegment, ...restOfPath] = path;
|
|
647
|
+
if (currentSegment === void 0) return value;
|
|
648
|
+
if (typeof input != "object" || input === null) {
|
|
649
|
+
if (typeof currentSegment == "string")
|
|
650
|
+
return { [currentSegment]: setDeep(null, restOfPath, value) };
|
|
651
|
+
let index;
|
|
652
|
+
if (types.isKeySegment(currentSegment))
|
|
653
|
+
index = 0;
|
|
654
|
+
else if (typeof currentSegment == "number" && currentSegment >= 0)
|
|
655
|
+
index = currentSegment;
|
|
656
|
+
else
|
|
657
|
+
return input;
|
|
658
|
+
return [
|
|
659
|
+
// fill until index
|
|
660
|
+
...Array.from({ length: index }).fill(null),
|
|
661
|
+
// then set deep here
|
|
662
|
+
setDeep(null, restOfPath, value)
|
|
663
|
+
];
|
|
664
|
+
}
|
|
665
|
+
if (Array.isArray(input)) {
|
|
666
|
+
let index;
|
|
667
|
+
return types.isKeySegment(currentSegment) ? index = getIndexForKey(input, currentSegment._key) : typeof currentSegment == "number" && (index = currentSegment < 0 ? input.length + currentSegment : currentSegment), index === void 0 ? input : index in input ? input.map(
|
|
668
|
+
(nestedInput, i2) => i2 === index ? setDeep(nestedInput, restOfPath, value) : nestedInput
|
|
669
|
+
) : [
|
|
670
|
+
...input,
|
|
671
|
+
...Array.from({ length: index - input.length }).fill(null),
|
|
672
|
+
setDeep(null, restOfPath, value)
|
|
673
|
+
];
|
|
674
|
+
}
|
|
675
|
+
return typeof currentSegment == "object" ? input : currentSegment in input ? Object.fromEntries(
|
|
676
|
+
Object.entries(input).map(
|
|
677
|
+
([key, nestedInput]) => key === currentSegment ? [key, setDeep(nestedInput, restOfPath, value)] : [key, nestedInput]
|
|
678
|
+
)
|
|
679
|
+
) : { ...input, [currentSegment]: setDeep(null, restOfPath, value) };
|
|
680
|
+
}
|
|
681
|
+
function unsetDeep(input, path) {
|
|
682
|
+
const [currentSegment, ...restOfPath] = path;
|
|
683
|
+
if (currentSegment === void 0 || typeof input != "object" || input === null) return input;
|
|
684
|
+
let _segment;
|
|
685
|
+
if (types.isKeySegment(currentSegment) ? _segment = getIndexForKey(input, currentSegment._key) : (typeof currentSegment == "string" || typeof currentSegment == "number") && (_segment = currentSegment), _segment === void 0) return input;
|
|
686
|
+
let segment = _segment;
|
|
687
|
+
return typeof segment == "number" && Array.isArray(input) && (segment = segment < 0 ? input.length + segment : segment), segment in input ? restOfPath.length ? Array.isArray(input) ? input.map(
|
|
688
|
+
(nestedInput, index) => index === segment ? unsetDeep(nestedInput, restOfPath) : nestedInput
|
|
689
|
+
) : Object.fromEntries(
|
|
690
|
+
Object.entries(input).map(
|
|
691
|
+
([key, value]) => key === segment ? [key, unsetDeep(value, restOfPath)] : [key, value]
|
|
692
|
+
)
|
|
693
|
+
) : Array.isArray(input) ? input.filter((_nestedInput, index) => index !== segment) : Object.fromEntries(Object.entries(input).filter(([key]) => key !== segment.toString())) : input;
|
|
694
|
+
}
|
|
695
|
+
const DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.sdk", clientStore = {
|
|
696
|
+
name: "clientStore",
|
|
697
|
+
getInitialState: (instance) => {
|
|
698
|
+
const { identity, config } = instance, defaultClient = client.createClient({
|
|
699
|
+
projectId: identity.projectId,
|
|
700
|
+
dataset: identity.dataset,
|
|
701
|
+
token: config?.auth?.token,
|
|
702
|
+
useCdn: !1,
|
|
703
|
+
apiVersion: DEFAULT_API_VERSION,
|
|
704
|
+
requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,
|
|
705
|
+
...config?.auth?.apiHost ? { apiHost: config.auth.apiHost } : {}
|
|
706
|
+
}), defaultGlobalClient = client.createClient({
|
|
707
|
+
token: config?.auth?.token,
|
|
708
|
+
useCdn: !1,
|
|
709
|
+
apiVersion: "vX",
|
|
710
|
+
// Many global APIs are only available under this version, we may need to support other versions in the future
|
|
711
|
+
useProjectHostname: !1,
|
|
712
|
+
requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,
|
|
713
|
+
...config?.auth?.apiHost ? { apiHost: config.auth.apiHost } : {}
|
|
714
|
+
});
|
|
715
|
+
return {
|
|
716
|
+
defaultClient,
|
|
717
|
+
defaultGlobalClient
|
|
718
|
+
};
|
|
719
|
+
},
|
|
720
|
+
initialize() {
|
|
721
|
+
const authEventSubscription = subscribeToAuthEvents(this);
|
|
722
|
+
return () => {
|
|
723
|
+
authEventSubscription.unsubscribe();
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
}, receiveToken = (prev, token) => {
|
|
727
|
+
const newDefaultClient = prev.defaultClient.withConfig({
|
|
728
|
+
token
|
|
729
|
+
}), newGlobalClient = prev.defaultGlobalClient.withConfig({
|
|
730
|
+
token
|
|
731
|
+
});
|
|
732
|
+
return {
|
|
733
|
+
defaultClient: newDefaultClient,
|
|
734
|
+
defaultGlobalClient: newGlobalClient
|
|
735
|
+
};
|
|
736
|
+
}, subscribeToAuthEvents = createInternalAction(
|
|
737
|
+
({ instance, state }) => () => getTokenState(instance).observable.subscribe((newToken) => {
|
|
738
|
+
state.set("receiveToken", (prev) => receiveToken(prev, newToken ?? void 0));
|
|
739
|
+
})
|
|
740
|
+
), optionsCache = /* @__PURE__ */ new WeakMap(), defaultClientSelector = (state, options) => options?.scope === "global" ? state.defaultGlobalClient : state.defaultClient, memoizedOptionsSelector = reselect.createSelector(
|
|
741
|
+
[defaultClientSelector, (_state, options) => options],
|
|
742
|
+
(client2, options) => {
|
|
743
|
+
let nestedCache = optionsCache.get(client2);
|
|
744
|
+
nestedCache || (nestedCache = /* @__PURE__ */ new Map(), optionsCache.set(client2, nestedCache));
|
|
745
|
+
const key = JSON.stringify(options);
|
|
746
|
+
return nestedCache.get(key) || (nestedCache.set(key, options), options);
|
|
747
|
+
}
|
|
748
|
+
), clientSelector = reselect.createSelector(
|
|
749
|
+
[defaultClientSelector, memoizedOptionsSelector],
|
|
750
|
+
(client2, options) => client2.withConfig(options)
|
|
751
|
+
), getClient = createAction(
|
|
752
|
+
clientStore,
|
|
753
|
+
({ state }) => (options) => clientSelector(state.get(), options)
|
|
754
|
+
), getClientState = createStateSourceAction(clientStore, clientSelector), comlinkControllerStore = {
|
|
755
|
+
name: "connectionStore",
|
|
756
|
+
getInitialState: () => ({
|
|
757
|
+
controller: null,
|
|
758
|
+
controllerOrigin: null,
|
|
759
|
+
channels: /* @__PURE__ */ new Map()
|
|
760
|
+
}),
|
|
761
|
+
initialize() {
|
|
762
|
+
return () => {
|
|
763
|
+
destroyController(this);
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
}, destroyController = createInternalAction(
|
|
767
|
+
({ state }) => () => {
|
|
768
|
+
const { controller } = state.get();
|
|
769
|
+
controller && (controller.destroy(), state.set("destroyController", {
|
|
770
|
+
controller: null,
|
|
771
|
+
channels: /* @__PURE__ */ new Map()
|
|
772
|
+
}));
|
|
773
|
+
}
|
|
774
|
+
), getOrCreateChannel = createAction(comlinkControllerStore, ({ state }) => (options) => {
|
|
775
|
+
const controller = state.get().controller;
|
|
776
|
+
if (!controller)
|
|
777
|
+
throw new Error("Controller must be initialized before using or creating channels");
|
|
778
|
+
const channels = state.get().channels, existing = channels.get(options.name);
|
|
779
|
+
if (existing) {
|
|
780
|
+
if (!lodashEs.isEqual(existing.options, options))
|
|
781
|
+
throw new Error(`Channel "${options.name}" already exists with different options`);
|
|
782
|
+
return state.set("incrementChannelRefCount", {
|
|
783
|
+
channels: new Map(channels).set(options.name, {
|
|
784
|
+
...existing,
|
|
785
|
+
refCount: existing.refCount + 1
|
|
786
|
+
})
|
|
787
|
+
}), existing.channel.start(), existing.channel;
|
|
788
|
+
}
|
|
789
|
+
const channel = controller.createChannel(options);
|
|
790
|
+
return channel.start(), state.set("createChannel", {
|
|
791
|
+
channels: new Map(channels).set(options.name, {
|
|
792
|
+
channel,
|
|
793
|
+
options,
|
|
794
|
+
refCount: 1
|
|
795
|
+
})
|
|
796
|
+
}), channel;
|
|
797
|
+
}), getOrCreateController = createAction(comlinkControllerStore, ({ state, instance }) => (targetOrigin) => {
|
|
798
|
+
const { controller, controllerOrigin } = state.get();
|
|
799
|
+
if (controller && controllerOrigin === targetOrigin)
|
|
800
|
+
return controller;
|
|
801
|
+
controller && destroyController({ state, instance });
|
|
802
|
+
const newController = comlink.createController({ targetOrigin });
|
|
803
|
+
return state.set("initializeController", {
|
|
804
|
+
controllerOrigin: targetOrigin,
|
|
805
|
+
controller: newController
|
|
806
|
+
}), newController;
|
|
807
|
+
}), releaseChannel = createAction(comlinkControllerStore, ({ state }) => (name) => {
|
|
808
|
+
const channels = state.get().channels, channelEntry = channels.get(name);
|
|
809
|
+
if (channelEntry) {
|
|
810
|
+
const newRefCount = channelEntry.refCount === 0 ? 0 : channelEntry.refCount - 1;
|
|
811
|
+
newRefCount === 0 ? (channelEntry.channel.stop(), channels.delete(name), state.set("releaseChannel", { channels: new Map(channels) })) : state.set("releaseChannel", {
|
|
812
|
+
channels: new Map(channels).set(name, {
|
|
813
|
+
...channelEntry,
|
|
814
|
+
refCount: newRefCount
|
|
815
|
+
})
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
}), comlinkNodeStore = {
|
|
819
|
+
name: "nodeStore",
|
|
820
|
+
getInitialState: () => ({
|
|
821
|
+
nodes: /* @__PURE__ */ new Map()
|
|
822
|
+
}),
|
|
823
|
+
initialize() {
|
|
824
|
+
return () => {
|
|
825
|
+
this.state.get().nodes.forEach(({ node }) => {
|
|
826
|
+
node.stop();
|
|
827
|
+
});
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
}, getOrCreateNode = createAction(comlinkNodeStore, ({ state }) => (options) => {
|
|
831
|
+
const nodes = state.get().nodes, existing = nodes.get(options.name);
|
|
832
|
+
if (existing) {
|
|
833
|
+
if (!lodashEs.isEqual(existing.options, options))
|
|
834
|
+
throw new Error(`Node "${options.name}" already exists with different options`);
|
|
835
|
+
return state.set("incrementNodeRefCount", {
|
|
836
|
+
nodes: new Map(nodes).set(options.name, {
|
|
837
|
+
...existing,
|
|
838
|
+
refCount: existing.refCount + 1
|
|
839
|
+
})
|
|
840
|
+
}), existing.node.start(), existing.node;
|
|
841
|
+
}
|
|
842
|
+
const node = comlink.createNode(options);
|
|
843
|
+
return node.start(), nodes.set(options.name, { node, options, refCount: 1 }), state.set("createNode", { nodes }), node;
|
|
844
|
+
}), releaseNode = createAction(comlinkNodeStore, ({ state }) => (name) => {
|
|
845
|
+
const nodes = state.get().nodes, nodeEntry = nodes.get(name);
|
|
846
|
+
if (nodeEntry) {
|
|
847
|
+
const newRefCount = nodeEntry.refCount === 0 ? 0 : nodeEntry.refCount - 1;
|
|
848
|
+
newRefCount === 0 ? (nodeEntry.node.stop(), nodes.delete(name), state.set("releaseNode", { nodes: new Map(nodes) })) : state.set("releaseNode", {
|
|
849
|
+
nodes: new Map(nodes).set(name, {
|
|
850
|
+
...nodeEntry,
|
|
851
|
+
refCount: newRefCount
|
|
852
|
+
})
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
});
|
|
856
|
+
function getPublishedId(id) {
|
|
857
|
+
const draftsPrefix = "drafts.";
|
|
858
|
+
return id.startsWith(draftsPrefix) ? id.slice(draftsPrefix.length) : id;
|
|
859
|
+
}
|
|
860
|
+
function getDraftId(id) {
|
|
861
|
+
const draftsPrefix = "drafts.";
|
|
862
|
+
return id.startsWith(draftsPrefix) ? id : `${draftsPrefix}${id}`;
|
|
863
|
+
}
|
|
864
|
+
function insecureRandomId() {
|
|
865
|
+
return Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
|
|
866
|
+
}
|
|
867
|
+
function createFetcherStore({
|
|
868
|
+
name,
|
|
869
|
+
fetcher: getObservable,
|
|
870
|
+
getKey,
|
|
871
|
+
fetchThrottleInternal = 1e3,
|
|
872
|
+
stateExpirationDelay = 5e3
|
|
873
|
+
}) {
|
|
874
|
+
const store = {
|
|
875
|
+
name,
|
|
876
|
+
getInitialState: () => ({
|
|
877
|
+
stateByParams: {}
|
|
878
|
+
}),
|
|
879
|
+
initialize() {
|
|
880
|
+
const subscription = subscribeToSubscriptionsAndFetch(this);
|
|
881
|
+
return () => subscription.unsubscribe();
|
|
882
|
+
}
|
|
883
|
+
}, subscribeToSubscriptionsAndFetch = createInternalAction(
|
|
884
|
+
({ instance, state }) => function() {
|
|
885
|
+
const factoryFn = getObservable(instance);
|
|
886
|
+
return state.observable.pipe(
|
|
887
|
+
// Map the state to an array of [serialized, entry] pairs.
|
|
888
|
+
operators.switchMap((s2) => {
|
|
889
|
+
const entries = Object.entries(s2.stateByParams);
|
|
890
|
+
return entries.length > 0 ? rxjs.from(entries) : rxjs.EMPTY;
|
|
891
|
+
}),
|
|
892
|
+
// Group by the serialized key.
|
|
893
|
+
operators.groupBy(([key]) => key),
|
|
894
|
+
operators.mergeMap(
|
|
895
|
+
(group$) => group$.pipe(
|
|
896
|
+
// Emit an initial value for pairwise comparisons.
|
|
897
|
+
operators.startWith([
|
|
898
|
+
group$.key,
|
|
899
|
+
void 0
|
|
900
|
+
]),
|
|
901
|
+
operators.pairwise(),
|
|
902
|
+
// Trigger only when the subscriptions array grows.
|
|
903
|
+
operators.filter(([[, prevEntry], [, currEntry]]) => {
|
|
904
|
+
const prevSubs = prevEntry?.subscriptions ?? [];
|
|
905
|
+
return (currEntry?.subscriptions ?? []).length > prevSubs.length;
|
|
906
|
+
}),
|
|
907
|
+
operators.map(([, [, currEntry]]) => currEntry),
|
|
908
|
+
// Only trigger if we haven't fetched recently.
|
|
909
|
+
operators.filter((entry) => {
|
|
910
|
+
const lastFetch = entry?.lastFetchInitiatedAt;
|
|
911
|
+
return lastFetch ? Date.now() - new Date(lastFetch).getTime() >= fetchThrottleInternal : !0;
|
|
912
|
+
}),
|
|
913
|
+
operators.switchMap((entry) => entry ? (state.set(
|
|
914
|
+
"setLastFetchInitiatedAt",
|
|
915
|
+
(prev) => ({
|
|
916
|
+
stateByParams: {
|
|
917
|
+
...prev.stateByParams,
|
|
918
|
+
[entry.key]: {
|
|
919
|
+
...entry,
|
|
920
|
+
...prev.stateByParams[entry.key],
|
|
921
|
+
lastFetchInitiatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
})
|
|
925
|
+
), factoryFn(...entry.params).pipe(
|
|
926
|
+
// the `createStateSourceAction` util requires the update
|
|
927
|
+
// to
|
|
928
|
+
operators.delay(0, rxjs.asapScheduler),
|
|
929
|
+
operators.tap(
|
|
930
|
+
(data) => state.set("setData", (prev) => ({
|
|
931
|
+
stateByParams: {
|
|
932
|
+
...prev.stateByParams,
|
|
933
|
+
[entry.key]: {
|
|
934
|
+
...lodashEs.omit(entry, "error"),
|
|
935
|
+
...lodashEs.omit(prev.stateByParams[entry.key], "error"),
|
|
936
|
+
data
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
}))
|
|
940
|
+
),
|
|
941
|
+
operators.catchError((error) => (state.set("setError", (prev) => ({
|
|
942
|
+
stateByParams: {
|
|
943
|
+
...prev.stateByParams,
|
|
944
|
+
[entry.key]: {
|
|
945
|
+
...entry,
|
|
946
|
+
...prev.stateByParams[entry.key],
|
|
947
|
+
error
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
})), rxjs.EMPTY))
|
|
951
|
+
)) : rxjs.EMPTY)
|
|
952
|
+
)
|
|
953
|
+
)
|
|
954
|
+
).subscribe({
|
|
955
|
+
error: (error) => state.set("setError", { error })
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
), getState2 = createStateSourceAction(store, {
|
|
959
|
+
selector: ({ stateByParams, error }, ...params) => {
|
|
960
|
+
if (error) throw error;
|
|
961
|
+
const key = getKey(...params), entry = stateByParams[key];
|
|
962
|
+
if (entry?.error) throw entry.error;
|
|
963
|
+
return entry?.data;
|
|
964
|
+
},
|
|
965
|
+
onSubscribe: ({ state }, ...params) => {
|
|
966
|
+
const subscriptionId = insecureRandomId(), key = getKey(...params);
|
|
967
|
+
return state.set("addSubscription", (prev) => ({
|
|
968
|
+
stateByParams: {
|
|
969
|
+
...prev.stateByParams,
|
|
970
|
+
[key]: {
|
|
971
|
+
...prev.stateByParams[key],
|
|
972
|
+
key,
|
|
973
|
+
params: prev.stateByParams[key]?.params || params,
|
|
974
|
+
subscriptions: [...prev.stateByParams[key]?.subscriptions || [], subscriptionId]
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
})), () => {
|
|
978
|
+
setTimeout(() => {
|
|
979
|
+
state.set("removeSubscription", (prev) => {
|
|
980
|
+
const entry = prev.stateByParams[key];
|
|
981
|
+
if (!entry) return prev;
|
|
982
|
+
const newSubs = (entry.subscriptions || []).filter((id) => id !== subscriptionId);
|
|
983
|
+
return newSubs.length === 0 ? { stateByParams: lodashEs.omit(prev.stateByParams, key) } : {
|
|
984
|
+
stateByParams: {
|
|
985
|
+
...prev.stateByParams,
|
|
986
|
+
[key]: {
|
|
987
|
+
...entry,
|
|
988
|
+
subscriptions: newSubs
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
});
|
|
993
|
+
}, stateExpirationDelay);
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
}), resolveState = createAction(store, () => function(...params) {
|
|
997
|
+
return rxjs.firstValueFrom(
|
|
998
|
+
getState2(this, ...params).observable.pipe(operators.first((i2) => i2 !== void 0))
|
|
999
|
+
);
|
|
1000
|
+
});
|
|
1001
|
+
return { getState: getState2, resolveState };
|
|
1002
|
+
}
|
|
1003
|
+
const datasets = createFetcherStore({
|
|
1004
|
+
name: "Datasets",
|
|
1005
|
+
getKey: () => "datasets",
|
|
1006
|
+
fetcher: (instance) => () => getClientState(instance, { apiVersion: "vX", scope: "project" }).observable.pipe(
|
|
1007
|
+
rxjs.switchMap((client2) => client2.observable.datasets.list())
|
|
1008
|
+
)
|
|
1009
|
+
}), getDatasetsState = datasets.getState, resolveDatasets = datasets.resolveState, isSanityMutatePatch = (value) => !(typeof value != "object" || !value || !("type" in value) || typeof value.type != "string" || value.type !== "patch" || !("id" in value) || typeof value.id != "string" || !("patches" in value) || !Array.isArray(value.patches));
|
|
1010
|
+
function createDocument(doc) {
|
|
1011
|
+
return {
|
|
1012
|
+
type: "document.create",
|
|
1013
|
+
...doc._id && { documentId: doc._id },
|
|
1014
|
+
documentType: doc._type,
|
|
1015
|
+
...doc.resourceId && { resourceId: doc.resourceId }
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
function deleteDocument(doc) {
|
|
1019
|
+
return {
|
|
1020
|
+
type: "document.delete",
|
|
1021
|
+
documentId: getPublishedId(doc._id),
|
|
1022
|
+
...doc.resourceId && { resourceId: doc.resourceId }
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
function convertSanityMutatePatch(sanityPatchMutation) {
|
|
1026
|
+
const encoded = mutate.SanityEncoder.encode(sanityPatchMutation);
|
|
1027
|
+
return {
|
|
1028
|
+
documentId: sanityPatchMutation.id,
|
|
1029
|
+
type: "document.edit",
|
|
1030
|
+
patches: encoded.map((i2) => {
|
|
1031
|
+
const copy = { ...i2.patch };
|
|
1032
|
+
return "id" in copy && delete copy.id, copy;
|
|
1033
|
+
})
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
function editDocument(doc, patches) {
|
|
1037
|
+
return isSanityMutatePatch(doc) ? convertSanityMutatePatch(doc) : {
|
|
1038
|
+
type: "document.edit",
|
|
1039
|
+
documentId: getPublishedId(doc._id),
|
|
1040
|
+
...patches && { patches: Array.isArray(patches) ? patches : [patches] },
|
|
1041
|
+
...doc.resourceId && { resourceId: doc.resourceId }
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
function publishDocument(doc) {
|
|
1045
|
+
return {
|
|
1046
|
+
type: "document.publish",
|
|
1047
|
+
documentId: getPublishedId(doc._id),
|
|
1048
|
+
...doc.resourceId && { resourceId: doc.resourceId }
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
function unpublishDocument(doc) {
|
|
1052
|
+
return {
|
|
1053
|
+
type: "document.unpublish",
|
|
1054
|
+
documentId: getPublishedId(doc._id),
|
|
1055
|
+
...doc.resourceId && { resourceId: doc.resourceId }
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
function discardDocument(doc) {
|
|
1059
|
+
return {
|
|
1060
|
+
type: "document.discard",
|
|
1061
|
+
documentId: getPublishedId(doc._id),
|
|
1062
|
+
...doc.resourceId && { resourceId: doc.resourceId }
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
const DOCUMENT_STATE_CLEAR_DELAY = 1e3, INITIAL_OUTGOING_THROTTLE_TIME = 1e3, API_VERSION$2 = "vX", patchOperations = {
|
|
1066
|
+
ifRevisionID,
|
|
1067
|
+
set,
|
|
1068
|
+
setIfMissing,
|
|
1069
|
+
unset,
|
|
1070
|
+
inc,
|
|
1071
|
+
dec,
|
|
1072
|
+
insert,
|
|
1073
|
+
diffMatchPatch
|
|
1074
|
+
};
|
|
1075
|
+
function getId(id) {
|
|
1076
|
+
return !id || typeof id != "string" ? crypto.randomUUID() : id.endsWith(".") ? `${id}${crypto.randomUUID()}` : id;
|
|
1077
|
+
}
|
|
1078
|
+
function getDocumentIds(selection) {
|
|
1079
|
+
if ("id" in selection) {
|
|
1080
|
+
const ids = (Array.isArray(selection.id) ? selection.id : [selection.id]).filter((id) => typeof id == "string");
|
|
1081
|
+
return Array.from(new Set(ids));
|
|
1082
|
+
}
|
|
1083
|
+
if ("query" in selection)
|
|
1084
|
+
throw new Error("'query' in mutations is not supported.");
|
|
1085
|
+
return [];
|
|
1086
|
+
}
|
|
1087
|
+
function processMutations({
|
|
1088
|
+
documents,
|
|
1089
|
+
mutations,
|
|
1090
|
+
transactionId,
|
|
1091
|
+
timestamp
|
|
1092
|
+
}) {
|
|
1093
|
+
if (!mutations.length) return documents;
|
|
1094
|
+
const dataset = { ...documents }, now = timestamp || (/* @__PURE__ */ new Date()).toISOString();
|
|
1095
|
+
for (const mutation of mutations) {
|
|
1096
|
+
if ("create" in mutation) {
|
|
1097
|
+
const id = getId(mutation.create._id);
|
|
1098
|
+
if (dataset[id])
|
|
1099
|
+
throw new Error(
|
|
1100
|
+
`Cannot create document with \`_id\` \`${id}\` because another document with the same ID already exists.`
|
|
1101
|
+
);
|
|
1102
|
+
const document2 = {
|
|
1103
|
+
// > `_createdAt` and `_updatedAt` may be submitted and will override
|
|
1104
|
+
// > the default which is of course the current time. This can be used
|
|
1105
|
+
// > to reconstruct a data-set with its timestamp structure intact.
|
|
1106
|
+
// >
|
|
1107
|
+
// > [- source](https://www.sanity.io/docs/http-mutations#c732f27330a4)
|
|
1108
|
+
_createdAt: now,
|
|
1109
|
+
_updatedAt: now,
|
|
1110
|
+
...mutation.create,
|
|
1111
|
+
// prefer the user's `_createdAt` and `_updatedAt`
|
|
1112
|
+
_rev: transactionId,
|
|
1113
|
+
_id: id
|
|
1114
|
+
};
|
|
1115
|
+
dataset[id] = document2;
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
1118
|
+
if ("createOrReplace" in mutation) {
|
|
1119
|
+
const id = getId(mutation.createOrReplace._id), prev = dataset[id], document2 = {
|
|
1120
|
+
...mutation.createOrReplace,
|
|
1121
|
+
// otherwise, if the mutation provided, a `_createdAt` time, use it,
|
|
1122
|
+
// otherwise default to now
|
|
1123
|
+
_createdAt: (
|
|
1124
|
+
// if there was an existing document, use the previous `_createdAt`
|
|
1125
|
+
// since we're replacing the current document
|
|
1126
|
+
prev?._createdAt || // if there was no previous document, then we're creating this
|
|
1127
|
+
// document for the first time so we should use the `_createdAt` from
|
|
1128
|
+
// the mutation if the user included it
|
|
1129
|
+
typeof mutation.createOrReplace._createdAt == "string" && mutation.createOrReplace._createdAt || // otherwise, default to now
|
|
1130
|
+
now
|
|
1131
|
+
),
|
|
1132
|
+
_updatedAt: (
|
|
1133
|
+
// if there was an existing document, then set the `_updatedAt` to now
|
|
1134
|
+
// since we're replacing the current document
|
|
1135
|
+
prev ? now : (
|
|
1136
|
+
// otherwise, we're creating this document for the first time,
|
|
1137
|
+
// in that case, use the user's `_updatedAt` if included in the
|
|
1138
|
+
// mutation
|
|
1139
|
+
typeof mutation.createOrReplace._updatedAt == "string" && mutation.createOrReplace._updatedAt || // otherwise default to now
|
|
1140
|
+
now
|
|
1141
|
+
)
|
|
1142
|
+
),
|
|
1143
|
+
_rev: transactionId,
|
|
1144
|
+
_id: id
|
|
1145
|
+
};
|
|
1146
|
+
dataset[id] = document2;
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
if ("createIfNotExists" in mutation) {
|
|
1150
|
+
const id = getId(mutation.createIfNotExists._id);
|
|
1151
|
+
if (dataset[id]) continue;
|
|
1152
|
+
const document2 = {
|
|
1153
|
+
// same logic as `create`:
|
|
1154
|
+
// prefer the user's `_createdAt` and `_updatedAt`
|
|
1155
|
+
_createdAt: now,
|
|
1156
|
+
_updatedAt: now,
|
|
1157
|
+
...mutation.createIfNotExists,
|
|
1158
|
+
_rev: transactionId,
|
|
1159
|
+
_id: id
|
|
1160
|
+
};
|
|
1161
|
+
dataset[id] = document2;
|
|
1162
|
+
continue;
|
|
1163
|
+
}
|
|
1164
|
+
if ("delete" in mutation) {
|
|
1165
|
+
for (const id of getDocumentIds(mutation.delete))
|
|
1166
|
+
dataset[id] = null;
|
|
1167
|
+
continue;
|
|
1168
|
+
}
|
|
1169
|
+
if ("patch" in mutation) {
|
|
1170
|
+
const { patch } = mutation, patched = getDocumentIds(patch).map((id) => {
|
|
1171
|
+
if (!dataset[id])
|
|
1172
|
+
throw new Error(`Cannot patch document with ID \`${id}\` because it was not found.`);
|
|
1173
|
+
return Object.entries(patchOperations).reduce((acc, [type, operation]) => patch[type] ? operation(
|
|
1174
|
+
acc,
|
|
1175
|
+
// @ts-expect-error TS doesn't handle this union very well
|
|
1176
|
+
patch[type]
|
|
1177
|
+
) : acc, dataset[id]);
|
|
1178
|
+
});
|
|
1179
|
+
for (const result of patched)
|
|
1180
|
+
dataset[result._id] = {
|
|
1181
|
+
...result,
|
|
1182
|
+
_rev: transactionId,
|
|
1183
|
+
_updatedAt: now
|
|
1184
|
+
};
|
|
1185
|
+
continue;
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
return dataset;
|
|
1189
|
+
}
|
|
1190
|
+
const DEFAULT_MAX_BUFFER_SIZE = 20, DEFAULT_DEADLINE_MS = 3e4;
|
|
1191
|
+
class OutOfSyncError extends Error {
|
|
1192
|
+
/**
|
|
1193
|
+
* Attach state to the error for debugging/reporting
|
|
1194
|
+
*/
|
|
1195
|
+
state;
|
|
1196
|
+
constructor(message, state) {
|
|
1197
|
+
super(message), this.name = "OutOfSyncError", this.state = state;
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
class DeadlineExceededError extends OutOfSyncError {
|
|
1201
|
+
constructor(message, state) {
|
|
1202
|
+
super(message, state), this.name = "DeadlineExceededError";
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
class MaxBufferExceededError extends OutOfSyncError {
|
|
1206
|
+
constructor(message, state) {
|
|
1207
|
+
super(message, state), this.name = "MaxBufferExceededError";
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
function sortListenerEvents(options) {
|
|
1211
|
+
const { resolveChainDeadline = DEFAULT_DEADLINE_MS, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE } = {};
|
|
1212
|
+
return (input$) => input$.pipe(
|
|
1213
|
+
// Maintain state: current base revision, a buffer of pending mutation events,
|
|
1214
|
+
// and a list of events to emit.
|
|
1215
|
+
operators.scan(
|
|
1216
|
+
(state, event) => {
|
|
1217
|
+
if (event.type === "sync")
|
|
1218
|
+
return {
|
|
1219
|
+
base: { revision: event.document?._rev },
|
|
1220
|
+
buffer: [],
|
|
1221
|
+
emitEvents: [event]
|
|
1222
|
+
};
|
|
1223
|
+
if (event.type === "mutation") {
|
|
1224
|
+
if (!state.base)
|
|
1225
|
+
throw new Error(
|
|
1226
|
+
"Invalid state. Cannot process mutation event without a base sync event"
|
|
1227
|
+
);
|
|
1228
|
+
const buffer = state.buffer.concat(event), emitEvents = [];
|
|
1229
|
+
let baseRevision = state.base.revision, progress = !0;
|
|
1230
|
+
for (; progress; ) {
|
|
1231
|
+
progress = !1;
|
|
1232
|
+
const idx = buffer.findIndex((e3) => e3.previousRev === baseRevision);
|
|
1233
|
+
if (idx !== -1) {
|
|
1234
|
+
const [next] = buffer.splice(idx, 1);
|
|
1235
|
+
emitEvents.push(next), baseRevision = next.transition === "disappear" ? void 0 : next.resultRev, progress = !0;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
if (buffer.length >= maxBufferSize)
|
|
1239
|
+
throw new MaxBufferExceededError(
|
|
1240
|
+
`Too many unchainable mutation events (${buffer.length}) waiting to resolve.`,
|
|
1241
|
+
{ base: { revision: baseRevision }, buffer, emitEvents }
|
|
1242
|
+
);
|
|
1243
|
+
return {
|
|
1244
|
+
base: { revision: baseRevision },
|
|
1245
|
+
buffer,
|
|
1246
|
+
emitEvents
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
return { ...state, emitEvents: [event] };
|
|
1250
|
+
},
|
|
1251
|
+
{
|
|
1252
|
+
base: void 0,
|
|
1253
|
+
buffer: [],
|
|
1254
|
+
emitEvents: []
|
|
1255
|
+
}
|
|
1256
|
+
),
|
|
1257
|
+
rxjs.switchMap((state) => state.buffer.length > 0 ? rxjs.concat(
|
|
1258
|
+
rxjs.of(state),
|
|
1259
|
+
rxjs.timer(resolveChainDeadline).pipe(
|
|
1260
|
+
operators.mergeMap(
|
|
1261
|
+
() => rxjs.throwError(
|
|
1262
|
+
() => new DeadlineExceededError(
|
|
1263
|
+
`Did not resolve chain within a deadline of ${resolveChainDeadline}ms`,
|
|
1264
|
+
state
|
|
1265
|
+
)
|
|
1266
|
+
)
|
|
1267
|
+
)
|
|
1268
|
+
)
|
|
1269
|
+
) : rxjs.of(state)),
|
|
1270
|
+
// Emit all events that are ready to be applied.
|
|
1271
|
+
operators.mergeMap((state) => rxjs.of(...state.emitEvents))
|
|
1272
|
+
);
|
|
1273
|
+
}
|
|
1274
|
+
const listen = createInternalAction(({ state }) => {
|
|
1275
|
+
const { sharedListener, fetchDocument } = state.get();
|
|
1276
|
+
return function(documentId) {
|
|
1277
|
+
return sharedListener.pipe(
|
|
1278
|
+
rxjs.concatMap((e3) => e3.type === "welcome" ? fetchDocument(documentId).pipe(
|
|
1279
|
+
rxjs.map((document2) => ({ type: "sync", document: document2 }))
|
|
1280
|
+
) : e3.type === "mutation" && e3.documentId === documentId ? rxjs.of(e3) : rxjs.EMPTY),
|
|
1281
|
+
sortListenerEvents(),
|
|
1282
|
+
rxjs.withLatestFrom(
|
|
1283
|
+
state.observable.pipe(
|
|
1284
|
+
rxjs.map((s2) => s2.documentStates[documentId]),
|
|
1285
|
+
rxjs.filter(Boolean),
|
|
1286
|
+
rxjs.distinctUntilChanged()
|
|
1287
|
+
)
|
|
1288
|
+
),
|
|
1289
|
+
rxjs.map(([next, documentState]) => {
|
|
1290
|
+
if (next.type === "sync")
|
|
1291
|
+
return {
|
|
1292
|
+
type: "sync",
|
|
1293
|
+
documentId,
|
|
1294
|
+
document: next.document,
|
|
1295
|
+
revision: next.document?._rev,
|
|
1296
|
+
timestamp: next.document?._updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1297
|
+
};
|
|
1298
|
+
const [document2] = Object.values(
|
|
1299
|
+
processMutations({
|
|
1300
|
+
documents: { [documentId]: documentState.remote },
|
|
1301
|
+
mutations: next.mutations,
|
|
1302
|
+
transactionId: next.transactionId,
|
|
1303
|
+
timestamp: next.timestamp
|
|
1304
|
+
})
|
|
1305
|
+
), { previousRev, transactionId, timestamp } = next;
|
|
1306
|
+
return {
|
|
1307
|
+
type: "mutation",
|
|
1308
|
+
documentId,
|
|
1309
|
+
document: document2 ?? null,
|
|
1310
|
+
revision: transactionId,
|
|
1311
|
+
timestamp,
|
|
1312
|
+
...previousRev && { previousRev }
|
|
1313
|
+
};
|
|
1314
|
+
})
|
|
1315
|
+
);
|
|
1316
|
+
};
|
|
1317
|
+
});
|
|
1318
|
+
class e {
|
|
1319
|
+
pattern;
|
|
1320
|
+
patternRe;
|
|
1321
|
+
constructor(e3) {
|
|
1322
|
+
this.pattern = e3, this.patternRe = function(e4) {
|
|
1323
|
+
const t2 = [];
|
|
1324
|
+
for (const r2 of e4.split(".")) r2 === "*" ? t2.push("[^.]+") : r2 === "**" ? t2.push(".*") : t2.push(r2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
1325
|
+
return new RegExp(`^${t2.join(".")}$`);
|
|
1326
|
+
}(e3);
|
|
1327
|
+
}
|
|
1328
|
+
matches(e3) {
|
|
1329
|
+
return this.patternRe.test(e3);
|
|
1330
|
+
}
|
|
1331
|
+
toJSON() {
|
|
1332
|
+
return this.pattern;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
class t {
|
|
1336
|
+
type = "stream";
|
|
1337
|
+
generator;
|
|
1338
|
+
ticker;
|
|
1339
|
+
isDone;
|
|
1340
|
+
data;
|
|
1341
|
+
constructor(e3) {
|
|
1342
|
+
this.generator = e3, this.ticker = null, this.isDone = !1, this.data = [];
|
|
1343
|
+
}
|
|
1344
|
+
isArray() {
|
|
1345
|
+
return !0;
|
|
1346
|
+
}
|
|
1347
|
+
async get() {
|
|
1348
|
+
const e3 = [];
|
|
1349
|
+
for await (const t2 of this) e3.push(await t2.get());
|
|
1350
|
+
return e3;
|
|
1351
|
+
}
|
|
1352
|
+
async first(e3 = () => !0) {
|
|
1353
|
+
for await (const t2 of this) if (e3(t2)) return t2;
|
|
1354
|
+
}
|
|
1355
|
+
async reduce(e3, t2) {
|
|
1356
|
+
let r2 = t2;
|
|
1357
|
+
for await (const t3 of this) r2 = await e3(r2, t3);
|
|
1358
|
+
return r2;
|
|
1359
|
+
}
|
|
1360
|
+
async *[Symbol.asyncIterator]() {
|
|
1361
|
+
let e3 = 0;
|
|
1362
|
+
for (; ; ) {
|
|
1363
|
+
for (; e3 < this.data.length; e3++) yield this.data[e3];
|
|
1364
|
+
if (this.isDone) return;
|
|
1365
|
+
await this._nextTick();
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
_nextTick() {
|
|
1369
|
+
if (this.ticker) return this.ticker;
|
|
1370
|
+
let e3;
|
|
1371
|
+
const t2 = () => {
|
|
1372
|
+
this.ticker = new Promise((t3) => {
|
|
1373
|
+
e3 = t3;
|
|
1374
|
+
});
|
|
1375
|
+
}, r2 = () => {
|
|
1376
|
+
e3(), t2();
|
|
1377
|
+
};
|
|
1378
|
+
return t2(), (async () => {
|
|
1379
|
+
for await (const e4 of this.generator()) this.data.push(e4), r2();
|
|
1380
|
+
this.isDone = !0, r2();
|
|
1381
|
+
})(), this.ticker;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
const r = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|([-+]\d{2}:\d{2}))$/;
|
|
1385
|
+
function n(e3, t2) {
|
|
1386
|
+
let r2 = e3.toString();
|
|
1387
|
+
for (; r2.length < t2; ) r2 = `0${r2}`;
|
|
1388
|
+
return r2;
|
|
1389
|
+
}
|
|
1390
|
+
class o {
|
|
1391
|
+
data;
|
|
1392
|
+
type;
|
|
1393
|
+
constructor(e3, t2) {
|
|
1394
|
+
this.data = e3, this.type = t2;
|
|
1395
|
+
}
|
|
1396
|
+
isArray() {
|
|
1397
|
+
return this.type === "array";
|
|
1398
|
+
}
|
|
1399
|
+
get() {
|
|
1400
|
+
return this.data;
|
|
1401
|
+
}
|
|
1402
|
+
first(e3 = () => !0) {
|
|
1403
|
+
if (!this.isArray()) throw new Error("`first` can only be called on array `StaticValue`s");
|
|
1404
|
+
const t2 = this.get();
|
|
1405
|
+
for (const r2 of t2) {
|
|
1406
|
+
const t3 = f(r2, "sync");
|
|
1407
|
+
if (e3(t3)) return t3;
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
reduce(e3, t2) {
|
|
1411
|
+
if (!this.isArray()) throw new Error("`reduce` can only be called on array `StaticValue`s");
|
|
1412
|
+
const r2 = this.get();
|
|
1413
|
+
let n2 = t2;
|
|
1414
|
+
for (const t3 of r2)
|
|
1415
|
+
n2 = e3(n2, f(t3, "sync"));
|
|
1416
|
+
return n2;
|
|
1417
|
+
}
|
|
1418
|
+
[Symbol.asyncIterator]() {
|
|
1419
|
+
if (Array.isArray(this.data)) return function* (e3) {
|
|
1420
|
+
for (const t2 of e3) yield f(t2, "async");
|
|
1421
|
+
}(this.data);
|
|
1422
|
+
throw new Error(`Cannot iterate over: ${this.type}`);
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
const i = new o(null, "null"), s = new o(!0, "boolean"), a = new o(!1, "boolean");
|
|
1426
|
+
class c {
|
|
1427
|
+
date;
|
|
1428
|
+
constructor(e3) {
|
|
1429
|
+
this.date = e3;
|
|
1430
|
+
}
|
|
1431
|
+
static parseToValue(e3) {
|
|
1432
|
+
const t2 = function(e4) {
|
|
1433
|
+
return r.test(e4) ? new Date(e4) : null;
|
|
1434
|
+
}(e3);
|
|
1435
|
+
return t2 ? new o(new c(t2), "datetime") : i;
|
|
1436
|
+
}
|
|
1437
|
+
equals(e3) {
|
|
1438
|
+
return this.date.getTime() == e3.date.getTime();
|
|
1439
|
+
}
|
|
1440
|
+
add(e3) {
|
|
1441
|
+
const t2 = new Date(this.date.getTime());
|
|
1442
|
+
return t2.setTime(t2.getTime() + 1e3 * e3), new c(t2);
|
|
1443
|
+
}
|
|
1444
|
+
difference(e3) {
|
|
1445
|
+
return (this.date.getTime() - e3.date.getTime()) / 1e3;
|
|
1446
|
+
}
|
|
1447
|
+
compareTo(e3) {
|
|
1448
|
+
return this.date.getTime() - e3.date.getTime();
|
|
1449
|
+
}
|
|
1450
|
+
toString() {
|
|
1451
|
+
return function(e3) {
|
|
1452
|
+
const t2 = n(e3.getUTCFullYear(), 4), r2 = n(e3.getUTCMonth() + 1, 2), o2 = n(e3.getUTCDate(), 2), i2 = n(e3.getUTCHours(), 2), s2 = n(e3.getUTCMinutes(), 2), a2 = n(e3.getUTCSeconds(), 2);
|
|
1453
|
+
let c2 = "";
|
|
1454
|
+
const u2 = e3.getMilliseconds();
|
|
1455
|
+
return u2 != 0 && (c2 = `.${n(u2, 3)}`), `${t2}-${r2}-${o2}T${i2}:${s2}:${a2}${c2}Z`;
|
|
1456
|
+
}(this.date);
|
|
1457
|
+
}
|
|
1458
|
+
toJSON() {
|
|
1459
|
+
return this.toString();
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
function u(e3) {
|
|
1463
|
+
return Number.isFinite(e3) ? new o(e3, "number") : i;
|
|
1464
|
+
}
|
|
1465
|
+
function p(e3) {
|
|
1466
|
+
return new o(e3, "string");
|
|
1467
|
+
}
|
|
1468
|
+
function l(e3) {
|
|
1469
|
+
return new o(e3, "datetime");
|
|
1470
|
+
}
|
|
1471
|
+
function f(e3, r2) {
|
|
1472
|
+
return (n2 = e3) && typeof n2.next == "function" && r2 !== "sync" ? new t(async function* () {
|
|
1473
|
+
for await (const t2 of e3) yield f(t2, "async");
|
|
1474
|
+
}) : e3 == null ? i : new o(e3, y(e3));
|
|
1475
|
+
var n2;
|
|
1476
|
+
}
|
|
1477
|
+
function y(t2) {
|
|
1478
|
+
return t2 === null || typeof t2 > "u" ? "null" : Array.isArray(t2) ? "array" : t2 instanceof e ? "path" : t2 instanceof c ? "datetime" : typeof t2;
|
|
1479
|
+
}
|
|
1480
|
+
const d = (e3) => typeof e3 == "object" && !!e3 && "then" in e3 && typeof e3.then == "function";
|
|
1481
|
+
function h(e3) {
|
|
1482
|
+
const t2 = e3(), r2 = t2.next();
|
|
1483
|
+
if (r2.done) return r2.value;
|
|
1484
|
+
function n2(e4) {
|
|
1485
|
+
const r3 = t2.next(e4);
|
|
1486
|
+
if (r3.done) return r3.value;
|
|
1487
|
+
const o3 = r3.value;
|
|
1488
|
+
return o3 && d(o3) ? o3.then(n2) : n2(o3);
|
|
1489
|
+
}
|
|
1490
|
+
const o2 = r2.value;
|
|
1491
|
+
return o2 && d(o2) ? o2.then(n2) : n2(o2);
|
|
1492
|
+
}
|
|
1493
|
+
function m(e3, t2) {
|
|
1494
|
+
return e3.type === "string" && t2.type === "string" || e3.type === "boolean" && t2.type === "boolean" || e3.type === "null" && t2.type === "null" || e3.type === "number" && t2.type === "number" ? e3.data === t2.data : e3.type === "datetime" && t2.type === "datetime" && e3.data.equals(t2.data);
|
|
1495
|
+
}
|
|
1496
|
+
const b = /([^!@#$%^&*(),\\/?";:{}|[\]+<>\s-])+/g, g = /([^!@#$%^&(),\\/?";:{}|[\]+<>\s-])+/g, w = /(\b\.+|\.+\b)/g;
|
|
1497
|
+
function k(e3) {
|
|
1498
|
+
return e3.replace(w, "").match(b) || [];
|
|
1499
|
+
}
|
|
1500
|
+
function v(e3) {
|
|
1501
|
+
return x(e3).map((e4) => (t2) => t2.some((t3) => e4.test(t3)));
|
|
1502
|
+
}
|
|
1503
|
+
function x(e3) {
|
|
1504
|
+
return (e3.replace(w, "").match(g) || []).map((e4) => new RegExp(`^${e4.slice(0, 1024).replace(/\*/g, ".*")}$`, "i"));
|
|
1505
|
+
}
|
|
1506
|
+
const _ = { datetime: 1, number: 2, string: 3, boolean: 4 };
|
|
1507
|
+
function A(e3, t2) {
|
|
1508
|
+
const r2 = y(e3);
|
|
1509
|
+
if (r2 !== y(t2)) return null;
|
|
1510
|
+
switch (r2) {
|
|
1511
|
+
case "number":
|
|
1512
|
+
case "boolean":
|
|
1513
|
+
return e3 - t2;
|
|
1514
|
+
case "string":
|
|
1515
|
+
return e3 < t2 ? -1 : e3 > t2 ? 1 : 0;
|
|
1516
|
+
case "datetime":
|
|
1517
|
+
return e3.compareTo(t2);
|
|
1518
|
+
default:
|
|
1519
|
+
return null;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
function E(e3, t2) {
|
|
1523
|
+
const r2 = y(e3), n2 = y(t2), o2 = _[r2] || 100, i2 = _[n2] || 100;
|
|
1524
|
+
if (o2 !== i2) return o2 - i2;
|
|
1525
|
+
let s2 = A(e3, t2);
|
|
1526
|
+
return s2 === null && (s2 = 0), s2;
|
|
1527
|
+
}
|
|
1528
|
+
const j = { "==": function(e3, t2) {
|
|
1529
|
+
return m(e3, t2) ? s : a;
|
|
1530
|
+
}, "!=": function(e3, t2) {
|
|
1531
|
+
return m(e3, t2) ? a : s;
|
|
1532
|
+
}, ">": function(e3, t2) {
|
|
1533
|
+
if (e3.type === "stream" || t2.type === "stream") return i;
|
|
1534
|
+
const r2 = A(e3.data, t2.data);
|
|
1535
|
+
return r2 === null ? i : r2 > 0 ? s : a;
|
|
1536
|
+
}, ">=": function(e3, t2) {
|
|
1537
|
+
if (e3.type === "stream" || t2.type === "stream") return i;
|
|
1538
|
+
const r2 = A(e3.data, t2.data);
|
|
1539
|
+
return r2 === null ? i : r2 >= 0 ? s : a;
|
|
1540
|
+
}, "<": function(e3, t2) {
|
|
1541
|
+
if (e3.type === "stream" || t2.type === "stream") return i;
|
|
1542
|
+
const r2 = A(e3.data, t2.data);
|
|
1543
|
+
return r2 === null ? i : r2 < 0 ? s : a;
|
|
1544
|
+
}, "<=": function(e3, t2) {
|
|
1545
|
+
if (e3.type === "stream" || t2.type === "stream") return i;
|
|
1546
|
+
const r2 = A(e3.data, t2.data);
|
|
1547
|
+
return r2 === null ? i : r2 <= 0 ? s : a;
|
|
1548
|
+
}, in: function(e3, t2) {
|
|
1549
|
+
return h(function* () {
|
|
1550
|
+
return t2.type === "path" ? e3.type !== "string" ? i : t2.data.matches(e3.data) ? s : a : t2.isArray() ? (yield t2.first((t3) => m(e3, t3))) ? s : a : i;
|
|
1551
|
+
});
|
|
1552
|
+
}, match: function(e3, t2) {
|
|
1553
|
+
return h(function* () {
|
|
1554
|
+
const r2 = yield e3.get(), n2 = yield t2.get();
|
|
1555
|
+
let o2, i2 = [];
|
|
1556
|
+
return Array.isArray(r2) ? i2 = r2.filter((e4) => typeof e4 == "string") : typeof r2 == "string" && (i2 = [r2]), Array.isArray(n2) ? o2 = n2.filter((e4) => typeof e4 == "string") : typeof n2 == "string" && (o2 = [n2]), o2?.length && function(e4, t3) {
|
|
1557
|
+
return e4.length !== 0 && t3.length !== 0 && t3.every((t4) => t4(e4));
|
|
1558
|
+
}(i2.flatMap(k), o2.flatMap(v)) ? s : a;
|
|
1559
|
+
});
|
|
1560
|
+
}, "+": function(e3, r2, n2) {
|
|
1561
|
+
return e3.type === "datetime" && r2.type === "number" ? l(e3.data.add(r2.data)) : e3.type === "number" && r2.type === "number" ? u(e3.data + r2.data) : e3.type === "string" && r2.type === "string" ? p(e3.data + r2.data) : e3.type === "object" && r2.type === "object" ? f({ ...e3.data, ...r2.data }, n2) : e3.type === "array" && r2.type === "array" ? f(e3.data.concat(r2.data), n2) : e3.isArray() && r2.isArray() ? n2 === "sync" ? h(function* () {
|
|
1562
|
+
const t2 = [...yield e3.get(), ...yield r2.get()];
|
|
1563
|
+
return new o(t2, "array");
|
|
1564
|
+
}) : new t(async function* () {
|
|
1565
|
+
for await (const t2 of e3) yield t2;
|
|
1566
|
+
for await (const e4 of r2) yield e4;
|
|
1567
|
+
}) : i;
|
|
1568
|
+
}, "-": function(e3, t2) {
|
|
1569
|
+
return e3.type === "datetime" && t2.type === "number" ? l(e3.data.add(-t2.data)) : e3.type === "datetime" && t2.type === "datetime" ? u(e3.data.difference(t2.data)) : e3.type === "number" && t2.type === "number" ? u(e3.data - t2.data) : i;
|
|
1570
|
+
}, "*": S((e3, t2) => e3 * t2), "/": S((e3, t2) => e3 / t2), "%": S((e3, t2) => e3 % t2), "**": S((e3, t2) => Math.pow(e3, t2)) };
|
|
1571
|
+
function S(e3) {
|
|
1572
|
+
return function(t2, r2) {
|
|
1573
|
+
return t2.type === "number" && r2.type === "number" ? u(e3(t2.data, r2.data)) : i;
|
|
1574
|
+
};
|
|
1575
|
+
}
|
|
1576
|
+
let O = class e2 {
|
|
1577
|
+
params;
|
|
1578
|
+
source;
|
|
1579
|
+
value;
|
|
1580
|
+
parent;
|
|
1581
|
+
context;
|
|
1582
|
+
isHidden = !1;
|
|
1583
|
+
constructor(e3, t2, r2, n2, o2) {
|
|
1584
|
+
this.params = e3, this.source = t2, this.value = r2, this.context = n2, this.parent = o2;
|
|
1585
|
+
}
|
|
1586
|
+
createNested(t2) {
|
|
1587
|
+
return this.isHidden ? new e2(this.params, this.source, t2, this.context, this.parent) : new e2(this.params, this.source, t2, this.context, this);
|
|
1588
|
+
}
|
|
1589
|
+
createHidden(e3) {
|
|
1590
|
+
const t2 = this.createNested(e3);
|
|
1591
|
+
return t2.isHidden = !0, t2;
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
function I(e3, t2, r2) {
|
|
1595
|
+
return (0, $[e3.type])(e3, t2, r2);
|
|
1596
|
+
}
|
|
1597
|
+
const $ = { This: (e3, t2) => t2.value, Selector() {
|
|
1598
|
+
throw new Error("Selectors can not be evaluated");
|
|
1599
|
+
}, Everything: (e3, t2) => t2.source, Parameter: ({ name: e3 }, t2, r2) => f(t2.params[e3], r2), Context({ key: e3 }, t2) {
|
|
1600
|
+
if (e3 === "before" || e3 === "after") return t2.context[e3] || i;
|
|
1601
|
+
throw new Error(`unknown context key: ${e3}`);
|
|
1602
|
+
}, Parent({ n: e3 }, t2) {
|
|
1603
|
+
let r2 = t2;
|
|
1604
|
+
for (let t3 = 0; t3 < e3; t3++) {
|
|
1605
|
+
if (!r2.parent) return i;
|
|
1606
|
+
r2 = r2.parent;
|
|
1607
|
+
}
|
|
1608
|
+
return r2.value;
|
|
1609
|
+
}, OpCall: ({ op: e3, left: t2, right: r2 }, n2, o2) => h(function* () {
|
|
1610
|
+
const i2 = j[e3];
|
|
1611
|
+
if (!i2) throw new Error(`Unknown operator: ${e3}`);
|
|
1612
|
+
const s2 = yield I(t2, n2, o2), a2 = yield I(r2, n2, o2);
|
|
1613
|
+
return yield i2(s2, a2, o2);
|
|
1614
|
+
}), Select: ({ alternatives: e3, fallback: t2 }, r2, n2) => h(function* () {
|
|
1615
|
+
for (const t3 of e3) {
|
|
1616
|
+
const e4 = yield I(t3.condition, r2, n2);
|
|
1617
|
+
if (e4.type === "boolean" && e4.data === !0) return yield I(t3.value, r2, n2);
|
|
1618
|
+
}
|
|
1619
|
+
return t2 ? yield I(t2, r2, n2) : i;
|
|
1620
|
+
}), InRange: ({ base: e3, left: t2, right: r2, isInclusive: n2 }, o2, c2) => h(function* () {
|
|
1621
|
+
const u2 = yield I(e3, o2, c2), p2 = yield I(t2, o2, c2), l2 = yield I(r2, o2, c2), f2 = A(yield u2.get(), yield p2.get());
|
|
1622
|
+
if (f2 === null) return i;
|
|
1623
|
+
const y2 = A(yield u2.get(), yield l2.get());
|
|
1624
|
+
return y2 === null ? i : n2 ? f2 >= 0 && y2 <= 0 ? s : a : f2 >= 0 && y2 < 0 ? s : a;
|
|
1625
|
+
}), Filter: ({ base: e3, expr: r2 }, n2, s2) => h(function* () {
|
|
1626
|
+
const a2 = yield I(e3, n2, s2);
|
|
1627
|
+
if (!a2.isArray()) return i;
|
|
1628
|
+
if (s2 === "sync") {
|
|
1629
|
+
const e4 = yield a2.get(), t2 = [];
|
|
1630
|
+
for (const o2 of e4) {
|
|
1631
|
+
const e5 = f(o2, s2), i2 = n2.createNested(e5), a3 = yield I(r2, i2, s2);
|
|
1632
|
+
a3.type === "boolean" && a3.data === !0 && t2.push(o2);
|
|
1633
|
+
}
|
|
1634
|
+
return new o(t2, "array");
|
|
1635
|
+
}
|
|
1636
|
+
return new t(async function* () {
|
|
1637
|
+
for await (const e4 of a2) {
|
|
1638
|
+
const t2 = n2.createNested(e4), o2 = await I(r2, t2, s2);
|
|
1639
|
+
o2.type === "boolean" && o2.data === !0 && (yield e4);
|
|
1640
|
+
}
|
|
1641
|
+
});
|
|
1642
|
+
}), Projection: ({ base: e3, expr: t2 }, r2, n2) => h(function* () {
|
|
1643
|
+
const o2 = yield I(e3, r2, n2);
|
|
1644
|
+
if (o2.type !== "object") return i;
|
|
1645
|
+
const s2 = r2.createNested(o2);
|
|
1646
|
+
return yield I(t2, s2, n2);
|
|
1647
|
+
}), FuncCall: ({ func: e3, args: t2 }, r2, n2) => e3(t2, r2, n2), PipeFuncCall: ({ func: e3, base: t2, args: r2 }, n2, o2) => h(function* () {
|
|
1648
|
+
const i2 = yield I(t2, n2, o2);
|
|
1649
|
+
return yield e3(i2, r2, n2, o2);
|
|
1650
|
+
}), AccessAttribute: ({ base: e3, name: t2 }, r2, n2) => h(function* () {
|
|
1651
|
+
let o2 = r2.value;
|
|
1652
|
+
return e3 && (o2 = yield I(e3, r2, n2)), o2.type === "object" && o2.data.hasOwnProperty(t2) ? f(o2.data[t2], n2) : i;
|
|
1653
|
+
}), AccessElement: ({ base: e3, index: t2 }, r2, n2) => h(function* () {
|
|
1654
|
+
const o2 = yield I(e3, r2, n2);
|
|
1655
|
+
if (!o2.isArray()) return i;
|
|
1656
|
+
const s2 = yield o2.get();
|
|
1657
|
+
return f(s2[t2 < 0 ? t2 + s2.length : t2], n2);
|
|
1658
|
+
}), Slice: ({ base: e3, left: t2, right: r2, isInclusive: n2 }, o2, s2) => h(function* () {
|
|
1659
|
+
const a2 = yield I(e3, o2, s2);
|
|
1660
|
+
if (!a2.isArray()) return i;
|
|
1661
|
+
const c2 = yield a2.get();
|
|
1662
|
+
let u2 = t2, p2 = r2;
|
|
1663
|
+
return u2 < 0 && (u2 = c2.length + u2), p2 < 0 && (p2 = c2.length + p2), n2 && p2++, u2 < 0 && (u2 = 0), p2 < 0 && (p2 = 0), f(c2.slice(u2, p2), s2);
|
|
1664
|
+
}), Deref: ({ base: e3 }, t2, r2) => h(function* () {
|
|
1665
|
+
const n2 = yield I(e3, t2, r2);
|
|
1666
|
+
if (!t2.source.isArray() || n2.type !== "object") return i;
|
|
1667
|
+
const o2 = n2.data._ref;
|
|
1668
|
+
return typeof o2 != "string" ? i : t2.context.dereference ? f(yield t2.context.dereference({ _ref: o2 }), r2) : (yield t2.source.first((e4) => e4.type === "object" && o2 == e4.data._id)) || i;
|
|
1669
|
+
}), Value: ({ value: e3 }, t2, r2) => f(e3, r2), Group: ({ base: e3 }, t2, r2) => I(e3, t2, r2), Object: ({ attributes: e3 }, t2, r2) => h(function* () {
|
|
1670
|
+
const n2 = {};
|
|
1671
|
+
for (const o2 of e3) {
|
|
1672
|
+
const e4 = o2.type;
|
|
1673
|
+
switch (o2.type) {
|
|
1674
|
+
case "ObjectAttributeValue": {
|
|
1675
|
+
const e5 = yield I(o2.value, t2, r2);
|
|
1676
|
+
n2[o2.name] = yield e5.get();
|
|
1677
|
+
break;
|
|
1678
|
+
}
|
|
1679
|
+
case "ObjectConditionalSplat": {
|
|
1680
|
+
const e5 = yield I(o2.condition, t2, r2);
|
|
1681
|
+
if (e5.type !== "boolean" || e5.data === !1) continue;
|
|
1682
|
+
const i2 = yield I(o2.value, t2, r2);
|
|
1683
|
+
i2.type === "object" && Object.assign(n2, i2.data);
|
|
1684
|
+
break;
|
|
1685
|
+
}
|
|
1686
|
+
case "ObjectSplat": {
|
|
1687
|
+
const e5 = yield I(o2.value, t2, r2);
|
|
1688
|
+
e5.type === "object" && Object.assign(n2, e5.data);
|
|
1689
|
+
break;
|
|
1690
|
+
}
|
|
1691
|
+
default:
|
|
1692
|
+
throw new Error(`Unknown node type: ${e4}`);
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
return f(n2, r2);
|
|
1696
|
+
}), Array: ({ elements: e3 }, r2, n2) => h(function* () {
|
|
1697
|
+
if (n2 === "sync") {
|
|
1698
|
+
const t2 = [];
|
|
1699
|
+
for (const o2 of e3) {
|
|
1700
|
+
const e4 = yield I(o2.value, r2, n2);
|
|
1701
|
+
if (o2.isSplat) {
|
|
1702
|
+
if (e4.isArray()) {
|
|
1703
|
+
const r3 = yield e4.get();
|
|
1704
|
+
t2.push(...r3);
|
|
1705
|
+
}
|
|
1706
|
+
} else t2.push(yield e4.get());
|
|
1707
|
+
}
|
|
1708
|
+
return new o(t2, "array");
|
|
1709
|
+
}
|
|
1710
|
+
return new t(async function* () {
|
|
1711
|
+
for (const t2 of e3) {
|
|
1712
|
+
const e4 = await I(t2.value, r2, n2);
|
|
1713
|
+
if (t2.isSplat) {
|
|
1714
|
+
if (e4.isArray()) for await (const t3 of e4) yield t3;
|
|
1715
|
+
} else yield e4;
|
|
1716
|
+
}
|
|
1717
|
+
});
|
|
1718
|
+
}), Tuple() {
|
|
1719
|
+
throw new Error("tuples can not be evaluated");
|
|
1720
|
+
}, Or: ({ left: e3, right: t2 }, r2, n2) => h(function* () {
|
|
1721
|
+
const o2 = yield I(e3, r2, n2), c2 = yield I(t2, r2, n2);
|
|
1722
|
+
return o2.type === "boolean" && o2.data === !0 || c2.type === "boolean" && c2.data === !0 ? s : o2.type !== "boolean" || c2.type !== "boolean" ? i : a;
|
|
1723
|
+
}), And: ({ left: e3, right: t2 }, r2, n2) => h(function* () {
|
|
1724
|
+
const o2 = yield I(e3, r2, n2), c2 = yield I(t2, r2, n2);
|
|
1725
|
+
return o2.type === "boolean" && o2.data === !1 || c2.type === "boolean" && c2.data === !1 ? a : o2.type !== "boolean" || c2.type !== "boolean" ? i : s;
|
|
1726
|
+
}), Not: ({ base: e3 }, t2, r2) => h(function* () {
|
|
1727
|
+
const n2 = yield I(e3, t2, r2);
|
|
1728
|
+
return n2.type !== "boolean" ? i : n2.data ? a : s;
|
|
1729
|
+
}), Neg: ({ base: e3 }, t2, r2) => h(function* () {
|
|
1730
|
+
const n2 = yield I(e3, t2, r2);
|
|
1731
|
+
return n2.type !== "number" ? i : u(-n2.data);
|
|
1732
|
+
}), Pos: ({ base: e3 }, t2, r2) => h(function* () {
|
|
1733
|
+
const n2 = yield I(e3, t2, r2);
|
|
1734
|
+
return n2.type !== "number" ? i : u(n2.data);
|
|
1735
|
+
}), Asc: () => i, Desc: () => i, ArrayCoerce: ({ base: e3 }, t2, r2) => h(function* () {
|
|
1736
|
+
const n2 = yield I(e3, t2, r2);
|
|
1737
|
+
return n2.isArray() ? n2 : i;
|
|
1738
|
+
}), Map: ({ base: e3, expr: r2 }, n2, s2) => h(function* () {
|
|
1739
|
+
const a2 = yield I(e3, n2, s2);
|
|
1740
|
+
if (!a2.isArray()) return i;
|
|
1741
|
+
if (s2 === "sync") {
|
|
1742
|
+
const e4 = yield a2.get(), t2 = [];
|
|
1743
|
+
for (const o2 of e4) {
|
|
1744
|
+
const e5 = f(o2, "sync"), i2 = n2.createHidden(e5), a3 = yield I(r2, i2, s2);
|
|
1745
|
+
t2.push(yield a3.get());
|
|
1746
|
+
}
|
|
1747
|
+
return new o(t2, "array");
|
|
1748
|
+
}
|
|
1749
|
+
return new t(async function* () {
|
|
1750
|
+
for await (const e4 of a2) {
|
|
1751
|
+
const t2 = n2.createHidden(e4);
|
|
1752
|
+
yield await I(r2, t2, s2);
|
|
1753
|
+
}
|
|
1754
|
+
});
|
|
1755
|
+
}), FlatMap: ({ base: e3, expr: r2 }, n2, s2) => h(function* () {
|
|
1756
|
+
const a2 = yield I(e3, n2, s2);
|
|
1757
|
+
if (!a2.isArray()) return i;
|
|
1758
|
+
if (s2 === "sync") {
|
|
1759
|
+
const e4 = yield a2.get(), t2 = [];
|
|
1760
|
+
for (const o2 of e4) {
|
|
1761
|
+
const e5 = f(o2, "sync"), i2 = n2.createHidden(e5), a3 = yield I(r2, i2, s2);
|
|
1762
|
+
if (a3.isArray()) {
|
|
1763
|
+
const e6 = yield a3.get();
|
|
1764
|
+
t2.push(...e6);
|
|
1765
|
+
} else {
|
|
1766
|
+
const e6 = yield a3.get();
|
|
1767
|
+
t2.push(e6);
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
return new o(t2, "array");
|
|
1771
|
+
}
|
|
1772
|
+
return new t(async function* () {
|
|
1773
|
+
for await (const e4 of a2) {
|
|
1774
|
+
const t2 = n2.createHidden(e4), o2 = await I(r2, t2, s2);
|
|
1775
|
+
if (o2.isArray()) for await (const e5 of o2) yield e5;
|
|
1776
|
+
else yield o2;
|
|
1777
|
+
}
|
|
1778
|
+
});
|
|
1779
|
+
}) };
|
|
1780
|
+
function C(e3, t2 = {}) {
|
|
1781
|
+
const r2 = f(t2.root, "sync"), n2 = f(t2.dataset, "sync"), o2 = { ...t2.params }, i2 = new O(o2, n2, r2, function(e4 = {}, t3) {
|
|
1782
|
+
return { timestamp: e4.timestamp || /* @__PURE__ */ new Date(), identity: e4.identity === void 0 ? "me" : e4.identity, sanity: e4.sanity, after: e4.after ? f(e4.after, t3) : null, before: e4.before ? f(e4.before, t3) : null, dereference: e4.dereference };
|
|
1783
|
+
}(t2, "sync"), null), s2 = I(e3, i2, "sync");
|
|
1784
|
+
if (d(s2)) throw new Error("Unexpected promise when evaluating. This expression may not support evaluateSync.");
|
|
1785
|
+
return s2;
|
|
1786
|
+
}
|
|
1787
|
+
function M(e3) {
|
|
1788
|
+
switch (e3.type) {
|
|
1789
|
+
case "Group":
|
|
1790
|
+
return M(e3.base);
|
|
1791
|
+
case "Value":
|
|
1792
|
+
case "Parameter":
|
|
1793
|
+
return !0;
|
|
1794
|
+
case "Pos":
|
|
1795
|
+
case "Neg":
|
|
1796
|
+
return M(e3.base);
|
|
1797
|
+
case "OpCall":
|
|
1798
|
+
switch (e3.op) {
|
|
1799
|
+
case "+":
|
|
1800
|
+
case "-":
|
|
1801
|
+
case "*":
|
|
1802
|
+
case "/":
|
|
1803
|
+
case "%":
|
|
1804
|
+
case "**":
|
|
1805
|
+
return M(e3.left) && M(e3.right);
|
|
1806
|
+
default:
|
|
1807
|
+
return !1;
|
|
1808
|
+
}
|
|
1809
|
+
default:
|
|
1810
|
+
return !1;
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
const T = new O({}, i, i, { timestamp: /* @__PURE__ */ new Date(0), identity: "me", before: null, after: null }, null);
|
|
1814
|
+
function P(e3) {
|
|
1815
|
+
return M(e3) ? function(e4) {
|
|
1816
|
+
const t2 = I(e4, T, "sync");
|
|
1817
|
+
if (d(t2)) throw new Error("BUG: constant evaluate should never return a promise");
|
|
1818
|
+
return t2;
|
|
1819
|
+
}(e3) : null;
|
|
1820
|
+
}
|
|
1821
|
+
function N(e3, t2) {
|
|
1822
|
+
return h(function* () {
|
|
1823
|
+
if (e3.type === "object") return V(e3.data);
|
|
1824
|
+
if (e3.isArray()) {
|
|
1825
|
+
const r2 = yield U(e3, t2);
|
|
1826
|
+
if (r2.length > 0) return r2.join(`
|
|
1827
|
+
|
|
1828
|
+
`);
|
|
1829
|
+
}
|
|
1830
|
+
return null;
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
function U(e3, t2) {
|
|
1834
|
+
return h(function* () {
|
|
1835
|
+
const r2 = [], n2 = yield e3.get();
|
|
1836
|
+
for (const e4 of n2) {
|
|
1837
|
+
const n3 = f(e4, t2);
|
|
1838
|
+
if (n3.type === "object") {
|
|
1839
|
+
const e5 = V(n3.data);
|
|
1840
|
+
e5 !== null && r2.push(e5);
|
|
1841
|
+
} else if (n3.isArray()) {
|
|
1842
|
+
const e5 = yield U(n3, t2);
|
|
1843
|
+
r2.push(...e5);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
return r2;
|
|
1847
|
+
});
|
|
1848
|
+
}
|
|
1849
|
+
function V(e3) {
|
|
1850
|
+
if (typeof e3._type != "string") return null;
|
|
1851
|
+
const t2 = e3.children;
|
|
1852
|
+
if (!Array.isArray(t2)) return null;
|
|
1853
|
+
let r2 = "";
|
|
1854
|
+
for (const e4 of t2) e4 && typeof e4 == "object" && typeof e4._type == "string" && e4._type === "span" && typeof e4.text == "string" && (r2 += e4.text);
|
|
1855
|
+
return r2;
|
|
1856
|
+
}
|
|
1857
|
+
const D = 1.2;
|
|
1858
|
+
function F(e3, t2, r2) {
|
|
1859
|
+
return h(function* () {
|
|
1860
|
+
if (e3.type === "OpCall" && e3.op === "match")
|
|
1861
|
+
return function(e4, t3) {
|
|
1862
|
+
return h(function* () {
|
|
1863
|
+
const r3 = yield e4.get(), n2 = yield t3.get();
|
|
1864
|
+
let o2, i2 = [];
|
|
1865
|
+
if (Array.isArray(r3) ? i2 = r3.filter((e5) => typeof e5 == "string") : typeof r3 == "string" && (i2 = [r3]), Array.isArray(n2) ? o2 = n2.filter((e5) => typeof e5 == "string") : typeof n2 == "string" && (o2 = [n2]), !o2?.length) return 0;
|
|
1866
|
+
const s2 = i2.flatMap(k), a2 = o2.flatMap(x);
|
|
1867
|
+
if (s2.length === 0 || a2.length === 0) return 0;
|
|
1868
|
+
let c2 = 0;
|
|
1869
|
+
for (const e5 of a2) {
|
|
1870
|
+
const t4 = s2.reduce((t5, r4) => t5 + (e5.test(r4) ? 1 : 0), 0);
|
|
1871
|
+
c2 += 2.2 * t4 / (t4 + D);
|
|
1872
|
+
}
|
|
1873
|
+
return c2;
|
|
1874
|
+
});
|
|
1875
|
+
}(yield I(e3.left, t2, r2), yield I(e3.right, t2, r2));
|
|
1876
|
+
if (e3.type === "FuncCall" && e3.name === "boost") {
|
|
1877
|
+
const n2 = yield F(e3.args[0], t2, r2), o2 = yield I(e3.args[1], t2, r2);
|
|
1878
|
+
return o2.type === "number" && n2 > 0 ? n2 + o2.data : 0;
|
|
1879
|
+
}
|
|
1880
|
+
switch (e3.type) {
|
|
1881
|
+
case "Or":
|
|
1882
|
+
return (yield F(e3.left, t2, r2)) + (yield F(e3.right, t2, r2));
|
|
1883
|
+
case "And": {
|
|
1884
|
+
const n2 = yield F(e3.left, t2, r2), o2 = yield F(e3.right, t2, r2);
|
|
1885
|
+
return n2 === 0 || o2 === 0 ? 0 : n2 + o2;
|
|
1886
|
+
}
|
|
1887
|
+
default: {
|
|
1888
|
+
const n2 = yield I(e3, t2, r2);
|
|
1889
|
+
return n2.type === "boolean" && n2.data === !0 ? 1 : 0;
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
function R(e3, t2) {
|
|
1895
|
+
switch (y(e3)) {
|
|
1896
|
+
case "array":
|
|
1897
|
+
for (const r2 of e3) if (R(r2, t2)) return !0;
|
|
1898
|
+
break;
|
|
1899
|
+
case "object":
|
|
1900
|
+
if (e3._ref) return t2.has(e3._ref);
|
|
1901
|
+
for (const r2 of Object.values(e3)) if (R(r2, t2)) return !0;
|
|
1902
|
+
}
|
|
1903
|
+
return !1;
|
|
1904
|
+
}
|
|
1905
|
+
const q = { anywhere: function() {
|
|
1906
|
+
throw new Error("not implemented");
|
|
1907
|
+
} };
|
|
1908
|
+
q.anywhere.arity = 1, q.coalesce = function(e3, t2, r2) {
|
|
1909
|
+
return h(function* () {
|
|
1910
|
+
for (const n2 of e3) {
|
|
1911
|
+
const e4 = yield I(n2, t2, r2);
|
|
1912
|
+
if (e4.type !== "null") return e4;
|
|
1913
|
+
}
|
|
1914
|
+
return i;
|
|
1915
|
+
});
|
|
1916
|
+
}, q.count = function(e3, t2, r2) {
|
|
1917
|
+
return h(function* () {
|
|
1918
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
1919
|
+
return n2.isArray() ? u(yield n2.reduce((e4) => e4 + 1, 0)) : i;
|
|
1920
|
+
});
|
|
1921
|
+
}, q.count.arity = 1, q.dateTime = function(e3, t2, r2) {
|
|
1922
|
+
return h(function* () {
|
|
1923
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
1924
|
+
return n2.type === "datetime" ? n2 : n2.type !== "string" ? i : c.parseToValue(n2.data);
|
|
1925
|
+
});
|
|
1926
|
+
}, q.dateTime.arity = 1, q.defined = function(e3, t2, r2) {
|
|
1927
|
+
return h(function* () {
|
|
1928
|
+
return (yield I(e3[0], t2, r2)).type === "null" ? a : s;
|
|
1929
|
+
});
|
|
1930
|
+
}, q.defined.arity = 1, q.identity = function(e3, t2) {
|
|
1931
|
+
return p(t2.context.identity);
|
|
1932
|
+
}, q.identity.arity = 0, q.length = function(e3, t2, r2) {
|
|
1933
|
+
return h(function* () {
|
|
1934
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
1935
|
+
return n2.type === "string" ? u(function(e4) {
|
|
1936
|
+
let t3 = 0;
|
|
1937
|
+
for (let r3 = 0; r3 < e4.length; r3++) {
|
|
1938
|
+
const n3 = e4.charCodeAt(r3);
|
|
1939
|
+
n3 >= 55296 && n3 <= 56319 || t3++;
|
|
1940
|
+
}
|
|
1941
|
+
return t3;
|
|
1942
|
+
}(n2.data)) : n2.isArray() ? u(yield n2.reduce((e4) => e4 + 1, 0)) : i;
|
|
1943
|
+
});
|
|
1944
|
+
}, q.length.arity = 1, q.path = function(t2, r2, n2) {
|
|
1945
|
+
return h(function* () {
|
|
1946
|
+
const s2 = yield I(t2[0], r2, n2);
|
|
1947
|
+
return s2.type !== "string" ? i : (a2 = new e(s2.data), new o(a2, "path"));
|
|
1948
|
+
var a2;
|
|
1949
|
+
});
|
|
1950
|
+
}, q.path.arity = 1, q.string = function(e3, t2, r2) {
|
|
1951
|
+
return h(function* () {
|
|
1952
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
1953
|
+
switch (n2.type) {
|
|
1954
|
+
case "number":
|
|
1955
|
+
case "string":
|
|
1956
|
+
case "boolean":
|
|
1957
|
+
case "datetime":
|
|
1958
|
+
return p(`${n2.data}`);
|
|
1959
|
+
default:
|
|
1960
|
+
return i;
|
|
1961
|
+
}
|
|
1962
|
+
});
|
|
1963
|
+
}, q.string.arity = 1, q.references = function(e3, t2, r2) {
|
|
1964
|
+
return h(function* () {
|
|
1965
|
+
const n2 = /* @__PURE__ */ new Set();
|
|
1966
|
+
for (const o2 of e3) {
|
|
1967
|
+
const e4 = yield I(o2, t2, r2);
|
|
1968
|
+
if (e4.type === "string") n2.add(e4.data);
|
|
1969
|
+
else if (e4.isArray()) {
|
|
1970
|
+
const t3 = yield e4.get();
|
|
1971
|
+
for (const e5 of t3) typeof e5 == "string" && n2.add(e5);
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
return n2.size === 0 ? a : R(yield t2.value.get(), n2) ? s : a;
|
|
1975
|
+
});
|
|
1976
|
+
}, q.references.arity = (e3) => e3 >= 1, q.round = function(e3, t2, r2) {
|
|
1977
|
+
return h(function* () {
|
|
1978
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
1979
|
+
if (n2.type !== "number") return i;
|
|
1980
|
+
const o2 = n2.data;
|
|
1981
|
+
let s2 = 0;
|
|
1982
|
+
if (e3.length === 2) {
|
|
1983
|
+
const n3 = yield I(e3[1], t2, r2);
|
|
1984
|
+
if (n3.type !== "number" || n3.data < 0 || !Number.isInteger(n3.data)) return i;
|
|
1985
|
+
s2 = n3.data;
|
|
1986
|
+
}
|
|
1987
|
+
return u(s2 === 0 ? o2 < 0 ? -Math.round(-o2) : Math.round(o2) : Number(o2.toFixed(s2)));
|
|
1988
|
+
});
|
|
1989
|
+
}, q.round.arity = (e3) => e3 >= 1 && e3 <= 2, q.now = function(e3, t2) {
|
|
1990
|
+
return p(t2.context.timestamp.toISOString());
|
|
1991
|
+
}, q.now.arity = 0, q.boost = function() {
|
|
1992
|
+
throw new Error("unexpected boost call");
|
|
1993
|
+
}, q.boost.arity = 2;
|
|
1994
|
+
const G = { lower: function(e3, t2, r2) {
|
|
1995
|
+
return h(function* () {
|
|
1996
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
1997
|
+
return n2.type !== "string" ? i : p(n2.data.toLowerCase());
|
|
1998
|
+
});
|
|
1999
|
+
} };
|
|
2000
|
+
G.lower.arity = 1, G.upper = function(e3, t2, r2) {
|
|
2001
|
+
return h(function* () {
|
|
2002
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2003
|
+
return n2.type !== "string" ? i : p(n2.data.toUpperCase());
|
|
2004
|
+
});
|
|
2005
|
+
}, G.upper.arity = 1, G.split = function(e3, t2, r2) {
|
|
2006
|
+
return h(function* () {
|
|
2007
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2008
|
+
if (n2.type !== "string") return i;
|
|
2009
|
+
const o2 = yield I(e3[1], t2, r2);
|
|
2010
|
+
return o2.type !== "string" ? i : n2.data.length === 0 ? f([], r2) : o2.data.length === 0 ? f(Array.from(n2.data), r2) : f(n2.data.split(o2.data), r2);
|
|
2011
|
+
});
|
|
2012
|
+
}, G.split.arity = 2, q.lower = G.lower, q.upper = G.upper, G.startsWith = function(e3, t2, r2) {
|
|
2013
|
+
return h(function* () {
|
|
2014
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2015
|
+
if (n2.type !== "string") return i;
|
|
2016
|
+
const o2 = yield I(e3[1], t2, r2);
|
|
2017
|
+
return o2.type !== "string" ? i : n2.data.startsWith(o2.data) ? s : a;
|
|
2018
|
+
});
|
|
2019
|
+
}, G.startsWith.arity = 2;
|
|
2020
|
+
const H = { join: function(e3, t2, r2) {
|
|
2021
|
+
return h(function* () {
|
|
2022
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2023
|
+
if (!n2.isArray()) return i;
|
|
2024
|
+
const o2 = yield I(e3[1], t2, r2);
|
|
2025
|
+
if (o2.type !== "string") return i;
|
|
2026
|
+
let s2 = "", a2 = !1;
|
|
2027
|
+
const c2 = yield n2.get();
|
|
2028
|
+
for (const e4 of c2) {
|
|
2029
|
+
const t3 = f(e4, r2);
|
|
2030
|
+
switch (a2 && (s2 += o2.data), t3.type) {
|
|
2031
|
+
case "number":
|
|
2032
|
+
case "string":
|
|
2033
|
+
case "boolean":
|
|
2034
|
+
case "datetime":
|
|
2035
|
+
s2 += `${t3.data}`;
|
|
2036
|
+
break;
|
|
2037
|
+
default:
|
|
2038
|
+
return i;
|
|
2039
|
+
}
|
|
2040
|
+
a2 = !0;
|
|
2041
|
+
}
|
|
2042
|
+
return f(s2, r2);
|
|
2043
|
+
});
|
|
2044
|
+
} };
|
|
2045
|
+
H.join.arity = 2, H.compact = function(e3, r2, n2) {
|
|
2046
|
+
return h(function* () {
|
|
2047
|
+
const o2 = yield I(e3[0], r2, n2);
|
|
2048
|
+
return o2.isArray() ? new t(async function* () {
|
|
2049
|
+
for await (const e4 of o2) e4.type !== "null" && (yield e4);
|
|
2050
|
+
}) : i;
|
|
2051
|
+
});
|
|
2052
|
+
}, H.compact.arity = 1, H.unique = function(e3, r2, n2) {
|
|
2053
|
+
return h(function* () {
|
|
2054
|
+
const s2 = yield I(e3[0], r2, n2);
|
|
2055
|
+
if (!s2.isArray()) return i;
|
|
2056
|
+
if (n2 === "sync") {
|
|
2057
|
+
const e4 = yield s2.get(), t2 = /* @__PURE__ */ new Set(), r3 = [];
|
|
2058
|
+
for (const n3 of e4) {
|
|
2059
|
+
const e5 = f(n3, "sync");
|
|
2060
|
+
switch (e5.type) {
|
|
2061
|
+
case "number":
|
|
2062
|
+
case "string":
|
|
2063
|
+
case "boolean":
|
|
2064
|
+
case "datetime":
|
|
2065
|
+
t2.has(n3) || (t2.add(n3), r3.push(e5));
|
|
2066
|
+
break;
|
|
2067
|
+
default:
|
|
2068
|
+
r3.push(e5);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
return new o(r3, "array");
|
|
2072
|
+
}
|
|
2073
|
+
return new t(async function* () {
|
|
2074
|
+
const e4 = /* @__PURE__ */ new Set();
|
|
2075
|
+
for await (const t2 of s2) switch (t2.type) {
|
|
2076
|
+
case "number":
|
|
2077
|
+
case "string":
|
|
2078
|
+
case "boolean":
|
|
2079
|
+
case "datetime":
|
|
2080
|
+
e4.has(t2.data) || (e4.add(t2.data), yield t2);
|
|
2081
|
+
break;
|
|
2082
|
+
default:
|
|
2083
|
+
yield t2;
|
|
2084
|
+
}
|
|
2085
|
+
});
|
|
2086
|
+
});
|
|
2087
|
+
}, H.unique.arity = 1, H.intersects = function(e3, t2, r2) {
|
|
2088
|
+
return h(function* () {
|
|
2089
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2090
|
+
if (!n2.isArray()) return i;
|
|
2091
|
+
const o2 = yield I(e3[1], t2, r2);
|
|
2092
|
+
return o2.isArray() ? (yield n2.first((e4) => !!o2.first((t3) => m(e4, t3)))) ? s : a : i;
|
|
2093
|
+
});
|
|
2094
|
+
}, H.intersects.arity = 2;
|
|
2095
|
+
const B = { text: function(e3, t2, r2) {
|
|
2096
|
+
return h(function* () {
|
|
2097
|
+
const n2 = yield I(e3[0], t2, r2), o2 = yield N(n2, r2);
|
|
2098
|
+
return o2 === null ? i : p(o2);
|
|
2099
|
+
});
|
|
2100
|
+
} };
|
|
2101
|
+
B.text.arity = 1;
|
|
2102
|
+
const W = { projectId: function(e3, t2) {
|
|
2103
|
+
return t2.context.sanity ? p(t2.context.sanity.projectId) : i;
|
|
2104
|
+
}, dataset: function(e3, t2) {
|
|
2105
|
+
return t2.context.sanity ? p(t2.context.sanity.dataset) : i;
|
|
2106
|
+
}, versionsOf: function(e3, t2, r2) {
|
|
2107
|
+
return h(function* () {
|
|
2108
|
+
if (!t2.source.isArray()) return i;
|
|
2109
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2110
|
+
if (n2.type !== "string") return i;
|
|
2111
|
+
const o2 = n2.data;
|
|
2112
|
+
return f(yield t2.source.reduce((e4, t3) => {
|
|
2113
|
+
if (y(t3) === "object") {
|
|
2114
|
+
const r3 = t3.get();
|
|
2115
|
+
r3 && "_id" in r3 && r3._id.split(".").length === 2 && r3._id.endsWith(`.${o2}`) && "_version" in r3 && typeof r3._version == "object" && e4.push(r3._id);
|
|
2116
|
+
}
|
|
2117
|
+
return e4;
|
|
2118
|
+
}, []), r2);
|
|
2119
|
+
});
|
|
2120
|
+
} };
|
|
2121
|
+
W.versionsOf.arity = 1, W.partOfRelease = function(e3, t2, r2) {
|
|
2122
|
+
return h(function* () {
|
|
2123
|
+
if (!t2.source.isArray()) return i;
|
|
2124
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2125
|
+
if (n2.type !== "string") return i;
|
|
2126
|
+
const o2 = n2.data;
|
|
2127
|
+
return f(yield t2.source.reduce((e4, t3) => {
|
|
2128
|
+
if (y(t3) === "object") {
|
|
2129
|
+
const r3 = t3.get();
|
|
2130
|
+
r3 && "_id" in r3 && r3._id.split(".").length === 2 && r3._id.startsWith(`${o2}.`) && "_version" in r3 && typeof r3._version == "object" && e4.push(r3._id);
|
|
2131
|
+
}
|
|
2132
|
+
return e4;
|
|
2133
|
+
}, []), r2);
|
|
2134
|
+
});
|
|
2135
|
+
}, W.partOfRelease.arity = 1;
|
|
2136
|
+
const Z = { order: function(e3, t2, r2, n2) {
|
|
2137
|
+
return h(function* () {
|
|
2138
|
+
if (!e3.isArray()) return i;
|
|
2139
|
+
const o2 = [], s2 = [];
|
|
2140
|
+
let a2 = 0;
|
|
2141
|
+
for (let e4 of t2) {
|
|
2142
|
+
let t3 = "asc";
|
|
2143
|
+
e4.type === "Desc" ? (t3 = "desc", e4 = e4.base) : e4.type === "Asc" && (e4 = e4.base), o2.push(e4), s2.push(t3), a2++;
|
|
2144
|
+
}
|
|
2145
|
+
const c2 = [];
|
|
2146
|
+
let u2 = 0;
|
|
2147
|
+
const p2 = yield e3.get();
|
|
2148
|
+
for (const e4 of p2) {
|
|
2149
|
+
const t3 = f(e4, n2), i2 = r2.createNested(t3), s3 = [yield t3.get(), u2];
|
|
2150
|
+
for (let e5 = 0; e5 < a2; e5++) {
|
|
2151
|
+
const t4 = yield I(o2[e5], i2, n2);
|
|
2152
|
+
s3.push(yield t4.get());
|
|
2153
|
+
}
|
|
2154
|
+
c2.push(s3), u2++;
|
|
2155
|
+
}
|
|
2156
|
+
return c2.sort((e4, t3) => {
|
|
2157
|
+
for (let r3 = 0; r3 < a2; r3++) {
|
|
2158
|
+
let n3 = E(e4[r3 + 2], t3[r3 + 2]);
|
|
2159
|
+
if (s2[r3] === "desc" && (n3 = -n3), n3 !== 0) return n3;
|
|
2160
|
+
}
|
|
2161
|
+
return e4[1] - t3[1];
|
|
2162
|
+
}), f(c2.map((e4) => e4[0]), n2);
|
|
2163
|
+
});
|
|
2164
|
+
} };
|
|
2165
|
+
Z.order.arity = (e3) => e3 >= 1, Z.score = function(e3, t2, r2, n2) {
|
|
2166
|
+
return h(function* () {
|
|
2167
|
+
if (!e3.isArray()) return i;
|
|
2168
|
+
const o2 = [], s2 = [], a2 = yield e3.get();
|
|
2169
|
+
for (const e4 of a2) {
|
|
2170
|
+
const i2 = f(e4, n2);
|
|
2171
|
+
if (i2.type !== "object") {
|
|
2172
|
+
o2.push(yield i2.get());
|
|
2173
|
+
continue;
|
|
2174
|
+
}
|
|
2175
|
+
const a3 = r2.createNested(i2);
|
|
2176
|
+
let c2 = typeof i2.data._score == "number" ? i2.data._score : 0;
|
|
2177
|
+
for (const e5 of t2) c2 += yield F(e5, a3, n2);
|
|
2178
|
+
const u2 = Object.assign({}, i2.data, { _score: c2 });
|
|
2179
|
+
s2.push(u2);
|
|
2180
|
+
}
|
|
2181
|
+
return s2.sort((e4, t3) => t3._score - e4._score), f(s2, n2);
|
|
2182
|
+
});
|
|
2183
|
+
}, Z.score.arity = (e3) => e3 >= 1;
|
|
2184
|
+
const z = { operation: function(e3, t2) {
|
|
2185
|
+
const r2 = t2.context.before !== null, n2 = t2.context.after !== null;
|
|
2186
|
+
return r2 && n2 ? p("update") : n2 ? p("create") : r2 ? p("delete") : i;
|
|
2187
|
+
}, changedAny: () => {
|
|
2188
|
+
throw new Error("not implemented");
|
|
2189
|
+
} };
|
|
2190
|
+
z.changedAny.arity = 1, z.changedAny.mode = "delta", z.changedOnly = () => {
|
|
2191
|
+
throw new Error("not implemented");
|
|
2192
|
+
}, z.changedOnly.arity = 1, z.changedOnly.mode = "delta";
|
|
2193
|
+
const J = { changedAny: () => {
|
|
2194
|
+
throw new Error("not implemented");
|
|
2195
|
+
} };
|
|
2196
|
+
J.changedAny.arity = 3, J.changedOnly = () => {
|
|
2197
|
+
throw new Error("not implemented");
|
|
2198
|
+
}, J.changedOnly.arity = 3;
|
|
2199
|
+
const Q = { min: function(e3, t2, r2) {
|
|
2200
|
+
return h(function* () {
|
|
2201
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2202
|
+
if (!n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number"))) return i;
|
|
2203
|
+
const o2 = yield n2.get();
|
|
2204
|
+
let s2;
|
|
2205
|
+
for (const e4 of o2) typeof e4 == "number" && (s2 === void 0 || e4 < s2) && (s2 = e4);
|
|
2206
|
+
return f(s2, r2);
|
|
2207
|
+
});
|
|
2208
|
+
} };
|
|
2209
|
+
Q.min.arity = 1, Q.max = function(e3, t2, r2) {
|
|
2210
|
+
return h(function* () {
|
|
2211
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2212
|
+
if (!n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number"))) return i;
|
|
2213
|
+
const o2 = yield n2.get();
|
|
2214
|
+
let s2;
|
|
2215
|
+
for (const e4 of o2) typeof e4 == "number" && (s2 === void 0 || e4 > s2) && (s2 = e4);
|
|
2216
|
+
return f(s2, r2);
|
|
2217
|
+
});
|
|
2218
|
+
}, Q.max.arity = 1, Q.sum = function(e3, t2, r2) {
|
|
2219
|
+
return h(function* () {
|
|
2220
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2221
|
+
return !n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number")) ? i : f(yield n2.reduce((e4, t3) => t3.type !== "number" ? e4 : e4 + t3.data, 0), r2);
|
|
2222
|
+
});
|
|
2223
|
+
}, Q.sum.arity = 1, Q.avg = function(e3, t2, r2) {
|
|
2224
|
+
return h(function* () {
|
|
2225
|
+
const n2 = yield I(e3[0], t2, r2);
|
|
2226
|
+
if (!n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number"))) return i;
|
|
2227
|
+
const o2 = yield n2.reduce((e4, t3) => t3.type !== "number" ? e4 : e4 + 1, 0), s2 = yield n2.reduce((e4, t3) => t3.type !== "number" ? e4 : e4 + t3.data, 0);
|
|
2228
|
+
return o2 === 0 ? i : f(s2 / o2, r2);
|
|
2229
|
+
});
|
|
2230
|
+
}, Q.avg.arity = 1;
|
|
2231
|
+
const L = { now: function(e3, t2) {
|
|
2232
|
+
return l(new c(t2.context.timestamp));
|
|
2233
|
+
} };
|
|
2234
|
+
L.now.arity = 0;
|
|
2235
|
+
const Y = { global: q, string: G, array: H, pt: B, delta: z, diff: J, sanity: W, math: Q, dateTime: L };
|
|
2236
|
+
class K {
|
|
2237
|
+
string;
|
|
2238
|
+
marks;
|
|
2239
|
+
index;
|
|
2240
|
+
parseOptions;
|
|
2241
|
+
allowBoost = !1;
|
|
2242
|
+
constructor(e3, t2, r2) {
|
|
2243
|
+
this.string = e3, this.marks = t2, this.index = 0, this.parseOptions = r2;
|
|
2244
|
+
}
|
|
2245
|
+
hasMark(e3 = 0) {
|
|
2246
|
+
return this.index + e3 < this.marks.length;
|
|
2247
|
+
}
|
|
2248
|
+
getMark(e3 = 0) {
|
|
2249
|
+
return this.marks[this.index + e3];
|
|
2250
|
+
}
|
|
2251
|
+
shift() {
|
|
2252
|
+
this.index += 1;
|
|
2253
|
+
}
|
|
2254
|
+
process(e3) {
|
|
2255
|
+
const t2 = this.marks[this.index];
|
|
2256
|
+
this.shift();
|
|
2257
|
+
const r2 = e3[t2.name];
|
|
2258
|
+
if (!r2) throw new Error(`Unknown handler: ${t2.name}`);
|
|
2259
|
+
return r2.call(e3, this, t2);
|
|
2260
|
+
}
|
|
2261
|
+
processString() {
|
|
2262
|
+
return this.shift(), this.processStringEnd();
|
|
2263
|
+
}
|
|
2264
|
+
processStringEnd() {
|
|
2265
|
+
const e3 = this.marks[this.index - 1], t2 = this.marks[this.index];
|
|
2266
|
+
return this.shift(), this.string.slice(e3.position, t2.position);
|
|
2267
|
+
}
|
|
2268
|
+
slice(e3) {
|
|
2269
|
+
const t2 = this.marks[this.index].position;
|
|
2270
|
+
return this.string.slice(t2, t2 + e3);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
const X = /^([\t\n\v\f\r \u0085\u00A0]|(\/\/[^\n]*\n))+/, ee = /^\d+/, te = /^[a-zA-Z_][a-zA-Z_0-9]*/;
|
|
2274
|
+
function re(e3, t2, r2) {
|
|
2275
|
+
let n2, o2 = t2;
|
|
2276
|
+
switch (e3[t2]) {
|
|
2277
|
+
case "+": {
|
|
2278
|
+
let r3 = re(e3, se(e3, t2 + 1), 10);
|
|
2279
|
+
if (r3.type === "error") return r3;
|
|
2280
|
+
n2 = [{ name: "pos", position: o2 }].concat(r3.marks), t2 = r3.position;
|
|
2281
|
+
break;
|
|
2282
|
+
}
|
|
2283
|
+
case "-": {
|
|
2284
|
+
let r3 = re(e3, se(e3, t2 + 1), 8);
|
|
2285
|
+
if (r3.type === "error") return r3;
|
|
2286
|
+
n2 = [{ name: "neg", position: o2 }].concat(r3.marks), t2 = r3.position;
|
|
2287
|
+
break;
|
|
2288
|
+
}
|
|
2289
|
+
case "(": {
|
|
2290
|
+
let r3 = re(e3, se(e3, t2 + 1), 0);
|
|
2291
|
+
if (r3.type === "error") return r3;
|
|
2292
|
+
switch (e3[t2 = se(e3, r3.position)]) {
|
|
2293
|
+
case ",":
|
|
2294
|
+
for (n2 = [{ name: "tuple", position: o2 }].concat(r3.marks), t2 = se(e3, t2 + 1); ; ) {
|
|
2295
|
+
if (r3 = re(e3, t2, 0), r3.type === "error") return r3;
|
|
2296
|
+
if (e3[t2 = se(e3, r3.position)] !== ",") break;
|
|
2297
|
+
t2 = se(e3, t2 + 1);
|
|
2298
|
+
}
|
|
2299
|
+
if (e3[t2] !== ")") return { type: "error", position: t2 };
|
|
2300
|
+
t2++, n2.push({ name: "tuple_end", position: t2 });
|
|
2301
|
+
break;
|
|
2302
|
+
case ")":
|
|
2303
|
+
t2++, n2 = [{ name: "group", position: o2 }].concat(r3.marks);
|
|
2304
|
+
break;
|
|
2305
|
+
default:
|
|
2306
|
+
return { type: "error", position: t2 };
|
|
2307
|
+
}
|
|
2308
|
+
break;
|
|
2309
|
+
}
|
|
2310
|
+
case "!": {
|
|
2311
|
+
let r3 = re(e3, se(e3, t2 + 1), 10);
|
|
2312
|
+
if (r3.type === "error") return r3;
|
|
2313
|
+
n2 = [{ name: "not", position: o2 }].concat(r3.marks), t2 = r3.position;
|
|
2314
|
+
break;
|
|
2315
|
+
}
|
|
2316
|
+
case "{": {
|
|
2317
|
+
let r3 = ie(e3, t2);
|
|
2318
|
+
if (r3.type === "error") return r3;
|
|
2319
|
+
n2 = r3.marks, t2 = r3.position;
|
|
2320
|
+
break;
|
|
2321
|
+
}
|
|
2322
|
+
case "[":
|
|
2323
|
+
if (n2 = [{ name: "array", position: t2 }], e3[t2 = se(e3, t2 + 1)] !== "]") for (; ; ) {
|
|
2324
|
+
e3.slice(t2, t2 + 3) === "..." && (n2.push({ name: "array_splat", position: t2 }), t2 = se(e3, t2 + 3));
|
|
2325
|
+
let r3 = re(e3, t2, 0);
|
|
2326
|
+
if (r3.type === "error") return r3;
|
|
2327
|
+
if (n2 = n2.concat(r3.marks), e3[t2 = se(e3, t2 = r3.position)] !== "," || e3[t2 = se(e3, t2 + 1)] === "]") break;
|
|
2328
|
+
}
|
|
2329
|
+
if (e3[t2] !== "]") return { type: "error", position: t2 };
|
|
2330
|
+
t2++, n2.push({ name: "array_end", position: t2 });
|
|
2331
|
+
break;
|
|
2332
|
+
case "'":
|
|
2333
|
+
case '"': {
|
|
2334
|
+
let r3 = function(e4, t3) {
|
|
2335
|
+
let r4 = e4[t3];
|
|
2336
|
+
t3 += 1;
|
|
2337
|
+
const n3 = [{ name: "str", position: t3 }];
|
|
2338
|
+
e: for (; ; t3++) {
|
|
2339
|
+
if (t3 > e4.length) return { type: "error", position: t3 };
|
|
2340
|
+
switch (e4[t3]) {
|
|
2341
|
+
case r4:
|
|
2342
|
+
n3.push({ name: "str_end", position: t3 }), t3++;
|
|
2343
|
+
break e;
|
|
2344
|
+
case "\\":
|
|
2345
|
+
n3.push({ name: "str_pause", position: t3 }), e4[t3 + 1] === "u" ? e4[t3 + 2] === "{" ? (n3.push({ name: "unicode_hex", position: t3 + 3 }), t3 = e4.indexOf("}", t3 + 3), n3.push({ name: "unicode_hex_end", position: t3 })) : (n3.push({ name: "unicode_hex", position: t3 + 2 }), n3.push({ name: "unicode_hex_end", position: t3 + 6 }), t3 += 5) : (n3.push({ name: "single_escape", position: t3 + 1 }), t3 += 1), n3.push({ name: "str_start", position: t3 + 1 });
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
return { type: "success", marks: n3, position: t3 };
|
|
2349
|
+
}(e3, t2);
|
|
2350
|
+
if (r3.type === "error") return r3;
|
|
2351
|
+
n2 = r3.marks, t2 = r3.position;
|
|
2352
|
+
break;
|
|
2353
|
+
}
|
|
2354
|
+
case "^":
|
|
2355
|
+
for (t2++, n2 = []; e3[t2] === "." && e3[t2 + 1] === "^"; ) n2.push({ name: "dblparent", position: o2 }), t2 += 2;
|
|
2356
|
+
n2.push({ name: "parent", position: o2 });
|
|
2357
|
+
break;
|
|
2358
|
+
case "@":
|
|
2359
|
+
n2 = [{ name: "this", position: o2 }], t2++;
|
|
2360
|
+
break;
|
|
2361
|
+
case "*":
|
|
2362
|
+
n2 = [{ name: "everything", position: o2 }], t2++;
|
|
2363
|
+
break;
|
|
2364
|
+
case "$": {
|
|
2365
|
+
let r3 = ae(e3, t2 + 1, te);
|
|
2366
|
+
r3 && (n2 = [{ name: "param", position: o2 }, { name: "ident", position: o2 + 1 }, { name: "ident_end", position: t2 += 1 + r3 }]);
|
|
2367
|
+
break;
|
|
2368
|
+
}
|
|
2369
|
+
default: {
|
|
2370
|
+
let r3 = ae(e3, t2, ee);
|
|
2371
|
+
if (r3) {
|
|
2372
|
+
let i4 = "integer";
|
|
2373
|
+
if (e3[t2 += r3] === ".") {
|
|
2374
|
+
let r4 = ae(e3, t2 + 1, ee);
|
|
2375
|
+
r4 && (i4 = "float", t2 += 1 + r4);
|
|
2376
|
+
}
|
|
2377
|
+
if (e3[t2] === "e" || e3[t2] === "E") {
|
|
2378
|
+
i4 = "sci", (e3[++t2] === "+" || e3[t2] === "-") && t2++;
|
|
2379
|
+
let r4 = ae(e3, t2, ee);
|
|
2380
|
+
if (!r4) return { type: "error", position: t2 };
|
|
2381
|
+
t2 += r4;
|
|
2382
|
+
}
|
|
2383
|
+
n2 = [{ name: i4, position: o2 }, { name: i4 + "_end", position: t2 }];
|
|
2384
|
+
break;
|
|
2385
|
+
}
|
|
2386
|
+
let i3 = ae(e3, t2, te);
|
|
2387
|
+
if (i3) {
|
|
2388
|
+
switch (e3[t2 += i3]) {
|
|
2389
|
+
case ":":
|
|
2390
|
+
case "(": {
|
|
2391
|
+
let r4 = oe(e3, o2, t2);
|
|
2392
|
+
if (r4.type === "error") return r4;
|
|
2393
|
+
n2 = r4.marks, t2 = r4.position;
|
|
2394
|
+
break;
|
|
2395
|
+
}
|
|
2396
|
+
default:
|
|
2397
|
+
n2 = [{ name: "this_attr", position: o2 }, { name: "ident", position: o2 }, { name: "ident_end", position: t2 }];
|
|
2398
|
+
}
|
|
2399
|
+
break;
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
if (!n2) return { type: "error", position: t2 };
|
|
2404
|
+
let i2, s2 = 12;
|
|
2405
|
+
e: for (; ; ) {
|
|
2406
|
+
let a2 = se(e3, t2);
|
|
2407
|
+
if (a2 === e3.length) {
|
|
2408
|
+
t2 = a2;
|
|
2409
|
+
break;
|
|
2410
|
+
}
|
|
2411
|
+
if (i2 = ne(e3, a2), i2.type !== "success") switch (e3[a2]) {
|
|
2412
|
+
case "=":
|
|
2413
|
+
switch (e3[a2 + 1]) {
|
|
2414
|
+
case ">": {
|
|
2415
|
+
if (r2 > 1 || s2 <= 1) break e;
|
|
2416
|
+
let i3 = re(e3, se(e3, a2 + 2), 1);
|
|
2417
|
+
if (i3.type === "error") return i3;
|
|
2418
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "pair", position: o2 }), t2 = i3.position, s2 = 1;
|
|
2419
|
+
break;
|
|
2420
|
+
}
|
|
2421
|
+
case "=": {
|
|
2422
|
+
if (r2 > 4 || s2 <= 4) break e;
|
|
2423
|
+
let i3 = re(e3, se(e3, a2 + 2), 5);
|
|
2424
|
+
if (i3.type === "error") return i3;
|
|
2425
|
+
n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 2 }), n2 = n2.concat(i3.marks), t2 = i3.position, s2 = 4;
|
|
2426
|
+
break;
|
|
2427
|
+
}
|
|
2428
|
+
default:
|
|
2429
|
+
break e;
|
|
2430
|
+
}
|
|
2431
|
+
break;
|
|
2432
|
+
case "+": {
|
|
2433
|
+
if (r2 > 6 || s2 < 6) break e;
|
|
2434
|
+
let i3 = re(e3, se(e3, a2 + 1), 7);
|
|
2435
|
+
if (i3.type === "error") return i3;
|
|
2436
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "add", position: o2 }), t2 = i3.position, s2 = 6;
|
|
2437
|
+
break;
|
|
2438
|
+
}
|
|
2439
|
+
case "-": {
|
|
2440
|
+
if (r2 > 6 || s2 < 6) break e;
|
|
2441
|
+
let i3 = re(e3, se(e3, a2 + 1), 7);
|
|
2442
|
+
if (i3.type === "error") return i3;
|
|
2443
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "sub", position: o2 }), t2 = i3.position, s2 = 6;
|
|
2444
|
+
break;
|
|
2445
|
+
}
|
|
2446
|
+
case "*": {
|
|
2447
|
+
if (e3[a2 + 1] === "*") {
|
|
2448
|
+
if (r2 > 8 || s2 <= 8) break e;
|
|
2449
|
+
let i4 = re(e3, se(e3, a2 + 2), 8);
|
|
2450
|
+
if (i4.type === "error") return i4;
|
|
2451
|
+
n2 = n2.concat(i4.marks), n2.unshift({ name: "pow", position: o2 }), t2 = i4.position, s2 = 8;
|
|
2452
|
+
break;
|
|
2453
|
+
}
|
|
2454
|
+
if (r2 > 7 || s2 < 7) break e;
|
|
2455
|
+
let i3 = re(e3, se(e3, a2 + 1), 8);
|
|
2456
|
+
if (i3.type === "error") return i3;
|
|
2457
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "mul", position: o2 }), t2 = i3.position, s2 = 7;
|
|
2458
|
+
break;
|
|
2459
|
+
}
|
|
2460
|
+
case "/": {
|
|
2461
|
+
if (r2 > 7 || s2 < 7) break e;
|
|
2462
|
+
let i3 = re(e3, se(e3, a2 + 1), 8);
|
|
2463
|
+
if (i3.type === "error") return i3;
|
|
2464
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "div", position: o2 }), t2 = i3.position, s2 = 7;
|
|
2465
|
+
break;
|
|
2466
|
+
}
|
|
2467
|
+
case "%": {
|
|
2468
|
+
if (r2 > 7 || s2 < 7) break e;
|
|
2469
|
+
let i3 = re(e3, se(e3, a2 + 1), 8);
|
|
2470
|
+
if (i3.type === "error") return i3;
|
|
2471
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "mod", position: o2 }), t2 = i3.position, s2 = 7;
|
|
2472
|
+
break;
|
|
2473
|
+
}
|
|
2474
|
+
case "<":
|
|
2475
|
+
case ">": {
|
|
2476
|
+
if (r2 > 4 || s2 <= 4) break e;
|
|
2477
|
+
let i3 = a2 + 1;
|
|
2478
|
+
e3[i3] === "=" && i3++;
|
|
2479
|
+
let c2 = re(e3, se(e3, i3), 5);
|
|
2480
|
+
if (c2.type === "error") return c2;
|
|
2481
|
+
n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: i3 }), n2 = n2.concat(c2.marks), t2 = c2.position, s2 = 4;
|
|
2482
|
+
break;
|
|
2483
|
+
}
|
|
2484
|
+
case "|":
|
|
2485
|
+
if (e3[a2 + 1] === "|") {
|
|
2486
|
+
if (r2 > 2 || s2 < 2) break e;
|
|
2487
|
+
let i3 = re(e3, se(e3, a2 + 2), 3);
|
|
2488
|
+
if (i3.type === "error") return i3;
|
|
2489
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "or", position: o2 }), t2 = i3.position, s2 = 2;
|
|
2490
|
+
} else {
|
|
2491
|
+
if (r2 > 11 || s2 < 11) break e;
|
|
2492
|
+
let i3 = se(e3, a2 + 1), c2 = ae(e3, i3, te);
|
|
2493
|
+
if (!c2) return { type: "error", position: i3 };
|
|
2494
|
+
if (e3[t2 = i3 + c2] === "(" || e3[t2] === ":") {
|
|
2495
|
+
let r3 = oe(e3, i3, t2);
|
|
2496
|
+
if (r3.type === "error") return r3;
|
|
2497
|
+
n2 = n2.concat(r3.marks), n2.unshift({ name: "pipecall", position: o2 }), t2 = r3.position, s2 = 11;
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
break;
|
|
2501
|
+
case "&": {
|
|
2502
|
+
if (e3[a2 + 1] != "&" || r2 > 3 || s2 < 3) break e;
|
|
2503
|
+
let i3 = re(e3, se(e3, a2 + 2), 4);
|
|
2504
|
+
if (i3.type === "error") return i3;
|
|
2505
|
+
n2 = n2.concat(i3.marks), n2.unshift({ name: "and", position: o2 }), t2 = i3.position, s2 = 3;
|
|
2506
|
+
break;
|
|
2507
|
+
}
|
|
2508
|
+
case "!": {
|
|
2509
|
+
if (e3[a2 + 1] !== "=" || r2 > 4 || s2 <= 4) break e;
|
|
2510
|
+
let i3 = re(e3, se(e3, a2 + 2), 5);
|
|
2511
|
+
if (i3.type === "error") return i3;
|
|
2512
|
+
n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 2 }), n2 = n2.concat(i3.marks), t2 = i3.position, s2 = 4;
|
|
2513
|
+
break;
|
|
2514
|
+
}
|
|
2515
|
+
case "d":
|
|
2516
|
+
if (e3.slice(a2, a2 + 4) !== "desc" || r2 > 4 || s2 < 4) break e;
|
|
2517
|
+
n2.unshift({ name: "desc", position: o2 }), t2 = a2 + 4, s2 = 4;
|
|
2518
|
+
break;
|
|
2519
|
+
case "a":
|
|
2520
|
+
if (e3.slice(a2, a2 + 3) !== "asc" || r2 > 4 || s2 < 4) break e;
|
|
2521
|
+
n2.unshift({ name: "asc", position: o2 }), t2 = a2 + 3, s2 = 4;
|
|
2522
|
+
break;
|
|
2523
|
+
default:
|
|
2524
|
+
switch (ce(e3, a2, te)) {
|
|
2525
|
+
case "in": {
|
|
2526
|
+
if (r2 > 4 || s2 <= 4) break e;
|
|
2527
|
+
let i3 = !1;
|
|
2528
|
+
e3[t2 = se(e3, a2 + 2)] === "(" && (i3 = !0, t2 = se(e3, t2 + 1));
|
|
2529
|
+
let c2 = t2, u2 = re(e3, t2, 5);
|
|
2530
|
+
if (u2.type === "error") return u2;
|
|
2531
|
+
if (e3[t2 = se(e3, u2.position)] === "." && e3[t2 + 1] === ".") {
|
|
2532
|
+
let r3 = "inc_range";
|
|
2533
|
+
e3[t2 + 2] === "." ? (r3 = "exc_range", t2 = se(e3, t2 + 3)) : t2 = se(e3, t2 + 2);
|
|
2534
|
+
let i4 = re(e3, t2, 5);
|
|
2535
|
+
if (i4.type === "error") return i4;
|
|
2536
|
+
n2.unshift({ name: "in_range", position: o2 }), n2 = n2.concat({ name: r3, position: c2 }, u2.marks, i4.marks), t2 = i4.position;
|
|
2537
|
+
} else n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 2 }), n2 = n2.concat(u2.marks);
|
|
2538
|
+
if (i3) {
|
|
2539
|
+
if (e3[t2 = se(e3, t2)] !== ")") return { type: "error", position: t2 };
|
|
2540
|
+
t2++;
|
|
2541
|
+
}
|
|
2542
|
+
s2 = 4;
|
|
2543
|
+
break;
|
|
2544
|
+
}
|
|
2545
|
+
case "match": {
|
|
2546
|
+
if (r2 > 4 || s2 <= 4) break e;
|
|
2547
|
+
let i3 = re(e3, se(e3, a2 + 5), 5);
|
|
2548
|
+
if (i3.type === "error") return i3;
|
|
2549
|
+
n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 5 }), n2 = n2.concat(i3.marks), t2 = i3.position, s2 = 4;
|
|
2550
|
+
break;
|
|
2551
|
+
}
|
|
2552
|
+
default:
|
|
2553
|
+
break e;
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
else {
|
|
2557
|
+
for (n2.unshift({ name: "traverse", position: o2 }); i2.type === "success"; ) n2 = n2.concat(i2.marks), i2 = ne(e3, se(e3, t2 = i2.position));
|
|
2558
|
+
n2.push({ name: "traversal_end", position: t2 });
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
return { type: "success", marks: n2, position: t2, failPosition: i2?.type === "error" && i2.position };
|
|
2562
|
+
}
|
|
2563
|
+
function ne(e3, t2) {
|
|
2564
|
+
let r2 = t2;
|
|
2565
|
+
switch (e3[t2]) {
|
|
2566
|
+
case ".": {
|
|
2567
|
+
let n3 = t2 = se(e3, t2 + 1), o3 = ae(e3, t2, te);
|
|
2568
|
+
return o3 ? { type: "success", marks: [{ name: "attr_access", position: r2 }, { name: "ident", position: n3 }, { name: "ident_end", position: t2 += o3 }], position: t2 } : { type: "error", position: t2 };
|
|
2569
|
+
}
|
|
2570
|
+
case "-":
|
|
2571
|
+
if (e3[t2 + 1] !== ">") return { type: "error", position: t2 };
|
|
2572
|
+
let n2 = [{ name: "deref", position: r2 }], o2 = se(e3, t2 += 2), i2 = ae(e3, o2, te);
|
|
2573
|
+
return i2 && (t2 = o2 + i2, n2.push({ name: "deref_attr", position: o2 }, { name: "ident", position: o2 }, { name: "ident_end", position: t2 })), { type: "success", marks: n2, position: t2 };
|
|
2574
|
+
case "[": {
|
|
2575
|
+
if (e3[t2 = se(e3, t2 + 1)] === "]") return { type: "success", marks: [{ name: "array_postfix", position: r2 }], position: t2 + 1 };
|
|
2576
|
+
let n3 = t2, o3 = re(e3, t2, 0);
|
|
2577
|
+
if (o3.type === "error") return o3;
|
|
2578
|
+
if (e3[t2 = se(e3, o3.position)] === "." && e3[t2 + 1] === ".") {
|
|
2579
|
+
let i3 = "inc_range";
|
|
2580
|
+
e3[t2 + 2] === "." ? (i3 = "exc_range", t2 += 3) : t2 += 2;
|
|
2581
|
+
let s2 = re(e3, t2 = se(e3, t2), 0);
|
|
2582
|
+
return s2.type === "error" ? s2 : e3[t2 = se(e3, s2.position)] !== "]" ? { type: "error", position: t2 } : { type: "success", marks: [{ name: "slice", position: r2 }, { name: i3, position: n3 }].concat(o3.marks, s2.marks), position: t2 + 1 };
|
|
2583
|
+
}
|
|
2584
|
+
return e3[t2] !== "]" ? { type: "error", position: t2 } : { type: "success", marks: [{ name: "square_bracket", position: r2 }].concat(o3.marks), position: t2 + 1 };
|
|
2585
|
+
}
|
|
2586
|
+
case "|":
|
|
2587
|
+
if (e3[t2 = se(e3, t2 + 1)] === "{") {
|
|
2588
|
+
let n3 = ie(e3, t2);
|
|
2589
|
+
return n3.type === "error" || n3.marks.unshift({ name: "projection", position: r2 }), n3;
|
|
2590
|
+
}
|
|
2591
|
+
break;
|
|
2592
|
+
case "{": {
|
|
2593
|
+
let n3 = ie(e3, t2);
|
|
2594
|
+
return n3.type === "error" || n3.marks.unshift({ name: "projection", position: r2 }), n3;
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
return { type: "error", position: t2 };
|
|
2598
|
+
}
|
|
2599
|
+
function oe(e3, t2, r2) {
|
|
2600
|
+
let n2 = [];
|
|
2601
|
+
if (n2.push({ name: "func_call", position: t2 }), e3[r2] === ":" && e3[r2 + 1] === ":") {
|
|
2602
|
+
n2.push({ name: "namespace", position: t2 }), n2.push({ name: "ident", position: t2 }, { name: "ident_end", position: r2 });
|
|
2603
|
+
let o3 = ae(e3, r2 = se(e3, r2 + 2), te);
|
|
2604
|
+
if (!o3) return { type: "error", position: r2 };
|
|
2605
|
+
if (n2.push({ name: "ident", position: r2 }, { name: "ident_end", position: r2 + o3 }), e3[r2 = se(e3, r2 + o3)] !== "(") return { type: "error", position: r2 };
|
|
2606
|
+
r2 = se(e3, ++r2);
|
|
2607
|
+
} else n2.push({ name: "ident", position: t2 }, { name: "ident_end", position: r2 }), r2 = se(e3, r2 + 1);
|
|
2608
|
+
let o2 = r2;
|
|
2609
|
+
if (e3[r2] !== ")") for (; ; ) {
|
|
2610
|
+
let t3 = re(e3, r2, 0);
|
|
2611
|
+
if (t3.type === "error") return t3;
|
|
2612
|
+
if (n2 = n2.concat(t3.marks), o2 = t3.position, e3[r2 = se(e3, t3.position)] !== "," || e3[r2 = se(e3, r2 + 1)] === ")") break;
|
|
2613
|
+
}
|
|
2614
|
+
return e3[r2] !== ")" ? { type: "error", position: r2 } : (n2.push({ name: "func_args_end", position: o2 }), { type: "success", marks: n2, position: r2 + 1 });
|
|
2615
|
+
}
|
|
2616
|
+
function ie(e3, t2) {
|
|
2617
|
+
let r2 = [{ name: "object", position: t2 }];
|
|
2618
|
+
for (t2 = se(e3, t2 + 1); e3[t2] !== "}"; ) {
|
|
2619
|
+
let n2 = t2;
|
|
2620
|
+
if (e3.slice(t2, t2 + 3) === "...") if (e3[t2 = se(e3, t2 + 3)] !== "}" && e3[t2] !== ",") {
|
|
2621
|
+
let o2 = re(e3, t2, 0);
|
|
2622
|
+
if (o2.type === "error") return o2;
|
|
2623
|
+
r2.push({ name: "object_splat", position: n2 }), r2 = r2.concat(o2.marks), t2 = o2.position;
|
|
2624
|
+
} else r2.push({ name: "object_splat_this", position: n2 });
|
|
2625
|
+
else {
|
|
2626
|
+
let o2 = re(e3, t2, 0);
|
|
2627
|
+
if (o2.type === "error") return o2;
|
|
2628
|
+
let i2 = se(e3, o2.position);
|
|
2629
|
+
if (o2.marks[0].name === "str" && e3[i2] === ":") {
|
|
2630
|
+
let s2 = re(e3, se(e3, i2 + 1), 0);
|
|
2631
|
+
if (s2.type === "error") return s2;
|
|
2632
|
+
r2.push({ name: "object_pair", position: n2 }), r2 = r2.concat(o2.marks, s2.marks), t2 = s2.position;
|
|
2633
|
+
} else r2 = r2.concat({ name: "object_expr", position: t2 }, o2.marks), t2 = o2.position;
|
|
2634
|
+
}
|
|
2635
|
+
if (e3[t2 = se(e3, t2)] !== ",") break;
|
|
2636
|
+
t2 = se(e3, t2 + 1);
|
|
2637
|
+
}
|
|
2638
|
+
return e3[t2] !== "}" ? { type: "error", position: t2 } : (t2++, r2.push({ name: "object_end", position: t2 }), { type: "success", marks: r2, position: t2 });
|
|
2639
|
+
}
|
|
2640
|
+
function se(e3, t2) {
|
|
2641
|
+
return t2 + ae(e3, t2, X);
|
|
2642
|
+
}
|
|
2643
|
+
function ae(e3, t2, r2) {
|
|
2644
|
+
let n2 = r2.exec(e3.slice(t2));
|
|
2645
|
+
return n2 ? n2[0].length : 0;
|
|
2646
|
+
}
|
|
2647
|
+
function ce(e3, t2, r2) {
|
|
2648
|
+
let n2 = r2.exec(e3.slice(t2));
|
|
2649
|
+
return n2 ? n2[0] : null;
|
|
2650
|
+
}
|
|
2651
|
+
function ue(e3, t2) {
|
|
2652
|
+
return (r2) => t2(e3(r2));
|
|
2653
|
+
}
|
|
2654
|
+
function pe(e3) {
|
|
2655
|
+
return (t2) => ({ type: "Map", base: t2, expr: e3({ type: "This" }) });
|
|
2656
|
+
}
|
|
2657
|
+
function le(e3, t2) {
|
|
2658
|
+
if (!t2) return { type: "a-a", build: e3 };
|
|
2659
|
+
switch (t2.type) {
|
|
2660
|
+
case "a-a":
|
|
2661
|
+
return { type: "a-a", build: ue(e3, t2.build) };
|
|
2662
|
+
case "a-b":
|
|
2663
|
+
return { type: "a-b", build: ue(e3, t2.build) };
|
|
2664
|
+
case "b-b":
|
|
2665
|
+
return { type: "a-a", build: ue(e3, pe(t2.build)) };
|
|
2666
|
+
case "b-a":
|
|
2667
|
+
return { type: "a-a", build: ue(e3, (r2 = t2.build, (e4) => ({ type: "FlatMap", base: e4, expr: r2({ type: "This" }) }))) };
|
|
2668
|
+
default:
|
|
2669
|
+
throw new Error(`unknown type: ${t2.type}`);
|
|
2670
|
+
}
|
|
2671
|
+
var r2;
|
|
2672
|
+
}
|
|
2673
|
+
function fe(e3, t2) {
|
|
2674
|
+
if (!t2) return { type: "b-b", build: e3 };
|
|
2675
|
+
switch (t2.type) {
|
|
2676
|
+
case "a-a":
|
|
2677
|
+
case "b-a":
|
|
2678
|
+
return { type: "b-a", build: ue(e3, t2.build) };
|
|
2679
|
+
case "a-b":
|
|
2680
|
+
case "b-b":
|
|
2681
|
+
return { type: "b-b", build: ue(e3, t2.build) };
|
|
2682
|
+
default:
|
|
2683
|
+
throw new Error(`unknown type: ${t2.type}`);
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
const ye = { "'": "'", '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: `
|
|
2687
|
+
`, r: "\r", t: " " };
|
|
2688
|
+
function de(e3) {
|
|
2689
|
+
const t2 = parseInt(e3, 16);
|
|
2690
|
+
return String.fromCharCode(t2);
|
|
2691
|
+
}
|
|
2692
|
+
class he extends Error {
|
|
2693
|
+
name = "GroqQueryError";
|
|
2694
|
+
}
|
|
2695
|
+
const me = { group: (e3) => ({ type: "Group", base: e3.process(me) }), everything: () => ({ type: "Everything" }), this: () => ({ type: "This" }), parent: () => ({ type: "Parent", n: 1 }), dblparent: (e3) => ({ type: "Parent", n: e3.process(me).n + 1 }), traverse(e3) {
|
|
2696
|
+
const t2 = e3.process(me), r2 = [];
|
|
2697
|
+
for (; e3.getMark().name !== "traversal_end"; ) r2.push(e3.process(ge));
|
|
2698
|
+
e3.shift();
|
|
2699
|
+
let n2 = null;
|
|
2700
|
+
for (let e4 = r2.length - 1; e4 >= 0; e4--) n2 = r2[e4](n2);
|
|
2701
|
+
if ((t2.type === "Everything" || t2.type === "Array" || t2.type === "PipeFuncCall") && (n2 = le((e4) => e4, n2)), n2 === null) throw new Error("BUG: unexpected empty traversal");
|
|
2702
|
+
return n2.build(t2);
|
|
2703
|
+
}, this_attr(e3) {
|
|
2704
|
+
const t2 = e3.processString();
|
|
2705
|
+
return t2 === "null" ? { type: "Value", value: null } : t2 === "true" ? { type: "Value", value: !0 } : t2 === "false" ? { type: "Value", value: !1 } : { type: "AccessAttribute", name: t2 };
|
|
2706
|
+
}, neg: (e3) => ({ type: "Neg", base: e3.process(me) }), pos: (e3) => ({ type: "Pos", base: e3.process(me) }), add: (e3) => ({ type: "OpCall", op: "+", left: e3.process(me), right: e3.process(me) }), sub: (e3) => ({ type: "OpCall", op: "-", left: e3.process(me), right: e3.process(me) }), mul: (e3) => ({ type: "OpCall", op: "*", left: e3.process(me), right: e3.process(me) }), div: (e3) => ({ type: "OpCall", op: "/", left: e3.process(me), right: e3.process(me) }), mod: (e3) => ({ type: "OpCall", op: "%", left: e3.process(me), right: e3.process(me) }), pow: (e3) => ({ type: "OpCall", op: "**", left: e3.process(me), right: e3.process(me) }), comp(e3) {
|
|
2707
|
+
const t2 = e3.process(me);
|
|
2708
|
+
return { type: "OpCall", op: e3.processString(), left: t2, right: e3.process(me) };
|
|
2709
|
+
}, in_range(e3) {
|
|
2710
|
+
const t2 = e3.process(me), r2 = e3.getMark().name === "inc_range";
|
|
2711
|
+
return e3.shift(), { type: "InRange", base: t2, left: e3.process(me), right: e3.process(me), isInclusive: r2 };
|
|
2712
|
+
}, str(e3) {
|
|
2713
|
+
let t2 = "";
|
|
2714
|
+
e: for (; e3.hasMark(); ) {
|
|
2715
|
+
const r2 = e3.getMark();
|
|
2716
|
+
switch (r2.name) {
|
|
2717
|
+
case "str_end":
|
|
2718
|
+
t2 += e3.processStringEnd();
|
|
2719
|
+
break e;
|
|
2720
|
+
case "str_pause":
|
|
2721
|
+
t2 += e3.processStringEnd();
|
|
2722
|
+
break;
|
|
2723
|
+
case "str_start":
|
|
2724
|
+
e3.shift();
|
|
2725
|
+
break;
|
|
2726
|
+
case "single_escape": {
|
|
2727
|
+
const r3 = e3.slice(1);
|
|
2728
|
+
e3.shift(), t2 += ye[r3];
|
|
2729
|
+
break;
|
|
2730
|
+
}
|
|
2731
|
+
case "unicode_hex":
|
|
2732
|
+
e3.shift(), t2 += de(e3.processStringEnd());
|
|
2733
|
+
break;
|
|
2734
|
+
default:
|
|
2735
|
+
throw new Error(`unexpected mark: ${r2.name}`);
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
return { type: "Value", value: t2 };
|
|
2739
|
+
}, integer(e3) {
|
|
2740
|
+
const t2 = e3.processStringEnd();
|
|
2741
|
+
return { type: "Value", value: Number(t2) };
|
|
2742
|
+
}, float(e3) {
|
|
2743
|
+
const t2 = e3.processStringEnd();
|
|
2744
|
+
return { type: "Value", value: Number(t2) };
|
|
2745
|
+
}, sci(e3) {
|
|
2746
|
+
const t2 = e3.processStringEnd();
|
|
2747
|
+
return { type: "Value", value: Number(t2) };
|
|
2748
|
+
}, object(e3) {
|
|
2749
|
+
const t2 = [];
|
|
2750
|
+
for (; e3.getMark().name !== "object_end"; ) t2.push(e3.process(be));
|
|
2751
|
+
return e3.shift(), { type: "Object", attributes: t2 };
|
|
2752
|
+
}, array(e3) {
|
|
2753
|
+
const t2 = [];
|
|
2754
|
+
for (; e3.getMark().name !== "array_end"; ) {
|
|
2755
|
+
let r2 = !1;
|
|
2756
|
+
e3.getMark().name === "array_splat" && (r2 = !0, e3.shift());
|
|
2757
|
+
const n2 = e3.process(me);
|
|
2758
|
+
t2.push({ type: "ArrayElement", value: n2, isSplat: r2 });
|
|
2759
|
+
}
|
|
2760
|
+
return e3.shift(), { type: "Array", elements: t2 };
|
|
2761
|
+
}, tuple(e3) {
|
|
2762
|
+
const t2 = [];
|
|
2763
|
+
for (; e3.getMark().name !== "tuple_end"; ) t2.push(e3.process(me));
|
|
2764
|
+
return e3.shift(), { type: "Tuple", members: t2 };
|
|
2765
|
+
}, func_call(e3) {
|
|
2766
|
+
let t2 = "global";
|
|
2767
|
+
e3.getMark().name === "namespace" && (e3.shift(), t2 = e3.processString());
|
|
2768
|
+
const r2 = e3.processString();
|
|
2769
|
+
if (t2 === "global" && r2 === "select") {
|
|
2770
|
+
const t3 = { type: "Select", alternatives: [] };
|
|
2771
|
+
for (; e3.getMark().name !== "func_args_end"; ) if (e3.getMark().name === "pair") {
|
|
2772
|
+
if (t3.fallback) throw new he("unexpected argument to select()");
|
|
2773
|
+
e3.shift();
|
|
2774
|
+
const r3 = e3.process(me), n3 = e3.process(me);
|
|
2775
|
+
t3.alternatives.push({ type: "SelectAlternative", condition: r3, value: n3 });
|
|
2776
|
+
} else {
|
|
2777
|
+
if (t3.fallback) throw new he("unexpected argument to select()");
|
|
2778
|
+
const r3 = e3.process(me);
|
|
2779
|
+
t3.fallback = r3;
|
|
2780
|
+
}
|
|
2781
|
+
return e3.shift(), t3;
|
|
2782
|
+
}
|
|
2783
|
+
const n2 = [];
|
|
2784
|
+
for (; e3.getMark().name !== "func_args_end"; ) xe(t2, r2, n2.length) ? (e3.process(we), n2.push({ type: "Selector" })) : n2.push(e3.process(me));
|
|
2785
|
+
if (e3.shift(), t2 === "global" && (r2 === "before" || r2 === "after") && e3.parseOptions.mode === "delta") return { type: "Context", key: r2 };
|
|
2786
|
+
if (t2 === "global" && r2 === "boost" && !e3.allowBoost) throw new he("unexpected boost");
|
|
2787
|
+
const o2 = Y[t2];
|
|
2788
|
+
if (!o2) throw new he(`Undefined namespace: ${t2}`);
|
|
2789
|
+
const i2 = o2[r2];
|
|
2790
|
+
if (!i2) throw new he(`Undefined function: ${r2}`);
|
|
2791
|
+
if (i2.arity !== void 0 && ve(r2, i2.arity, n2.length), i2.mode !== void 0 && i2.mode !== e3.parseOptions.mode) throw new he(`Undefined function: ${r2}`);
|
|
2792
|
+
return { type: "FuncCall", func: i2, namespace: t2, name: r2, args: n2 };
|
|
2793
|
+
}, pipecall(e3) {
|
|
2794
|
+
const t2 = e3.process(me);
|
|
2795
|
+
e3.shift();
|
|
2796
|
+
let r2 = "global";
|
|
2797
|
+
if (e3.getMark().name === "namespace" && (e3.shift(), r2 = e3.processString()), r2 !== "global") throw new he(`Undefined namespace: ${r2}`);
|
|
2798
|
+
const n2 = e3.processString(), o2 = [], i2 = e3.allowBoost;
|
|
2799
|
+
for (n2 === "score" && (e3.allowBoost = !0); ; ) {
|
|
2800
|
+
const t3 = e3.getMark().name;
|
|
2801
|
+
if (t3 === "func_args_end") break;
|
|
2802
|
+
if (n2 === "order") {
|
|
2803
|
+
if (t3 === "asc") {
|
|
2804
|
+
e3.shift(), o2.push({ type: "Asc", base: e3.process(me) });
|
|
2805
|
+
continue;
|
|
2806
|
+
}
|
|
2807
|
+
if (t3 === "desc") {
|
|
2808
|
+
e3.shift(), o2.push({ type: "Desc", base: e3.process(me) });
|
|
2809
|
+
continue;
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
o2.push(e3.process(me));
|
|
2813
|
+
}
|
|
2814
|
+
e3.shift(), e3.allowBoost = i2;
|
|
2815
|
+
const s2 = Z[n2];
|
|
2816
|
+
if (!s2) throw new he(`Undefined pipe function: ${n2}`);
|
|
2817
|
+
return s2.arity && ve(n2, s2.arity, o2.length), { type: "PipeFuncCall", func: s2, base: t2, name: n2, args: o2 };
|
|
2818
|
+
}, pair() {
|
|
2819
|
+
throw new he("unexpected =>");
|
|
2820
|
+
}, and: (e3) => ({ type: "And", left: e3.process(me), right: e3.process(me) }), or: (e3) => ({ type: "Or", left: e3.process(me), right: e3.process(me) }), not: (e3) => ({ type: "Not", base: e3.process(me) }), asc() {
|
|
2821
|
+
throw new he("unexpected asc");
|
|
2822
|
+
}, desc() {
|
|
2823
|
+
throw new he("unexpected desc");
|
|
2824
|
+
}, param(e3) {
|
|
2825
|
+
const t2 = e3.processString();
|
|
2826
|
+
return e3.parseOptions.params && e3.parseOptions.params.hasOwnProperty(t2) ? { type: "Value", value: e3.parseOptions.params[t2] } : { type: "Parameter", name: t2 };
|
|
2827
|
+
} }, be = { object_expr(e3) {
|
|
2828
|
+
if (e3.getMark().name === "pair")
|
|
2829
|
+
return e3.shift(), { type: "ObjectConditionalSplat", condition: e3.process(me), value: e3.process(me) };
|
|
2830
|
+
const t2 = e3.process(me);
|
|
2831
|
+
return { type: "ObjectAttributeValue", name: ke(t2), value: t2 };
|
|
2832
|
+
}, object_pair(e3) {
|
|
2833
|
+
const t2 = e3.process(me);
|
|
2834
|
+
if (t2.type !== "Value") throw new Error("name must be string");
|
|
2835
|
+
const r2 = e3.process(me);
|
|
2836
|
+
return { type: "ObjectAttributeValue", name: t2.value, value: r2 };
|
|
2837
|
+
}, object_splat: (e3) => ({ type: "ObjectSplat", value: e3.process(me) }), object_splat_this: () => ({ type: "ObjectSplat", value: { type: "This" } }) }, ge = { square_bracket(e3) {
|
|
2838
|
+
const t2 = e3.process(me), r2 = P(t2);
|
|
2839
|
+
return r2 && r2.type === "number" ? (e4) => function(e5, t3) {
|
|
2840
|
+
if (!t3) return { type: "a-b", build: e5 };
|
|
2841
|
+
switch (t3.type) {
|
|
2842
|
+
case "a-a":
|
|
2843
|
+
case "b-a":
|
|
2844
|
+
return { type: "a-a", build: ue(e5, t3.build) };
|
|
2845
|
+
case "a-b":
|
|
2846
|
+
case "b-b":
|
|
2847
|
+
return { type: "a-b", build: ue(e5, t3.build) };
|
|
2848
|
+
default:
|
|
2849
|
+
throw new Error(`unknown type: ${t3.type}`);
|
|
2850
|
+
}
|
|
2851
|
+
}((e5) => ({ type: "AccessElement", base: e5, index: r2.data }), e4) : r2 && r2.type === "string" ? (e4) => fe((e5) => ({ type: "AccessAttribute", base: e5, name: r2.data }), e4) : (e4) => le((e5) => ({ type: "Filter", base: e5, expr: t2 }), e4);
|
|
2852
|
+
}, slice(e3) {
|
|
2853
|
+
const t2 = e3.getMark().name === "inc_range";
|
|
2854
|
+
e3.shift();
|
|
2855
|
+
const r2 = e3.process(me), n2 = e3.process(me), o2 = P(r2), i2 = P(n2);
|
|
2856
|
+
if (!o2 || !i2 || o2.type !== "number" || i2.type !== "number") throw new he("slicing must use constant numbers");
|
|
2857
|
+
return (e4) => le((e5) => ({ type: "Slice", base: e5, left: o2.data, right: i2.data, isInclusive: t2 }), e4);
|
|
2858
|
+
}, projection(e3) {
|
|
2859
|
+
const t2 = e3.process(me);
|
|
2860
|
+
return (e4) => function(e5, t3) {
|
|
2861
|
+
if (!t3) return { type: "b-b", build: e5 };
|
|
2862
|
+
switch (t3.type) {
|
|
2863
|
+
case "a-a":
|
|
2864
|
+
return { type: "a-a", build: ue(pe(e5), t3.build) };
|
|
2865
|
+
case "a-b":
|
|
2866
|
+
return { type: "a-b", build: ue(pe(e5), t3.build) };
|
|
2867
|
+
case "b-a":
|
|
2868
|
+
return { type: "b-a", build: ue(e5, t3.build) };
|
|
2869
|
+
case "b-b":
|
|
2870
|
+
return { type: "b-b", build: ue(e5, t3.build) };
|
|
2871
|
+
default:
|
|
2872
|
+
throw new Error(`unknown type: ${t3.type}`);
|
|
2873
|
+
}
|
|
2874
|
+
}((e5) => ({ type: "Projection", base: e5, expr: t2 }), e4);
|
|
2875
|
+
}, attr_access(e3) {
|
|
2876
|
+
const t2 = e3.processString();
|
|
2877
|
+
return (e4) => fe((e5) => ({ type: "AccessAttribute", base: e5, name: t2 }), e4);
|
|
2878
|
+
}, deref(e3) {
|
|
2879
|
+
let t2 = null;
|
|
2880
|
+
return e3.getMark().name === "deref_attr" && (e3.shift(), t2 = e3.processString()), (e4) => fe((e5) => /* @__PURE__ */ ((e6) => t2 ? { type: "AccessAttribute", base: e6, name: t2 } : e6)({ type: "Deref", base: e5 }), e4);
|
|
2881
|
+
}, array_postfix: () => (e3) => le((e4) => ({ type: "ArrayCoerce", base: e4 }), e3) }, we = { group: (e3) => (e3.process(we), null), everything() {
|
|
2882
|
+
throw new Error("Invalid selector syntax");
|
|
2883
|
+
}, this() {
|
|
2884
|
+
throw new Error("Invalid selector syntax");
|
|
2885
|
+
}, parent() {
|
|
2886
|
+
throw new Error("Invalid selector syntax");
|
|
2887
|
+
}, dblparent() {
|
|
2888
|
+
throw new Error("Invalid selector syntax");
|
|
2889
|
+
}, traverse(e3) {
|
|
2890
|
+
for (e3.process(we); e3.getMark().name !== "traversal_end"; ) e3.process(ge);
|
|
2891
|
+
return e3.shift(), null;
|
|
2892
|
+
}, this_attr: (e3) => (e3.processString(), null), neg() {
|
|
2893
|
+
throw new Error("Invalid selector syntax");
|
|
2894
|
+
}, pos() {
|
|
2895
|
+
throw new Error("Invalid selector syntax");
|
|
2896
|
+
}, add() {
|
|
2897
|
+
throw new Error("Invalid selector syntax");
|
|
2898
|
+
}, sub() {
|
|
2899
|
+
throw new Error("Invalid selector syntax");
|
|
2900
|
+
}, mul() {
|
|
2901
|
+
throw new Error("Invalid selector syntax");
|
|
2902
|
+
}, div() {
|
|
2903
|
+
throw new Error("Invalid selector syntax");
|
|
2904
|
+
}, mod() {
|
|
2905
|
+
throw new Error("Invalid selector syntax");
|
|
2906
|
+
}, pow() {
|
|
2907
|
+
throw new Error("Invalid selector syntax");
|
|
2908
|
+
}, comp() {
|
|
2909
|
+
throw new Error("Invalid selector syntax");
|
|
2910
|
+
}, in_range() {
|
|
2911
|
+
throw new Error("Invalid selector syntax");
|
|
2912
|
+
}, str() {
|
|
2913
|
+
throw new Error("Invalid selector syntax");
|
|
2914
|
+
}, integer() {
|
|
2915
|
+
throw new Error("Invalid selector syntax");
|
|
2916
|
+
}, float() {
|
|
2917
|
+
throw new Error("Invalid selector syntax");
|
|
2918
|
+
}, sci() {
|
|
2919
|
+
throw new Error("Invalid selector syntax");
|
|
2920
|
+
}, object() {
|
|
2921
|
+
throw new Error("Invalid selector syntax");
|
|
2922
|
+
}, array() {
|
|
2923
|
+
throw new Error("Invalid selector syntax");
|
|
2924
|
+
}, tuple() {
|
|
2925
|
+
throw new Error("Invalid selector syntax");
|
|
2926
|
+
}, func_call(e3, t2) {
|
|
2927
|
+
const r2 = me.func_call(e3, t2);
|
|
2928
|
+
if (r2.name === "anywhere" && r2.args.length === 1) return null;
|
|
2929
|
+
throw new Error("Invalid selector syntax");
|
|
2930
|
+
}, pipecall() {
|
|
2931
|
+
throw new Error("Invalid selector syntax");
|
|
2932
|
+
}, pair() {
|
|
2933
|
+
throw new Error("Invalid selector syntax");
|
|
2934
|
+
}, and() {
|
|
2935
|
+
throw new Error("Invalid selector syntax");
|
|
2936
|
+
}, or() {
|
|
2937
|
+
throw new Error("Invalid selector syntax");
|
|
2938
|
+
}, not() {
|
|
2939
|
+
throw new Error("Invalid selector syntax");
|
|
2940
|
+
}, asc() {
|
|
2941
|
+
throw new Error("Invalid selector syntax");
|
|
2942
|
+
}, desc() {
|
|
2943
|
+
throw new Error("Invalid selector syntax");
|
|
2944
|
+
}, param() {
|
|
2945
|
+
throw new Error("Invalid selector syntax");
|
|
2946
|
+
} };
|
|
2947
|
+
function ke(e3) {
|
|
2948
|
+
if (e3.type === "AccessAttribute" && !e3.base) return e3.name;
|
|
2949
|
+
if (e3.type === "PipeFuncCall" || e3.type === "Deref" || e3.type === "Map" || e3.type === "Projection" || e3.type === "Slice" || e3.type === "Filter" || e3.type === "AccessElement" || e3.type === "ArrayCoerce" || e3.type === "Group") return ke(e3.base);
|
|
2950
|
+
throw new he(`Cannot determine property key for type: ${e3.type}`);
|
|
2951
|
+
}
|
|
2952
|
+
function ve(e3, t2, r2) {
|
|
2953
|
+
if (typeof t2 == "number") {
|
|
2954
|
+
if (r2 !== t2) throw new he(`Incorrect number of arguments to function ${e3}(). Expected ${t2}, got ${r2}.`);
|
|
2955
|
+
} else if (t2 && !t2(r2)) throw new he(`Incorrect number of arguments to function ${e3}().`);
|
|
2956
|
+
}
|
|
2957
|
+
function xe(e3, t2, r2) {
|
|
2958
|
+
return e3 == "diff" && r2 == 2 && ["changedAny", "changedOnly"].includes(t2);
|
|
2959
|
+
}
|
|
2960
|
+
class _e extends Error {
|
|
2961
|
+
position;
|
|
2962
|
+
name = "GroqSyntaxError";
|
|
2963
|
+
constructor(e3) {
|
|
2964
|
+
super(`Syntax error in GROQ query at position ${e3}`), this.position = e3;
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
function Ae(e3, t2 = {}) {
|
|
2968
|
+
const r2 = function(e4) {
|
|
2969
|
+
let t3 = 0;
|
|
2970
|
+
t3 = se(e4, t3);
|
|
2971
|
+
let r3 = re(e4, t3, 0);
|
|
2972
|
+
return r3.type === "error" ? r3 : (t3 = se(e4, r3.position), t3 !== e4.length ? (r3.failPosition && (t3 = r3.failPosition - 1), { type: "error", position: t3 }) : (delete r3.position, delete r3.failPosition, r3));
|
|
2973
|
+
}(e3);
|
|
2974
|
+
if (r2.type === "error") throw new _e(r2.position);
|
|
2975
|
+
return new K(e3, r2.marks, t2).process(me);
|
|
2976
|
+
}
|
|
2977
|
+
const isRecord = (value) => typeof value == "object" && !!value && !Array.isArray(value), ignoredKeys = ["_id", "_type", "_createdAt", "_updatedAt", "_rev"];
|
|
2978
|
+
function diffPatch(before, after) {
|
|
2979
|
+
return diffRecursive(before, after, []);
|
|
2980
|
+
}
|
|
2981
|
+
function diffRecursive(before, after, path) {
|
|
2982
|
+
if (before === after) return [];
|
|
2983
|
+
const patches = [], pathStr = stringifyPath(path);
|
|
2984
|
+
if (before === null || after === null)
|
|
2985
|
+
return before !== after && patches.push({ set: { [pathStr]: after } }), patches;
|
|
2986
|
+
if (typeof before != typeof after || Array.isArray(before) !== Array.isArray(after))
|
|
2987
|
+
return patches.push({ set: { [pathStr]: after } }), patches;
|
|
2988
|
+
if (typeof before == "string" && typeof after == "string") {
|
|
2989
|
+
const dmpPatches = diffMatchPatch$1.makePatches(before, after), patchStr = diffMatchPatch$1.stringifyPatches(dmpPatches);
|
|
2990
|
+
return patches.push({ diffMatchPatch: { [pathStr]: patchStr } }), patches;
|
|
2991
|
+
}
|
|
2992
|
+
if (typeof before == "number" && typeof after == "number")
|
|
2993
|
+
return patches.push({ set: { [pathStr]: after } }), patches;
|
|
2994
|
+
if (typeof before != "object")
|
|
2995
|
+
return before !== after && patches.push({ set: { [pathStr]: after } }), patches;
|
|
2996
|
+
if (Array.isArray(before) && Array.isArray(after))
|
|
2997
|
+
return patches.push(...diffArray(before, after, path)), patches;
|
|
2998
|
+
if (!isRecord(after) || !isRecord(before)) return patches;
|
|
2999
|
+
const beforeKeys = Object.keys(before).filter((k2) => !ignoredKeys.includes(k2)), afterKeys = Object.keys(after).filter((k2) => !ignoredKeys.includes(k2)), allKeys = /* @__PURE__ */ new Set([...beforeKeys, ...afterKeys]);
|
|
3000
|
+
for (const key of allKeys) {
|
|
3001
|
+
const subPath = [...path, key];
|
|
3002
|
+
key in after ? key in before ? patches.push(...diffRecursive(before[key], after[key], subPath)) : patches.push({ set: { [stringifyPath(subPath)]: after[key] } }) : patches.push({ unset: [stringifyPath(subPath)] });
|
|
3003
|
+
}
|
|
3004
|
+
return patches;
|
|
3005
|
+
}
|
|
3006
|
+
function diffArray(beforeArr, afterArr, path) {
|
|
3007
|
+
const pathStr = stringifyPath(path), isKeyedArray = (arr) => arr.every((item) => types.isKeyedObject(item));
|
|
3008
|
+
if (isKeyedArray(beforeArr) && isKeyedArray(afterArr)) {
|
|
3009
|
+
if (beforeArr.length === 0 && afterArr.length > 0)
|
|
3010
|
+
return [
|
|
3011
|
+
{
|
|
3012
|
+
insert: {
|
|
3013
|
+
before: stringifyPath([...path, 0]),
|
|
3014
|
+
items: afterArr
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
];
|
|
3018
|
+
const unsetPatches = [], diffPatches = [], insertPatches = [], beforeMap = /* @__PURE__ */ new Map();
|
|
3019
|
+
beforeArr.forEach((item, index) => {
|
|
3020
|
+
beforeMap.set(item._key, { item, index });
|
|
3021
|
+
});
|
|
3022
|
+
const afterMap = /* @__PURE__ */ new Map();
|
|
3023
|
+
afterArr.forEach((item, index) => {
|
|
3024
|
+
afterMap.set(item._key, { item, index });
|
|
3025
|
+
});
|
|
3026
|
+
for (const [key] of beforeMap.entries())
|
|
3027
|
+
afterMap.has(key) || unsetPatches.push({ unset: [stringifyPath([...path, { _key: key }])] });
|
|
3028
|
+
for (const [key, { item: afterItem }] of afterMap.entries())
|
|
3029
|
+
beforeMap.has(key) && diffPatches.push(
|
|
3030
|
+
...diffRecursive(beforeMap.get(key).item, afterItem, [...path, { _key: key }])
|
|
3031
|
+
);
|
|
3032
|
+
let newItemsGroup = [], insertPosition = null;
|
|
3033
|
+
for (let i2 = 0; i2 < afterArr.length; i2++) {
|
|
3034
|
+
const item = afterArr[i2];
|
|
3035
|
+
if (beforeMap.has(item._key))
|
|
3036
|
+
newItemsGroup.length > 0 && insertPosition && (insertPosition.op === "before" ? insertPatches.push({
|
|
3037
|
+
insert: {
|
|
3038
|
+
before: stringifyPath([...path, { _key: insertPosition.refKey }]),
|
|
3039
|
+
items: newItemsGroup
|
|
3040
|
+
}
|
|
3041
|
+
}) : insertPatches.push({
|
|
3042
|
+
insert: {
|
|
3043
|
+
after: stringifyPath([...path, { _key: insertPosition.refKey }]),
|
|
3044
|
+
items: newItemsGroup
|
|
3045
|
+
}
|
|
3046
|
+
}), newItemsGroup = [], insertPosition = null);
|
|
3047
|
+
else {
|
|
3048
|
+
if (newItemsGroup.length === 0)
|
|
3049
|
+
if (i2 === 0) {
|
|
3050
|
+
let j2 = i2;
|
|
3051
|
+
for (; j2 < afterArr.length && !beforeMap.has(afterArr[j2]._key); )
|
|
3052
|
+
j2++;
|
|
3053
|
+
j2 < afterArr.length ? insertPosition = { op: "before", refKey: afterArr[j2]._key } : beforeArr.length > 0 && (insertPosition = { op: "after", refKey: beforeArr[beforeArr.length - 1]._key });
|
|
3054
|
+
} else {
|
|
3055
|
+
let j2 = i2 - 1;
|
|
3056
|
+
for (; j2 >= 0 && !beforeMap.has(afterArr[j2]._key); )
|
|
3057
|
+
j2--;
|
|
3058
|
+
if (j2 >= 0)
|
|
3059
|
+
insertPosition = { op: "after", refKey: afterArr[j2]._key };
|
|
3060
|
+
else {
|
|
3061
|
+
let k2 = i2;
|
|
3062
|
+
for (; k2 < afterArr.length && !beforeMap.has(afterArr[k2]._key); )
|
|
3063
|
+
k2++;
|
|
3064
|
+
k2 < afterArr.length && (insertPosition = { op: "before", refKey: afterArr[k2]._key });
|
|
3065
|
+
}
|
|
3066
|
+
}
|
|
3067
|
+
newItemsGroup.push(item);
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
return newItemsGroup.length > 0 && insertPosition && (insertPosition.op === "after" ? insertPatches.push({
|
|
3071
|
+
insert: {
|
|
3072
|
+
after: stringifyPath([...path, { _key: insertPosition.refKey }]),
|
|
3073
|
+
items: newItemsGroup
|
|
3074
|
+
}
|
|
3075
|
+
}) : insertPatches.push({
|
|
3076
|
+
insert: {
|
|
3077
|
+
before: stringifyPath([...path, { _key: insertPosition.refKey }]),
|
|
3078
|
+
items: newItemsGroup
|
|
3079
|
+
}
|
|
3080
|
+
})), afterArr.every((item) => !beforeMap.has(item._key)) ? [...insertPatches, ...unsetPatches, ...diffPatches] : [...unsetPatches, ...diffPatches, ...insertPatches];
|
|
3081
|
+
} else {
|
|
3082
|
+
const patches = [], minLength = Math.min(beforeArr.length, afterArr.length);
|
|
3083
|
+
for (let i2 = 0; i2 < minLength; i2++)
|
|
3084
|
+
patches.push(...diffRecursive(beforeArr[i2], afterArr[i2], [...path, i2]));
|
|
3085
|
+
for (let i2 = afterArr.length; i2 < beforeArr.length; i2++)
|
|
3086
|
+
patches.push({ unset: [stringifyPath([...path, i2])] });
|
|
3087
|
+
if (afterArr.length > beforeArr.length) {
|
|
3088
|
+
const newItems = afterArr.slice(beforeArr.length);
|
|
3089
|
+
beforeArr.length > 0 ? patches.push({
|
|
3090
|
+
insert: { after: stringifyPath([...path, beforeArr.length - 1]), items: newItems }
|
|
3091
|
+
}) : patches.push({ set: { [pathStr]: afterArr } });
|
|
3092
|
+
}
|
|
3093
|
+
return patches;
|
|
3094
|
+
}
|
|
3095
|
+
}
|
|
3096
|
+
class MultiKeyWeakMap {
|
|
3097
|
+
// The root of our nested WeakMap structure.
|
|
3098
|
+
#rootMap = /* @__PURE__ */ new WeakMap();
|
|
3099
|
+
// Instead of random IDs, we use a counter for deterministic IDs.
|
|
3100
|
+
static #globalIdCounter = 0;
|
|
3101
|
+
// Each instance keeps a cache mapping a key to its assigned ID.
|
|
3102
|
+
#idCache = /* @__PURE__ */ new WeakMap();
|
|
3103
|
+
/**
|
|
3104
|
+
* Assigns a numeric ID to the key.
|
|
3105
|
+
*/
|
|
3106
|
+
#assignId(key) {
|
|
3107
|
+
const cachedId = this.#idCache.get(key);
|
|
3108
|
+
if (cachedId !== void 0) return cachedId;
|
|
3109
|
+
const id = MultiKeyWeakMap.#globalIdCounter;
|
|
3110
|
+
return this.#idCache.set(key, id), MultiKeyWeakMap.#globalIdCounter++, id;
|
|
3111
|
+
}
|
|
3112
|
+
/**
|
|
3113
|
+
* Remove duplicate keys and arrange them in a consistent order
|
|
3114
|
+
* by sorting according to their assigned IDs.
|
|
3115
|
+
*/
|
|
3116
|
+
#arrangeKeys(keys) {
|
|
3117
|
+
const keyed = Array.from(new Set(keys)).map((key) => [this.#assignId(key), key]);
|
|
3118
|
+
return keyed.sort((a2, b2) => a2[0] - b2[0]), keyed.map(([, key]) => key);
|
|
3119
|
+
}
|
|
3120
|
+
/**
|
|
3121
|
+
* Recursively search the nested WeakMap structure for the value.
|
|
3122
|
+
*/
|
|
3123
|
+
#getDeep(keys, map) {
|
|
3124
|
+
if (keys.length === 0) return;
|
|
3125
|
+
const [firstKey, ...restKeys] = keys, node = map.get(firstKey);
|
|
3126
|
+
if (node)
|
|
3127
|
+
return restKeys.length === 0 ? node.value : this.#getDeep(restKeys, node.next);
|
|
3128
|
+
}
|
|
3129
|
+
/**
|
|
3130
|
+
* Recursively create nodes along the key chain until the final key
|
|
3131
|
+
* is reached, then assign the value.
|
|
3132
|
+
*/
|
|
3133
|
+
#setDeep(keys, map, value) {
|
|
3134
|
+
if (keys.length === 0) return;
|
|
3135
|
+
const [firstKey, ...restKeys] = keys;
|
|
3136
|
+
let node = map.get(firstKey);
|
|
3137
|
+
node || (node = {
|
|
3138
|
+
value: void 0,
|
|
3139
|
+
next: /* @__PURE__ */ new WeakMap()
|
|
3140
|
+
}, map.set(firstKey, node)), restKeys.length === 0 ? node.value = value : this.#setDeep(restKeys, node.next, value);
|
|
3141
|
+
}
|
|
3142
|
+
/**
|
|
3143
|
+
* Retrieves the value associated with the array of keys.
|
|
3144
|
+
* The keys are de-duplicated and sorted so that the order does not matter.
|
|
3145
|
+
*/
|
|
3146
|
+
get(keys) {
|
|
3147
|
+
const arrangedKeys = this.#arrangeKeys(keys);
|
|
3148
|
+
return this.#getDeep(arrangedKeys, this.#rootMap);
|
|
3149
|
+
}
|
|
3150
|
+
/**
|
|
3151
|
+
* Associates the value with the given array of keys.
|
|
3152
|
+
*/
|
|
3153
|
+
set(keys, value) {
|
|
3154
|
+
const arrangedKeys = this.#arrangeKeys(keys);
|
|
3155
|
+
this.#setDeep(arrangedKeys, this.#rootMap, value);
|
|
3156
|
+
}
|
|
3157
|
+
}
|
|
3158
|
+
function createGrantsLookup(datasetAcl) {
|
|
3159
|
+
const filtersByGrant = {
|
|
3160
|
+
create: /* @__PURE__ */ new Set(),
|
|
3161
|
+
history: /* @__PURE__ */ new Set(),
|
|
3162
|
+
read: /* @__PURE__ */ new Set(),
|
|
3163
|
+
update: /* @__PURE__ */ new Set()
|
|
3164
|
+
};
|
|
3165
|
+
for (const entry of datasetAcl)
|
|
3166
|
+
for (const grant of entry.permissions) {
|
|
3167
|
+
const set2 = filtersByGrant[grant];
|
|
3168
|
+
set2.add(entry.filter), filtersByGrant[grant] = set2;
|
|
3169
|
+
}
|
|
3170
|
+
return Object.fromEntries(
|
|
3171
|
+
Object.entries(filtersByGrant).map(([grant, filters]) => {
|
|
3172
|
+
const combinedFilter = Array.from(filters).map((i2) => `(${i2})`).join("||");
|
|
3173
|
+
return combinedFilter ? [grant, Ae(`$document {"_": ${combinedFilter}}._`)] : [grant, Ae("false")];
|
|
3174
|
+
})
|
|
3175
|
+
);
|
|
3176
|
+
}
|
|
3177
|
+
const documentsCache = new MultiKeyWeakMap(), actionsCache = /* @__PURE__ */ new WeakMap(), nullReplacer = {}, documentsSelector = reselect.createSelector(
|
|
3178
|
+
[
|
|
3179
|
+
({ documentStates }) => documentStates,
|
|
3180
|
+
(_state, actions) => actions
|
|
3181
|
+
],
|
|
3182
|
+
(documentStates, actions) => {
|
|
3183
|
+
const documentIds = new Set(
|
|
3184
|
+
(Array.isArray(actions) ? actions : [actions]).map((i2) => i2.documentId).filter((i2) => typeof i2 == "string").flatMap((documentId) => [getPublishedId(documentId), getDraftId(documentId)])
|
|
3185
|
+
), documents = {};
|
|
3186
|
+
for (const documentId of documentIds) {
|
|
3187
|
+
const local = documentStates[documentId]?.local;
|
|
3188
|
+
if (local === void 0) return;
|
|
3189
|
+
documents[documentId] = local;
|
|
3190
|
+
}
|
|
3191
|
+
const keys = Object.values(
|
|
3192
|
+
// value in this record will be `undefined` because
|
|
3193
|
+
// of the early return if undefined is found above
|
|
3194
|
+
documents
|
|
3195
|
+
).map((doc) => doc === null ? nullReplacer : doc);
|
|
3196
|
+
return documentsCache.get(keys) || (documentsCache.set(keys, documents), documents);
|
|
3197
|
+
}
|
|
3198
|
+
), memoizedActionsSelector = reselect.createSelector(
|
|
3199
|
+
[
|
|
3200
|
+
documentsSelector,
|
|
3201
|
+
(_state, actions) => actions
|
|
3202
|
+
],
|
|
3203
|
+
(documents, actions) => {
|
|
3204
|
+
if (!documents) return;
|
|
3205
|
+
let nestedCache = actionsCache.get(documents);
|
|
3206
|
+
nestedCache || (nestedCache = /* @__PURE__ */ new Map(), actionsCache.set(documents, nestedCache));
|
|
3207
|
+
const normalizedActions = Array.isArray(actions) ? actions : [actions], actionsKey = JSON.stringify(normalizedActions);
|
|
3208
|
+
return nestedCache.get(actionsKey) || (nestedCache.set(actionsKey, normalizedActions), normalizedActions);
|
|
3209
|
+
}
|
|
3210
|
+
);
|
|
3211
|
+
function checkGrant$1(grantExpr, document2) {
|
|
3212
|
+
return C(grantExpr, { params: { document: document2 } }).get();
|
|
3213
|
+
}
|
|
3214
|
+
const enNarrowConjunction = new Intl.ListFormat("en", { style: "narrow", type: "conjunction" }), calculatePermissions = reselect.createSelector(
|
|
3215
|
+
[({ grants }) => grants, documentsSelector, memoizedActionsSelector],
|
|
3216
|
+
(grants, documents, actions) => {
|
|
3217
|
+
if (!documents || !grants || !actions) return;
|
|
3218
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString(), reasons = [];
|
|
3219
|
+
try {
|
|
3220
|
+
processActions({
|
|
3221
|
+
actions,
|
|
3222
|
+
transactionId: crypto.randomUUID(),
|
|
3223
|
+
working: documents,
|
|
3224
|
+
base: documents,
|
|
3225
|
+
timestamp,
|
|
3226
|
+
grants
|
|
3227
|
+
});
|
|
3228
|
+
} catch (error) {
|
|
3229
|
+
if (error instanceof PermissionActionError)
|
|
3230
|
+
reasons.push({
|
|
3231
|
+
message: error.message,
|
|
3232
|
+
documentId: error.documentId,
|
|
3233
|
+
type: "access"
|
|
3234
|
+
});
|
|
3235
|
+
else if (error instanceof ActionError)
|
|
3236
|
+
reasons.push({
|
|
3237
|
+
message: error.message,
|
|
3238
|
+
documentId: error.documentId,
|
|
3239
|
+
type: "precondition"
|
|
3240
|
+
});
|
|
3241
|
+
else
|
|
3242
|
+
throw error;
|
|
3243
|
+
}
|
|
3244
|
+
for (const action of actions)
|
|
3245
|
+
if (action.type === "document.edit" && !action.patches?.length) {
|
|
3246
|
+
const docId = action.documentId, doc = documents[getDraftId(docId)] ?? documents[getPublishedId(docId)];
|
|
3247
|
+
doc ? checkGrant$1(grants.update, doc) || reasons.push({
|
|
3248
|
+
type: "access",
|
|
3249
|
+
message: `You are not allowed to edit the document with ID "${docId}".`,
|
|
3250
|
+
documentId: docId
|
|
3251
|
+
}) : reasons.push({
|
|
3252
|
+
type: "precondition",
|
|
3253
|
+
message: `The document with ID "${docId}" could not be found. Please check that it exists before editing.`,
|
|
3254
|
+
documentId: docId
|
|
3255
|
+
});
|
|
3256
|
+
}
|
|
3257
|
+
const allowed = reasons.length === 0;
|
|
3258
|
+
if (allowed) return { allowed };
|
|
3259
|
+
const sortedReasons = reasons.map((reason, index) => ({ ...reason, index })).sort((a2, b2) => a2.type !== b2.type ? a2.type === "access" ? -1 : 1 : a2.message.localeCompare(b2.message, "en-US")).map(({ index: _index, ...reason }) => reason);
|
|
3260
|
+
return {
|
|
3261
|
+
allowed,
|
|
3262
|
+
reasons: sortedReasons,
|
|
3263
|
+
message: enNarrowConjunction.format(sortedReasons.map((i2) => i2.message))
|
|
3264
|
+
};
|
|
3265
|
+
}
|
|
3266
|
+
);
|
|
3267
|
+
function checkGrant(grantExpr, document2) {
|
|
3268
|
+
return C(grantExpr, { params: { document: document2 } }).get();
|
|
3269
|
+
}
|
|
3270
|
+
class ActionError extends Error {
|
|
3271
|
+
documentId;
|
|
3272
|
+
transactionId;
|
|
3273
|
+
constructor(options) {
|
|
3274
|
+
super(options.message), Object.assign(this, options);
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
class PermissionActionError extends ActionError {
|
|
3278
|
+
}
|
|
3279
|
+
function processActions({
|
|
3280
|
+
actions,
|
|
3281
|
+
transactionId,
|
|
3282
|
+
working: initialWorking,
|
|
3283
|
+
base: initialBase,
|
|
3284
|
+
timestamp,
|
|
3285
|
+
grants
|
|
3286
|
+
}) {
|
|
3287
|
+
let working = { ...initialWorking }, base = { ...initialBase };
|
|
3288
|
+
const outgoingActions = [], outgoingMutations = [];
|
|
3289
|
+
for (const action of actions)
|
|
3290
|
+
switch (action.type) {
|
|
3291
|
+
case "document.create": {
|
|
3292
|
+
const documentId = getId(action.documentId), draftId = getDraftId(documentId), publishedId = getPublishedId(documentId);
|
|
3293
|
+
if (working[draftId])
|
|
3294
|
+
throw new ActionError({
|
|
3295
|
+
documentId,
|
|
3296
|
+
transactionId,
|
|
3297
|
+
message: "A draft version of this document already exists. Please use or discard the existing draft before creating a new one."
|
|
3298
|
+
});
|
|
3299
|
+
const newDocBase = { ...base[publishedId], _type: action.documentType, _id: draftId }, newDocWorking = { ...working[publishedId], _type: action.documentType, _id: draftId }, mutations = [{ create: newDocWorking }];
|
|
3300
|
+
if (base = processMutations({
|
|
3301
|
+
documents: base,
|
|
3302
|
+
transactionId,
|
|
3303
|
+
mutations: [{ create: newDocBase }],
|
|
3304
|
+
timestamp
|
|
3305
|
+
}), working = processMutations({
|
|
3306
|
+
documents: working,
|
|
3307
|
+
transactionId,
|
|
3308
|
+
mutations,
|
|
3309
|
+
timestamp
|
|
3310
|
+
}), !checkGrant(grants.create, working[draftId]))
|
|
3311
|
+
throw new PermissionActionError({
|
|
3312
|
+
documentId,
|
|
3313
|
+
transactionId,
|
|
3314
|
+
message: `You do not have permission to create a draft for document "${documentId}".`
|
|
3315
|
+
});
|
|
3316
|
+
outgoingMutations.push(...mutations), outgoingActions.push({
|
|
3317
|
+
actionType: "sanity.action.document.version.create",
|
|
3318
|
+
publishedId,
|
|
3319
|
+
attributes: newDocWorking
|
|
3320
|
+
});
|
|
3321
|
+
continue;
|
|
3322
|
+
}
|
|
3323
|
+
case "document.delete": {
|
|
3324
|
+
const documentId = action.documentId, draftId = getDraftId(documentId), publishedId = getPublishedId(documentId);
|
|
3325
|
+
if (!working[publishedId])
|
|
3326
|
+
throw new ActionError({
|
|
3327
|
+
documentId,
|
|
3328
|
+
transactionId,
|
|
3329
|
+
message: working[draftId] ? "Cannot delete a document without a published version." : "The document you are trying to delete does not exist."
|
|
3330
|
+
});
|
|
3331
|
+
const cantDeleteDraft = working[draftId] && !checkGrant(grants.update, working[draftId]), cantDeletePublished = working[publishedId] && !checkGrant(grants.update, working[publishedId]);
|
|
3332
|
+
if (cantDeleteDraft || cantDeletePublished)
|
|
3333
|
+
throw new PermissionActionError({
|
|
3334
|
+
documentId,
|
|
3335
|
+
transactionId,
|
|
3336
|
+
message: "You do not have permission to delete this document."
|
|
3337
|
+
});
|
|
3338
|
+
const mutations = [{ delete: { id: publishedId } }, { delete: { id: draftId } }], includeDrafts = working[draftId] ? [draftId] : void 0;
|
|
3339
|
+
base = processMutations({ documents: base, transactionId, mutations, timestamp }), working = processMutations({ documents: working, transactionId, mutations, timestamp }), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
3340
|
+
actionType: "sanity.action.document.delete",
|
|
3341
|
+
publishedId,
|
|
3342
|
+
...includeDrafts ? { includeDrafts } : {}
|
|
3343
|
+
});
|
|
3344
|
+
continue;
|
|
3345
|
+
}
|
|
3346
|
+
case "document.discard": {
|
|
3347
|
+
const documentId = getId(action.documentId), draftId = getDraftId(documentId), mutations = [{ delete: { id: draftId } }];
|
|
3348
|
+
if (!working[draftId])
|
|
3349
|
+
throw new ActionError({
|
|
3350
|
+
documentId,
|
|
3351
|
+
transactionId,
|
|
3352
|
+
message: `There is no draft available to discard for document "${documentId}".`
|
|
3353
|
+
});
|
|
3354
|
+
if (!checkGrant(grants.update, working[draftId]))
|
|
3355
|
+
throw new PermissionActionError({
|
|
3356
|
+
documentId,
|
|
3357
|
+
transactionId,
|
|
3358
|
+
message: `You do not have permission to discard changes for document "${documentId}".`
|
|
3359
|
+
});
|
|
3360
|
+
base = processMutations({ documents: base, transactionId, mutations, timestamp }), working = processMutations({ documents: working, transactionId, mutations, timestamp }), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
3361
|
+
actionType: "sanity.action.document.version.discard",
|
|
3362
|
+
versionId: draftId
|
|
3363
|
+
});
|
|
3364
|
+
continue;
|
|
3365
|
+
}
|
|
3366
|
+
case "document.edit": {
|
|
3367
|
+
const documentId = getId(action.documentId), draftId = getDraftId(documentId), publishedId = getPublishedId(documentId), userPatches = action.patches?.map((patch) => ({ patch: { id: draftId, ...patch } }));
|
|
3368
|
+
if (!userPatches?.length) continue;
|
|
3369
|
+
if (!working[draftId] && !working[publishedId] || !base[draftId] && !base[publishedId])
|
|
3370
|
+
throw new ActionError({
|
|
3371
|
+
documentId,
|
|
3372
|
+
transactionId,
|
|
3373
|
+
message: "Cannot edit document because it does not exist in draft or published form."
|
|
3374
|
+
});
|
|
3375
|
+
const baseMutations = [];
|
|
3376
|
+
!base[draftId] && base[publishedId] && baseMutations.push({ create: { ...base[publishedId], _id: draftId } });
|
|
3377
|
+
const baseBefore = base[draftId] ?? base[publishedId];
|
|
3378
|
+
userPatches && baseMutations.push(...userPatches), base = processMutations({
|
|
3379
|
+
documents: base,
|
|
3380
|
+
transactionId,
|
|
3381
|
+
mutations: baseMutations,
|
|
3382
|
+
timestamp
|
|
3383
|
+
});
|
|
3384
|
+
const baseAfter = base[draftId], patches = diffPatch(baseBefore, baseAfter), workingMutations = [];
|
|
3385
|
+
if (!working[draftId] && working[publishedId]) {
|
|
3386
|
+
const newDraftFromPublished = { ...working[publishedId], _id: draftId };
|
|
3387
|
+
if (!checkGrant(grants.create, newDraftFromPublished))
|
|
3388
|
+
throw new PermissionActionError({
|
|
3389
|
+
documentId,
|
|
3390
|
+
transactionId,
|
|
3391
|
+
message: "You do not have permission to create a draft for editing this document."
|
|
3392
|
+
});
|
|
3393
|
+
workingMutations.push({ create: newDraftFromPublished });
|
|
3394
|
+
}
|
|
3395
|
+
const workingBefore = working[draftId] ?? working[publishedId];
|
|
3396
|
+
if (!checkGrant(grants.update, workingBefore))
|
|
3397
|
+
throw new PermissionActionError({
|
|
3398
|
+
documentId,
|
|
3399
|
+
transactionId,
|
|
3400
|
+
message: `You do not have permission to edit document "${documentId}".`
|
|
3401
|
+
});
|
|
3402
|
+
workingMutations.push(...patches.map((patch) => ({ patch: { id: draftId, ...patch } }))), working = processMutations({
|
|
3403
|
+
documents: working,
|
|
3404
|
+
transactionId,
|
|
3405
|
+
mutations: workingMutations,
|
|
3406
|
+
timestamp
|
|
3407
|
+
}), outgoingMutations.push(...workingMutations), outgoingActions.push(
|
|
3408
|
+
...patches.map(
|
|
3409
|
+
(patch) => ({
|
|
3410
|
+
actionType: "sanity.action.document.edit",
|
|
3411
|
+
draftId,
|
|
3412
|
+
publishedId,
|
|
3413
|
+
patch
|
|
3414
|
+
})
|
|
3415
|
+
)
|
|
3416
|
+
);
|
|
3417
|
+
continue;
|
|
3418
|
+
}
|
|
3419
|
+
case "document.publish": {
|
|
3420
|
+
const documentId = getId(action.documentId), draftId = getDraftId(documentId), publishedId = getPublishedId(documentId), workingDraft = working[draftId], baseDraft = base[draftId];
|
|
3421
|
+
if (!workingDraft || !baseDraft)
|
|
3422
|
+
throw new ActionError({
|
|
3423
|
+
documentId,
|
|
3424
|
+
transactionId,
|
|
3425
|
+
message: `Cannot publish because no draft version was found for document "${documentId}".`
|
|
3426
|
+
});
|
|
3427
|
+
if (!lodashEs.isEqual(workingDraft, baseDraft))
|
|
3428
|
+
throw new ActionError({
|
|
3429
|
+
documentId,
|
|
3430
|
+
transactionId,
|
|
3431
|
+
message: "Publish aborted: The document has changed elsewhere. Please try again."
|
|
3432
|
+
});
|
|
3433
|
+
const newPublishedFromDraft = { ...strengthenOnPublish(workingDraft), _id: publishedId }, mutations = [
|
|
3434
|
+
{ delete: { id: draftId } },
|
|
3435
|
+
{ createOrReplace: newPublishedFromDraft }
|
|
3436
|
+
];
|
|
3437
|
+
if (working[draftId] && !checkGrant(grants.update, working[draftId]))
|
|
3438
|
+
throw new PermissionActionError({
|
|
3439
|
+
documentId,
|
|
3440
|
+
transactionId,
|
|
3441
|
+
message: `Publish failed: You do not have permission to update the draft for "${documentId}".`
|
|
3442
|
+
});
|
|
3443
|
+
if (working[publishedId] && !checkGrant(grants.update, newPublishedFromDraft))
|
|
3444
|
+
throw new PermissionActionError({
|
|
3445
|
+
documentId,
|
|
3446
|
+
transactionId,
|
|
3447
|
+
message: `Publish failed: You do not have permission to update the published version of "${documentId}".`
|
|
3448
|
+
});
|
|
3449
|
+
if (!working[publishedId] && !checkGrant(grants.create, newPublishedFromDraft))
|
|
3450
|
+
throw new PermissionActionError({
|
|
3451
|
+
documentId,
|
|
3452
|
+
transactionId,
|
|
3453
|
+
message: `Publish failed: You do not have permission to publish a new version of "${documentId}".`
|
|
3454
|
+
});
|
|
3455
|
+
base = processMutations({ documents: base, transactionId, mutations, timestamp }), working = processMutations({ documents: working, transactionId, mutations, timestamp }), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
3456
|
+
actionType: "sanity.action.document.publish",
|
|
3457
|
+
draftId,
|
|
3458
|
+
publishedId
|
|
3459
|
+
});
|
|
3460
|
+
continue;
|
|
3461
|
+
}
|
|
3462
|
+
case "document.unpublish": {
|
|
3463
|
+
const documentId = getId(action.documentId), draftId = getDraftId(documentId), publishedId = getPublishedId(documentId);
|
|
3464
|
+
if (!working[publishedId] && !base[publishedId])
|
|
3465
|
+
throw new ActionError({
|
|
3466
|
+
documentId,
|
|
3467
|
+
transactionId,
|
|
3468
|
+
message: `Cannot unpublish because the document "${documentId}" is not currently published.`
|
|
3469
|
+
});
|
|
3470
|
+
const sourceDoc = working[publishedId] ?? base[publishedId], newDraftFromPublished = { ...sourceDoc, _id: draftId }, mutations = [
|
|
3471
|
+
{ delete: { id: publishedId } },
|
|
3472
|
+
{ createIfNotExists: newDraftFromPublished }
|
|
3473
|
+
];
|
|
3474
|
+
if (!checkGrant(grants.update, sourceDoc))
|
|
3475
|
+
throw new PermissionActionError({
|
|
3476
|
+
documentId,
|
|
3477
|
+
transactionId,
|
|
3478
|
+
message: `You do not have permission to unpublish the document "${documentId}".`
|
|
3479
|
+
});
|
|
3480
|
+
if (!working[draftId] && !checkGrant(grants.create, newDraftFromPublished))
|
|
3481
|
+
throw new PermissionActionError({
|
|
3482
|
+
documentId,
|
|
3483
|
+
transactionId,
|
|
3484
|
+
message: `You do not have permission to create a draft from the published version of "${documentId}".`
|
|
3485
|
+
});
|
|
3486
|
+
base = processMutations({
|
|
3487
|
+
documents: base,
|
|
3488
|
+
transactionId,
|
|
3489
|
+
mutations: [
|
|
3490
|
+
{ delete: { id: publishedId } },
|
|
3491
|
+
{ createIfNotExists: { ...base[publishedId] ?? sourceDoc, _id: draftId } }
|
|
3492
|
+
],
|
|
3493
|
+
timestamp
|
|
3494
|
+
}), working = processMutations({ documents: working, transactionId, mutations, timestamp }), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
3495
|
+
actionType: "sanity.action.document.unpublish",
|
|
3496
|
+
draftId,
|
|
3497
|
+
publishedId
|
|
3498
|
+
});
|
|
3499
|
+
continue;
|
|
3500
|
+
}
|
|
3501
|
+
default:
|
|
3502
|
+
throw new Error(
|
|
3503
|
+
`Unknown action type: "${// @ts-expect-error invalid input
|
|
3504
|
+
action.type}". Please contact support if this issue persists.`
|
|
3505
|
+
);
|
|
3506
|
+
}
|
|
3507
|
+
const previousRevs = Object.fromEntries(
|
|
3508
|
+
Object.entries(initialWorking).map(([id, doc]) => [id, doc?._rev])
|
|
3509
|
+
);
|
|
3510
|
+
return {
|
|
3511
|
+
working,
|
|
3512
|
+
outgoingActions,
|
|
3513
|
+
outgoingMutations,
|
|
3514
|
+
previous: initialWorking,
|
|
3515
|
+
previousRevs
|
|
3516
|
+
};
|
|
3517
|
+
}
|
|
3518
|
+
function strengthenOnPublish(draft) {
|
|
3519
|
+
const isStrengthenReference = (value) => "_strengthenOnPublish" in value;
|
|
3520
|
+
function strengthen(value) {
|
|
3521
|
+
if (typeof value != "object" || !value) return value;
|
|
3522
|
+
if (isStrengthenReference(value)) {
|
|
3523
|
+
const { _strengthenOnPublish, _weak, ...rest } = value;
|
|
3524
|
+
return {
|
|
3525
|
+
...rest,
|
|
3526
|
+
..._strengthenOnPublish.weak && { _weak: !0 }
|
|
3527
|
+
};
|
|
3528
|
+
}
|
|
3529
|
+
return Array.isArray(value) ? value.map(strengthen) : Object.fromEntries(Object.entries(value).map(([k2, v2]) => [k2, strengthen(v2)]));
|
|
3530
|
+
}
|
|
3531
|
+
return strengthen(draft);
|
|
3532
|
+
}
|
|
3533
|
+
const EMPTY_REVISIONS = {};
|
|
3534
|
+
function queueTransaction(prev, transaction) {
|
|
3535
|
+
const { transactionId, actions } = transaction;
|
|
3536
|
+
return {
|
|
3537
|
+
...getDocumentIdsFromActions(actions).reduce(
|
|
3538
|
+
(acc, id) => addSubscriptionIdToDocument(acc, id, transactionId),
|
|
3539
|
+
prev
|
|
3540
|
+
),
|
|
3541
|
+
queued: [...prev.queued, transaction]
|
|
3542
|
+
};
|
|
3543
|
+
}
|
|
3544
|
+
function removeQueuedTransaction(prev, transactionId) {
|
|
3545
|
+
const transaction = prev.queued.find((t2) => t2.transactionId === transactionId);
|
|
3546
|
+
return transaction ? {
|
|
3547
|
+
...getDocumentIdsFromActions(transaction.actions).reduce(
|
|
3548
|
+
(acc, id) => removeSubscriptionIdFromDocument(acc, id, transactionId),
|
|
3549
|
+
prev
|
|
3550
|
+
),
|
|
3551
|
+
queued: prev.queued.filter((t2) => transactionId !== t2.transactionId)
|
|
3552
|
+
} : prev;
|
|
3553
|
+
}
|
|
3554
|
+
function applyFirstQueuedTransaction(prev) {
|
|
3555
|
+
const queued = prev.queued.at(0);
|
|
3556
|
+
if (!queued || !prev.grants) return prev;
|
|
3557
|
+
const ids = getDocumentIdsFromActions(queued.actions);
|
|
3558
|
+
if (ids.some((id) => prev.documentStates[id]?.local === void 0)) return prev;
|
|
3559
|
+
const working = ids.reduce((acc, id) => (acc[id] = prev.documentStates[id]?.local, acc), {}), timestamp = (/* @__PURE__ */ new Date()).toISOString(), result = processActions({
|
|
3560
|
+
...queued,
|
|
3561
|
+
working,
|
|
3562
|
+
base: working,
|
|
3563
|
+
timestamp,
|
|
3564
|
+
grants: prev.grants
|
|
3565
|
+
}), applied = {
|
|
3566
|
+
...queued,
|
|
3567
|
+
...result,
|
|
3568
|
+
base: result.previous,
|
|
3569
|
+
timestamp
|
|
3570
|
+
};
|
|
3571
|
+
return {
|
|
3572
|
+
...prev,
|
|
3573
|
+
applied: [...prev.applied, applied],
|
|
3574
|
+
queued: prev.queued.filter((t2) => t2.transactionId !== queued.transactionId),
|
|
3575
|
+
documentStates: Object.entries(result.working).reduce(
|
|
3576
|
+
(acc, [id, next]) => {
|
|
3577
|
+
const prevDoc = acc[id];
|
|
3578
|
+
return prevDoc && (acc[id] = { ...prevDoc, local: next }), acc;
|
|
3579
|
+
},
|
|
3580
|
+
{ ...prev.documentStates }
|
|
3581
|
+
)
|
|
3582
|
+
};
|
|
3583
|
+
}
|
|
3584
|
+
function batchAppliedTransactions([curr, ...rest]) {
|
|
3585
|
+
if (!curr) return;
|
|
3586
|
+
if (!curr.actions.length) return batchAppliedTransactions(rest);
|
|
3587
|
+
if (curr.actions.length > 1)
|
|
3588
|
+
return {
|
|
3589
|
+
...curr,
|
|
3590
|
+
disableBatching: !0,
|
|
3591
|
+
batchedTransactionIds: [curr.transactionId]
|
|
3592
|
+
};
|
|
3593
|
+
const [action] = curr.actions;
|
|
3594
|
+
if (action.type !== "document.edit" || curr.disableBatching)
|
|
3595
|
+
return {
|
|
3596
|
+
...curr,
|
|
3597
|
+
disableBatching: !0,
|
|
3598
|
+
batchedTransactionIds: [curr.transactionId]
|
|
3599
|
+
};
|
|
3600
|
+
const editAction = {
|
|
3601
|
+
...curr,
|
|
3602
|
+
actions: [action],
|
|
3603
|
+
disableBatching: !1,
|
|
3604
|
+
batchedTransactionIds: [curr.transactionId]
|
|
3605
|
+
};
|
|
3606
|
+
if (!rest.length) return editAction;
|
|
3607
|
+
const next = batchAppliedTransactions(rest);
|
|
3608
|
+
if (next)
|
|
3609
|
+
return next.disableBatching ? editAction : {
|
|
3610
|
+
disableBatching: !1,
|
|
3611
|
+
// Use the transactionId from the later (next) transaction.
|
|
3612
|
+
transactionId: next.transactionId,
|
|
3613
|
+
// Accumulate actions: current action first, then later ones.
|
|
3614
|
+
actions: [action, ...next.actions],
|
|
3615
|
+
// Merge outgoingActions in order.
|
|
3616
|
+
outgoingActions: [...curr.outgoingActions, ...next.outgoingActions],
|
|
3617
|
+
// Batched transaction IDs: preserve order by placing curr first.
|
|
3618
|
+
batchedTransactionIds: [curr.transactionId, ...next.batchedTransactionIds],
|
|
3619
|
+
// Merge outgoingMutations in order.
|
|
3620
|
+
outgoingMutations: [...curr.outgoingMutations, ...next.outgoingMutations],
|
|
3621
|
+
// Working state reflects the latest optimistic changes: later transactions override earlier.
|
|
3622
|
+
working: { ...curr.working, ...next.working },
|
|
3623
|
+
// Base state (base, previous, previousRevs) must reflect the original state.
|
|
3624
|
+
// Use curr values (the earliest transaction) to override later ones.
|
|
3625
|
+
previousRevs: { ...next.previousRevs, ...curr.previousRevs },
|
|
3626
|
+
previous: { ...next.previous, ...curr.previous },
|
|
3627
|
+
base: { ...next.base, ...curr.base },
|
|
3628
|
+
// Use the earliest timestamp from curr.
|
|
3629
|
+
timestamp: curr.timestamp ?? next.timestamp
|
|
3630
|
+
};
|
|
3631
|
+
}
|
|
3632
|
+
function transitionAppliedTransactionsToOutgoing(prev) {
|
|
3633
|
+
if (prev.outgoing) return prev;
|
|
3634
|
+
const transaction = batchAppliedTransactions(prev.applied);
|
|
3635
|
+
if (!transaction) return prev;
|
|
3636
|
+
const {
|
|
3637
|
+
transactionId,
|
|
3638
|
+
previousRevs,
|
|
3639
|
+
working,
|
|
3640
|
+
batchedTransactionIds: consumedTransactions
|
|
3641
|
+
} = transaction, timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
3642
|
+
return {
|
|
3643
|
+
...prev,
|
|
3644
|
+
outgoing: transaction,
|
|
3645
|
+
applied: prev.applied.filter((i2) => !consumedTransactions.includes(i2.transactionId)),
|
|
3646
|
+
documentStates: Object.entries(previousRevs).reduce(
|
|
3647
|
+
(acc, [documentId, previousRev]) => {
|
|
3648
|
+
if (working[documentId]?._rev === previousRev) return acc;
|
|
3649
|
+
const documentState = prev.documentStates[documentId];
|
|
3650
|
+
return documentState && (acc[documentId] = {
|
|
3651
|
+
...documentState,
|
|
3652
|
+
unverifiedRevisions: {
|
|
3653
|
+
...documentState.unverifiedRevisions,
|
|
3654
|
+
// add unverified revision
|
|
3655
|
+
[transactionId]: { documentId, previousRev, transactionId, timestamp }
|
|
3656
|
+
}
|
|
3657
|
+
}), acc;
|
|
3658
|
+
},
|
|
3659
|
+
{ ...prev.documentStates }
|
|
3660
|
+
)
|
|
3661
|
+
};
|
|
3662
|
+
}
|
|
3663
|
+
function cleanupOutgoingTransaction(prev) {
|
|
3664
|
+
const { outgoing } = prev;
|
|
3665
|
+
if (!outgoing) return prev;
|
|
3666
|
+
let next = prev;
|
|
3667
|
+
const ids = getDocumentIdsFromActions(outgoing.actions);
|
|
3668
|
+
for (const transactionId of outgoing.batchedTransactionIds)
|
|
3669
|
+
for (const documentId of ids)
|
|
3670
|
+
next = removeSubscriptionIdFromDocument(next, documentId, transactionId);
|
|
3671
|
+
return { ...next, outgoing: void 0 };
|
|
3672
|
+
}
|
|
3673
|
+
function revertOutgoingTransaction(prev) {
|
|
3674
|
+
if (!prev.grants) return prev;
|
|
3675
|
+
let working = Object.fromEntries(
|
|
3676
|
+
Object.entries(prev.documentStates).map(([documentId, documentState]) => [
|
|
3677
|
+
documentId,
|
|
3678
|
+
documentState?.remote
|
|
3679
|
+
])
|
|
3680
|
+
);
|
|
3681
|
+
const nextApplied = [];
|
|
3682
|
+
for (const t2 of prev.applied)
|
|
3683
|
+
try {
|
|
3684
|
+
const next = processActions({ ...t2, working, grants: prev.grants });
|
|
3685
|
+
working = next.working, nextApplied.push({ ...t2, ...next });
|
|
3686
|
+
} catch (error) {
|
|
3687
|
+
if (error instanceof ActionError) continue;
|
|
3688
|
+
throw error;
|
|
3689
|
+
}
|
|
3690
|
+
return {
|
|
3691
|
+
...prev,
|
|
3692
|
+
applied: nextApplied,
|
|
3693
|
+
outgoing: void 0,
|
|
3694
|
+
documentStates: Object.fromEntries(
|
|
3695
|
+
Object.entries(prev.documentStates).filter((e3) => !!e3[1]).map(([documentId, { unverifiedRevisions = {}, local, ...documentState }]) => {
|
|
3696
|
+
const next = {
|
|
3697
|
+
...documentState,
|
|
3698
|
+
local: documentId in working ? working[documentId] : local,
|
|
3699
|
+
unverifiedRevisions: prev.outgoing && prev.outgoing.transactionId in unverifiedRevisions ? lodashEs.omit(unverifiedRevisions, prev.outgoing.transactionId) : unverifiedRevisions
|
|
3700
|
+
};
|
|
3701
|
+
return [documentId, next];
|
|
3702
|
+
})
|
|
3703
|
+
)
|
|
3704
|
+
};
|
|
3705
|
+
}
|
|
3706
|
+
function applyRemoteDocument(prev, { document: document2, documentId, previousRev, revision, timestamp, type }, events) {
|
|
3707
|
+
if (!prev.grants) return prev;
|
|
3708
|
+
const prevDocState = prev.documentStates[documentId];
|
|
3709
|
+
if (!prevDocState) return prev;
|
|
3710
|
+
const prevUnverifiedRevisions = prevDocState.unverifiedRevisions, revisionToVerify = revision ? prevUnverifiedRevisions?.[revision] : void 0;
|
|
3711
|
+
let unverifiedRevisions = prevUnverifiedRevisions ?? EMPTY_REVISIONS;
|
|
3712
|
+
if (revision && revisionToVerify && (unverifiedRevisions = lodashEs.omit(prevUnverifiedRevisions, revision)), type === "sync" && (unverifiedRevisions = Object.fromEntries(
|
|
3713
|
+
Object.entries(unverifiedRevisions).filter(([, unverifiedRevision]) => unverifiedRevision ? new Date(timestamp).getTime() <= new Date(unverifiedRevision.timestamp).getTime() : !1)
|
|
3714
|
+
)), revisionToVerify && revisionToVerify.previousRev === previousRev)
|
|
3715
|
+
return {
|
|
3716
|
+
...prev,
|
|
3717
|
+
documentStates: {
|
|
3718
|
+
...prev.documentStates,
|
|
3719
|
+
[documentId]: {
|
|
3720
|
+
...prevDocState,
|
|
3721
|
+
remote: document2,
|
|
3722
|
+
remoteRev: revision,
|
|
3723
|
+
unverifiedRevisions
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
};
|
|
3727
|
+
let working = { ...prev.applied.at(0)?.previous, [documentId]: document2 };
|
|
3728
|
+
const nextApplied = [];
|
|
3729
|
+
for (const curr of prev.applied)
|
|
3730
|
+
try {
|
|
3731
|
+
const next = processActions({ ...curr, working, grants: prev.grants });
|
|
3732
|
+
working = next.working, nextApplied.push({ ...curr, ...next });
|
|
3733
|
+
} catch (error) {
|
|
3734
|
+
if (error instanceof ActionError) {
|
|
3735
|
+
events.next({
|
|
3736
|
+
type: "rebase-error",
|
|
3737
|
+
transactionId: error.transactionId,
|
|
3738
|
+
documentId: error.documentId,
|
|
3739
|
+
message: error.message,
|
|
3740
|
+
error
|
|
3741
|
+
});
|
|
3742
|
+
continue;
|
|
3743
|
+
}
|
|
3744
|
+
throw error;
|
|
3745
|
+
}
|
|
3746
|
+
return {
|
|
3747
|
+
...prev,
|
|
3748
|
+
applied: nextApplied,
|
|
3749
|
+
documentStates: {
|
|
3750
|
+
...prev.documentStates,
|
|
3751
|
+
[documentId]: {
|
|
3752
|
+
...prevDocState,
|
|
3753
|
+
remote: document2,
|
|
3754
|
+
remoteRev: revision,
|
|
3755
|
+
local: working[documentId],
|
|
3756
|
+
unverifiedRevisions
|
|
3757
|
+
}
|
|
3758
|
+
}
|
|
3759
|
+
};
|
|
3760
|
+
}
|
|
3761
|
+
function addSubscriptionIdToDocument(prev, documentId, subscriptionId) {
|
|
3762
|
+
const prevDocState = prev.documentStates?.[documentId], prevSubscriptions = prevDocState?.subscriptions ?? [];
|
|
3763
|
+
return {
|
|
3764
|
+
...prev,
|
|
3765
|
+
documentStates: {
|
|
3766
|
+
...prev.documentStates,
|
|
3767
|
+
[documentId]: {
|
|
3768
|
+
...prevDocState,
|
|
3769
|
+
id: documentId,
|
|
3770
|
+
subscriptions: [...prevSubscriptions, subscriptionId]
|
|
3771
|
+
}
|
|
3772
|
+
}
|
|
3773
|
+
};
|
|
3774
|
+
}
|
|
3775
|
+
function removeSubscriptionIdFromDocument(prev, documentId, subscriptionId) {
|
|
3776
|
+
const prevDocState = prev.documentStates?.[documentId], subscriptions = (prevDocState?.subscriptions ?? []).filter((id) => id !== subscriptionId);
|
|
3777
|
+
return prevDocState ? subscriptions.length ? {
|
|
3778
|
+
...prev,
|
|
3779
|
+
documentStates: {
|
|
3780
|
+
...prev.documentStates,
|
|
3781
|
+
[documentId]: { ...prevDocState, subscriptions }
|
|
3782
|
+
}
|
|
3783
|
+
} : { ...prev, documentStates: lodashEs.omit(prev.documentStates, documentId) } : prev;
|
|
3784
|
+
}
|
|
3785
|
+
function manageSubscriberIds(state, documentId) {
|
|
3786
|
+
const documentIds = Array.from(
|
|
3787
|
+
new Set(
|
|
3788
|
+
(Array.isArray(documentId) ? documentId : [documentId]).flatMap((id) => [
|
|
3789
|
+
csm.getPublishedId(id),
|
|
3790
|
+
getDraftId(id)
|
|
3791
|
+
])
|
|
3792
|
+
)
|
|
3793
|
+
), subscriptionId = insecureRandomId();
|
|
3794
|
+
return state.set(
|
|
3795
|
+
"addSubscribers",
|
|
3796
|
+
(prev) => documentIds.reduce(
|
|
3797
|
+
(acc, id) => addSubscriptionIdToDocument(acc, id, subscriptionId),
|
|
3798
|
+
prev
|
|
3799
|
+
)
|
|
3800
|
+
), () => {
|
|
3801
|
+
setTimeout(() => {
|
|
3802
|
+
state.set(
|
|
3803
|
+
"removeSubscribers",
|
|
3804
|
+
(prev) => documentIds.reduce(
|
|
3805
|
+
(acc, id) => removeSubscriptionIdFromDocument(acc, id, subscriptionId),
|
|
3806
|
+
prev
|
|
3807
|
+
)
|
|
3808
|
+
);
|
|
3809
|
+
}, DOCUMENT_STATE_CLEAR_DELAY);
|
|
3810
|
+
};
|
|
3811
|
+
}
|
|
3812
|
+
function getDocumentIdsFromActions(action) {
|
|
3813
|
+
const actions = Array.isArray(action) ? action : [action];
|
|
3814
|
+
return Array.from(
|
|
3815
|
+
new Set(
|
|
3816
|
+
actions.map((i2) => i2.documentId).filter((i2) => typeof i2 == "string").flatMap((documentId) => [csm.getPublishedId(documentId), getDraftId(documentId)])
|
|
3817
|
+
)
|
|
3818
|
+
);
|
|
3819
|
+
}
|
|
3820
|
+
function getDocumentEvents(outgoing) {
|
|
3821
|
+
const documentIdsByAction = Object.entries(
|
|
3822
|
+
outgoing.actions.reduce(
|
|
3823
|
+
(acc, { type, documentId }) => {
|
|
3824
|
+
const ids = acc[type] || /* @__PURE__ */ new Set();
|
|
3825
|
+
return documentId && ids.add(documentId), acc[type] = ids, acc;
|
|
3826
|
+
},
|
|
3827
|
+
{}
|
|
3828
|
+
)
|
|
3829
|
+
), actionMap = {
|
|
3830
|
+
"document.create": "created",
|
|
3831
|
+
"document.delete": "deleted",
|
|
3832
|
+
"document.discard": "discarded",
|
|
3833
|
+
"document.edit": "edited",
|
|
3834
|
+
"document.publish": "published",
|
|
3835
|
+
"document.unpublish": "unpublished"
|
|
3836
|
+
};
|
|
3837
|
+
return documentIdsByAction.flatMap(
|
|
3838
|
+
([actionType, documentIds]) => Array.from(documentIds).map(
|
|
3839
|
+
(documentId) => ({ type: actionMap[actionType], documentId, outgoing })
|
|
3840
|
+
)
|
|
3841
|
+
);
|
|
3842
|
+
}
|
|
3843
|
+
const API_VERSION$1 = "vX";
|
|
3844
|
+
function createSharedListener(instance) {
|
|
3845
|
+
const events$ = getClientState(instance, { apiVersion: API_VERSION$1 }).observable.pipe(
|
|
3846
|
+
rxjs.switchMap(
|
|
3847
|
+
(client2) => (
|
|
3848
|
+
// TODO: it seems like the client.listen method is not emitting disconnected
|
|
3849
|
+
// events. this is important to ensure we have an up to date version of the
|
|
3850
|
+
// doc. probably should introduce our own events for when the user goes offline
|
|
3851
|
+
client2.listen(
|
|
3852
|
+
"*",
|
|
3853
|
+
{},
|
|
3854
|
+
{
|
|
3855
|
+
events: ["mutation", "welcome", "reconnect"],
|
|
3856
|
+
includeResult: !1,
|
|
3857
|
+
tag: "document-listener"
|
|
3858
|
+
// // from manual testing, it seems like mendoza patches may be
|
|
3859
|
+
// // causing some ambiguity/wonkiness
|
|
3860
|
+
// includeMutations: false,
|
|
3861
|
+
// effectFormat: 'mendoza',
|
|
3862
|
+
}
|
|
3863
|
+
)
|
|
3864
|
+
)
|
|
3865
|
+
),
|
|
3866
|
+
rxjs.share()
|
|
3867
|
+
), [welcome$, mutation$] = rxjs.partition(events$, (e3) => e3.type === "welcome");
|
|
3868
|
+
return rxjs.merge(
|
|
3869
|
+
// we replay the welcome event because that event kicks off fetching the document
|
|
3870
|
+
welcome$.pipe(rxjs.shareReplay(1)),
|
|
3871
|
+
mutation$
|
|
3872
|
+
);
|
|
3873
|
+
}
|
|
3874
|
+
function createFetchDocument(instance) {
|
|
3875
|
+
return function(documentId) {
|
|
3876
|
+
return getClientState(instance, { apiVersion: API_VERSION$1 }).observable.pipe(
|
|
3877
|
+
rxjs.switchMap((client2) => _unstable_store.createDocumentLoaderFromClient(client2)(documentId)),
|
|
3878
|
+
rxjs.map((result) => {
|
|
3879
|
+
if (!result.accessible) {
|
|
3880
|
+
if (result.reason === "existence") return null;
|
|
3881
|
+
throw new Error(`Document with ID \`${documentId}\` is inaccessible due to permissions.`);
|
|
3882
|
+
}
|
|
3883
|
+
return result.document;
|
|
3884
|
+
}),
|
|
3885
|
+
rxjs.first()
|
|
3886
|
+
);
|
|
3887
|
+
};
|
|
3888
|
+
}
|
|
3889
|
+
const documentStore = {
|
|
3890
|
+
name: "Document",
|
|
3891
|
+
getInitialState: (instance) => ({
|
|
3892
|
+
documentStates: {},
|
|
3893
|
+
// these can be emptied on refetch
|
|
3894
|
+
queued: [],
|
|
3895
|
+
applied: [],
|
|
3896
|
+
sharedListener: createSharedListener(instance),
|
|
3897
|
+
fetchDocument: createFetchDocument(instance),
|
|
3898
|
+
events: new rxjs.Subject()
|
|
3899
|
+
}),
|
|
3900
|
+
initialize() {
|
|
3901
|
+
const queuedTransactionSubscription = subscribeToQueuedAndApplyNextTransaction(this), subscriptionsSubscription = subscribeToSubscriptionsAndListenToDocuments(this), appliedSubscription = subscribeToAppliedAndSubmitNextTransaction(this), clientSubscription = subscribeToClientAndFetchDatasetAcl(this);
|
|
3902
|
+
return () => {
|
|
3903
|
+
queuedTransactionSubscription.unsubscribe(), subscriptionsSubscription.unsubscribe(), appliedSubscription.unsubscribe(), clientSubscription.unsubscribe();
|
|
3904
|
+
};
|
|
3905
|
+
}
|
|
3906
|
+
};
|
|
3907
|
+
function getDocumentState(...args) {
|
|
3908
|
+
return _getDocumentState(...args);
|
|
3909
|
+
}
|
|
3910
|
+
const _getDocumentState = createStateSourceAction(documentStore, {
|
|
3911
|
+
selector: ({ error, documentStates }, doc, path) => {
|
|
3912
|
+
const documentId = typeof doc == "string" ? doc : doc._id;
|
|
3913
|
+
if (error) throw error;
|
|
3914
|
+
const draftId = getDraftId(documentId), publishedId = csm.getPublishedId(documentId), draft = documentStates[draftId]?.local, published = documentStates[publishedId]?.local, document2 = draft ?? published;
|
|
3915
|
+
if (document2 !== void 0)
|
|
3916
|
+
return path ? jsonMatch(document2, path).at(0)?.value : document2;
|
|
3917
|
+
},
|
|
3918
|
+
onSubscribe: ({ state }, doc) => manageSubscriberIds(state, typeof doc == "string" ? doc : doc._id)
|
|
3919
|
+
});
|
|
3920
|
+
function resolveDocument(...args) {
|
|
3921
|
+
return _resolveDocument(...args);
|
|
3922
|
+
}
|
|
3923
|
+
const _resolveDocument = createAction(documentStore, () => function(doc) {
|
|
3924
|
+
const documentId = typeof doc == "string" ? doc : doc._id;
|
|
3925
|
+
return rxjs.firstValueFrom(
|
|
3926
|
+
getDocumentState(this, documentId).observable.pipe(rxjs.filter((i2) => i2 !== void 0))
|
|
3927
|
+
);
|
|
3928
|
+
}), getDocumentSyncStatus = createStateSourceAction(documentStore, {
|
|
3929
|
+
selector: ({ error, documentStates: documents, outgoing, applied, queued }, doc) => {
|
|
3930
|
+
const documentId = doc._id;
|
|
3931
|
+
if (error) throw error;
|
|
3932
|
+
const draftId = getDraftId(documentId), publishedId = csm.getPublishedId(documentId), draft = documents[draftId], published = documents[publishedId];
|
|
3933
|
+
if (!(draft === void 0 || published === void 0))
|
|
3934
|
+
return !queued.length && !applied.length && !outgoing;
|
|
3935
|
+
},
|
|
3936
|
+
onSubscribe: ({ state }, doc) => manageSubscriberIds(state, doc._id)
|
|
3937
|
+
}), getPermissionsState = createStateSourceAction(documentStore, {
|
|
3938
|
+
selector: calculatePermissions,
|
|
3939
|
+
onSubscribe: ({ state }, actions) => manageSubscriberIds(state, getDocumentIdsFromActions(actions))
|
|
3940
|
+
}), resolvePermissions = createAction(documentStore, () => function(actions) {
|
|
3941
|
+
return rxjs.firstValueFrom(
|
|
3942
|
+
getPermissionsState(this, actions).observable.pipe(rxjs.filter((i2) => i2 !== void 0))
|
|
3943
|
+
);
|
|
3944
|
+
}), subscribeDocumentEvents = createAction(documentStore, ({ state }) => {
|
|
3945
|
+
const { events } = state.get();
|
|
3946
|
+
return function(eventHandler) {
|
|
3947
|
+
const subscription = events.subscribe(eventHandler);
|
|
3948
|
+
return () => subscription.unsubscribe();
|
|
3949
|
+
};
|
|
3950
|
+
}), subscribeToQueuedAndApplyNextTransaction = createInternalAction(
|
|
3951
|
+
({ state }) => {
|
|
3952
|
+
const { events } = state.get();
|
|
3953
|
+
return function() {
|
|
3954
|
+
return state.observable.pipe(
|
|
3955
|
+
rxjs.map(applyFirstQueuedTransaction),
|
|
3956
|
+
rxjs.distinctUntilChanged(),
|
|
3957
|
+
rxjs.tap((next) => state.set("applyFirstQueuedTransaction", next)),
|
|
3958
|
+
rxjs.catchError((error, caught) => {
|
|
3959
|
+
if (error instanceof ActionError)
|
|
3960
|
+
return state.set(
|
|
3961
|
+
"removeQueuedTransaction",
|
|
3962
|
+
(prev) => removeQueuedTransaction(prev, error.transactionId)
|
|
3963
|
+
), events.next({
|
|
3964
|
+
type: "error",
|
|
3965
|
+
message: error.message,
|
|
3966
|
+
documentId: error.documentId,
|
|
3967
|
+
transactionId: error.transactionId,
|
|
3968
|
+
error
|
|
3969
|
+
}), caught;
|
|
3970
|
+
throw error;
|
|
3971
|
+
})
|
|
3972
|
+
).subscribe({ error: (error) => state.set("setError", { error }) });
|
|
3973
|
+
};
|
|
3974
|
+
}
|
|
3975
|
+
), subscribeToAppliedAndSubmitNextTransaction = createInternalAction(
|
|
3976
|
+
({ state, instance }) => {
|
|
3977
|
+
const { events } = state.get();
|
|
3978
|
+
return function() {
|
|
3979
|
+
return state.observable.pipe(
|
|
3980
|
+
rxjs.throttle(
|
|
3981
|
+
(s2) => (
|
|
3982
|
+
// if there is no outgoing transaction, we can throttle by the
|
|
3983
|
+
// initial outgoing throttle time…
|
|
3984
|
+
s2.outgoing ? (
|
|
3985
|
+
// …otherwise, wait until the outgoing has been cleared
|
|
3986
|
+
state.observable.pipe(rxjs.first(({ outgoing }) => !outgoing))
|
|
3987
|
+
) : rxjs.timer(INITIAL_OUTGOING_THROTTLE_TIME)
|
|
3988
|
+
),
|
|
3989
|
+
{ leading: !1, trailing: !0 }
|
|
3990
|
+
),
|
|
3991
|
+
rxjs.map(transitionAppliedTransactionsToOutgoing),
|
|
3992
|
+
rxjs.distinctUntilChanged((a2, b2) => a2.outgoing?.transactionId === b2.outgoing?.transactionId),
|
|
3993
|
+
rxjs.tap((next) => state.set("transitionAppliedTransactionsToOutgoing", next)),
|
|
3994
|
+
rxjs.map((s2) => s2.outgoing),
|
|
3995
|
+
rxjs.distinctUntilChanged(),
|
|
3996
|
+
rxjs.withLatestFrom(getClientState(instance, { apiVersion: API_VERSION$2 }).observable),
|
|
3997
|
+
rxjs.concatMap(([outgoing, client2]) => outgoing ? client2.observable.action(outgoing.outgoingActions, {
|
|
3998
|
+
transactionId: outgoing.transactionId,
|
|
3999
|
+
skipCrossDatasetReferenceValidation: !0
|
|
4000
|
+
}).pipe(
|
|
4001
|
+
rxjs.catchError((error) => (state.set("revertOutgoingTransaction", revertOutgoingTransaction), events.next({ type: "reverted", message: error.message, outgoing, error }), rxjs.EMPTY)),
|
|
4002
|
+
rxjs.map((result) => ({ result, outgoing }))
|
|
4003
|
+
) : rxjs.EMPTY),
|
|
4004
|
+
rxjs.tap(({ outgoing, result }) => {
|
|
4005
|
+
state.set("cleanupOutgoingTransaction", cleanupOutgoingTransaction);
|
|
4006
|
+
for (const e3 of getDocumentEvents(outgoing)) events.next(e3);
|
|
4007
|
+
events.next({ type: "accepted", outgoing, result });
|
|
4008
|
+
})
|
|
4009
|
+
).subscribe({ error: (error) => state.set("setError", { error }) });
|
|
4010
|
+
};
|
|
4011
|
+
}
|
|
4012
|
+
), subscribeToSubscriptionsAndListenToDocuments = createInternalAction(
|
|
4013
|
+
({ state }) => {
|
|
4014
|
+
const { events } = state.get();
|
|
4015
|
+
return function() {
|
|
4016
|
+
return state.observable.pipe(
|
|
4017
|
+
rxjs.filter((s2) => !!s2.grants),
|
|
4018
|
+
rxjs.map((s2) => Object.keys(s2.documentStates)),
|
|
4019
|
+
rxjs.distinctUntilChanged((curr, next) => {
|
|
4020
|
+
if (curr.length !== next.length) return !1;
|
|
4021
|
+
const currSet = new Set(curr);
|
|
4022
|
+
return next.every((i2) => currSet.has(i2));
|
|
4023
|
+
}),
|
|
4024
|
+
rxjs.startWith(/* @__PURE__ */ new Set()),
|
|
4025
|
+
rxjs.pairwise(),
|
|
4026
|
+
rxjs.switchMap((pair) => {
|
|
4027
|
+
const [curr, next] = pair.map((ids) => new Set(ids)), added = Array.from(next).filter((i2) => !curr.has(i2)), removed = Array.from(curr).filter((i2) => !next.has(i2)), changes = [
|
|
4028
|
+
...added.map((id) => ({ id, add: !0 })),
|
|
4029
|
+
...removed.map((id) => ({ id, add: !1 }))
|
|
4030
|
+
].sort((a2, b2) => {
|
|
4031
|
+
const aIsDraft = a2.id === getDraftId(a2.id), bIsDraft = b2.id === getDraftId(b2.id);
|
|
4032
|
+
return aIsDraft && bIsDraft ? a2.id.localeCompare(b2.id, "en-US") : aIsDraft ? -1 : bIsDraft ? 1 : a2.id.localeCompare(b2.id, "en-US");
|
|
4033
|
+
});
|
|
4034
|
+
return rxjs.of(...changes);
|
|
4035
|
+
}),
|
|
4036
|
+
rxjs.groupBy((i2) => i2.id),
|
|
4037
|
+
rxjs.mergeMap(
|
|
4038
|
+
(group) => group.pipe(
|
|
4039
|
+
rxjs.switchMap((e3) => e3.add ? listen(this, e3.id).pipe(
|
|
4040
|
+
rxjs.catchError((error) => {
|
|
4041
|
+
throw error instanceof OutOfSyncError && listen(this, e3.id), error;
|
|
4042
|
+
}),
|
|
4043
|
+
rxjs.tap(
|
|
4044
|
+
(remote) => state.set(
|
|
4045
|
+
"applyRemoteDocument",
|
|
4046
|
+
(prev) => applyRemoteDocument(prev, remote, events)
|
|
4047
|
+
)
|
|
4048
|
+
)
|
|
4049
|
+
) : rxjs.EMPTY)
|
|
4050
|
+
)
|
|
4051
|
+
)
|
|
4052
|
+
).subscribe({ error: (error) => state.set("setError", { error }) });
|
|
4053
|
+
};
|
|
4054
|
+
}
|
|
4055
|
+
), subscribeToClientAndFetchDatasetAcl = createInternalAction(
|
|
4056
|
+
({ instance, state }) => {
|
|
4057
|
+
const { projectId, dataset } = instance.identity;
|
|
4058
|
+
return function() {
|
|
4059
|
+
return getClientState(instance, { apiVersion: API_VERSION$2 }).observable.pipe(
|
|
4060
|
+
rxjs.switchMap(
|
|
4061
|
+
(client2) => client2.observable.request({
|
|
4062
|
+
uri: `/projects/${projectId}/datasets/${dataset}/acl`,
|
|
4063
|
+
tag: "acl.get",
|
|
4064
|
+
withCredentials: !0
|
|
4065
|
+
})
|
|
4066
|
+
),
|
|
4067
|
+
rxjs.tap((datasetAcl) => state.set("setGrants", { grants: createGrantsLookup(datasetAcl) }))
|
|
4068
|
+
).subscribe({
|
|
4069
|
+
error: (error) => state.set("setError", { error })
|
|
4070
|
+
});
|
|
4071
|
+
};
|
|
4072
|
+
}
|
|
4073
|
+
);
|
|
4074
|
+
function applyDocumentActions(...args) {
|
|
4075
|
+
return _applyDocumentActions(...args);
|
|
4076
|
+
}
|
|
4077
|
+
const _applyDocumentActions = createAction(documentStore, ({ state }) => {
|
|
4078
|
+
const { events } = state.get();
|
|
4079
|
+
return async function(action, { transactionId = crypto.randomUUID(), disableBatching } = {}) {
|
|
4080
|
+
const actions = Array.isArray(action) ? action : [action], transaction = {
|
|
4081
|
+
transactionId,
|
|
4082
|
+
actions,
|
|
4083
|
+
...disableBatching && { disableBatching }
|
|
4084
|
+
}, fatalError$ = state.observable.pipe(
|
|
4085
|
+
rxjs.map((s2) => s2.error),
|
|
4086
|
+
rxjs.first(Boolean),
|
|
4087
|
+
rxjs.map((error) => ({ type: "error", error }))
|
|
4088
|
+
), transactionError$ = events.pipe(
|
|
4089
|
+
rxjs.filter((e3) => e3.type === "error"),
|
|
4090
|
+
rxjs.first((e3) => e3.transactionId === transactionId)
|
|
4091
|
+
), appliedTransaction$ = state.observable.pipe(
|
|
4092
|
+
rxjs.map((s2) => s2.applied),
|
|
4093
|
+
rxjs.distinctUntilChanged(),
|
|
4094
|
+
rxjs.map((applied) => applied.find((t2) => t2.transactionId === transactionId)),
|
|
4095
|
+
rxjs.first(Boolean)
|
|
4096
|
+
), successfulTransaction$ = events.pipe(
|
|
4097
|
+
rxjs.filter((e3) => e3.type === "accepted"),
|
|
4098
|
+
rxjs.first((e3) => e3.outgoing.batchedTransactionIds.includes(transactionId))
|
|
4099
|
+
), rejectedTransaction$ = events.pipe(
|
|
4100
|
+
rxjs.filter((e3) => e3.type === "reverted"),
|
|
4101
|
+
rxjs.first((e3) => e3.outgoing.batchedTransactionIds.includes(transactionId))
|
|
4102
|
+
), appliedTransactionOrError = rxjs.firstValueFrom(
|
|
4103
|
+
rxjs.race([fatalError$, transactionError$, appliedTransaction$])
|
|
4104
|
+
), acceptedOrRejectedTransaction = rxjs.firstValueFrom(
|
|
4105
|
+
rxjs.race([successfulTransaction$, rejectedTransaction$, transactionError$])
|
|
4106
|
+
);
|
|
4107
|
+
state.set("queueTransaction", (prev) => queueTransaction(prev, transaction));
|
|
4108
|
+
const result = await appliedTransactionOrError;
|
|
4109
|
+
if ("type" in result && result.type === "error") throw result.error;
|
|
4110
|
+
const { working: documents, previous, previousRevs } = result, existingIds = new Set(
|
|
4111
|
+
Object.entries(previous).filter(([, value]) => !!value).map(([key]) => key)
|
|
4112
|
+
), resultingIds = new Set(
|
|
4113
|
+
Object.entries(documents).filter(([, value]) => !!value).map(([key]) => key)
|
|
4114
|
+
), allIds = /* @__PURE__ */ new Set([...existingIds, ...resultingIds]), updated = [], appeared = [], disappeared = [];
|
|
4115
|
+
for (const id of allIds)
|
|
4116
|
+
existingIds.has(id) && resultingIds.has(id) ? updated.push(id) : !existingIds.has(id) && resultingIds.has(id) ? appeared.push(id) : !resultingIds.has(id) && existingIds.has(id) && disappeared.push(id);
|
|
4117
|
+
async function submitted() {
|
|
4118
|
+
const raceResult = await acceptedOrRejectedTransaction;
|
|
4119
|
+
if (raceResult.type !== "accepted") throw raceResult.error;
|
|
4120
|
+
return raceResult.result;
|
|
4121
|
+
}
|
|
4122
|
+
return {
|
|
4123
|
+
transactionId,
|
|
4124
|
+
documents,
|
|
4125
|
+
previous,
|
|
4126
|
+
previousRevs,
|
|
4127
|
+
appeared,
|
|
4128
|
+
updated,
|
|
4129
|
+
disappeared,
|
|
4130
|
+
submitted
|
|
4131
|
+
};
|
|
4132
|
+
};
|
|
4133
|
+
});
|
|
4134
|
+
function getSdkIdentity({
|
|
4135
|
+
projectId,
|
|
4136
|
+
dataset
|
|
4137
|
+
}) {
|
|
4138
|
+
const id = generateId();
|
|
4139
|
+
return Object.freeze({
|
|
4140
|
+
id,
|
|
4141
|
+
projectId,
|
|
4142
|
+
dataset,
|
|
4143
|
+
resourceId: `${projectId}.${dataset}`
|
|
4144
|
+
});
|
|
4145
|
+
}
|
|
4146
|
+
function generateId() {
|
|
4147
|
+
return Array.from(
|
|
4148
|
+
{ length: 8 },
|
|
4149
|
+
() => Math.floor(Math.random() * 16).toString(16).padStart(2, "0")
|
|
4150
|
+
).join("");
|
|
4151
|
+
}
|
|
4152
|
+
function createSanityInstance({
|
|
4153
|
+
projectId = "",
|
|
4154
|
+
dataset = "",
|
|
4155
|
+
...config
|
|
4156
|
+
}) {
|
|
4157
|
+
const identity = getSdkIdentity({ projectId, dataset });
|
|
4158
|
+
return {
|
|
4159
|
+
identity,
|
|
4160
|
+
config,
|
|
4161
|
+
dispose: () => disposeResources(identity)
|
|
4162
|
+
};
|
|
4163
|
+
}
|
|
4164
|
+
function createLiveEventSubscriber(tag) {
|
|
4165
|
+
return createInternalAction(({ instance, state }) => {
|
|
4166
|
+
const client$ = getClientState(instance, { apiVersion: "vX" }).observable, syncTags$ = state.observable.pipe(
|
|
4167
|
+
rxjs.map((i2) => i2.syncTags),
|
|
4168
|
+
rxjs.distinctUntilChanged()
|
|
4169
|
+
);
|
|
4170
|
+
return function() {
|
|
4171
|
+
const messageEvents$ = client$.pipe(
|
|
4172
|
+
rxjs.switchMap(
|
|
4173
|
+
(client2) => client2.live.events({ includeDrafts: !!client2.config().token, tag }).pipe(rxjs.filter((e3) => e3.type === "message"))
|
|
4174
|
+
)
|
|
4175
|
+
);
|
|
4176
|
+
return rxjs.combineLatest([messageEvents$, syncTags$]).subscribe({
|
|
4177
|
+
next: ([event, currentSyncTags]) => {
|
|
4178
|
+
for (const eventTag of event.tags)
|
|
4179
|
+
if (currentSyncTags[eventTag]) {
|
|
4180
|
+
state.set("setLastLiveEventId", (prevState) => ({
|
|
4181
|
+
...prevState,
|
|
4182
|
+
lastLiveEventId: event.id
|
|
4183
|
+
}));
|
|
4184
|
+
return;
|
|
4185
|
+
}
|
|
4186
|
+
}
|
|
4187
|
+
});
|
|
4188
|
+
};
|
|
4189
|
+
});
|
|
4190
|
+
}
|
|
4191
|
+
function hashString(str) {
|
|
4192
|
+
let hash = 0;
|
|
4193
|
+
for (let i2 = 0; i2 < str.length; i2++)
|
|
4194
|
+
hash = (hash * 31 + str.charCodeAt(i2)) % 2147483647;
|
|
4195
|
+
return Math.abs(hash).toString(16).padStart(8, "0");
|
|
4196
|
+
}
|
|
4197
|
+
const TITLE_CANDIDATES = ["title", "name", "label", "heading", "header", "caption"], SUBTITLE_CANDIDATES = ["description", "subtitle", ...TITLE_CANDIDATES];
|
|
4198
|
+
function getPreviewProjection() {
|
|
4199
|
+
return `{
|
|
4200
|
+
// Get all potential title fields
|
|
4201
|
+
"titleCandidates": {
|
|
4202
|
+
${TITLE_CANDIDATES.map((field) => `"${field}": ${field}`).join(`,
|
|
4203
|
+
`)}
|
|
4204
|
+
},
|
|
4205
|
+
// Get all potential subtitle fields
|
|
4206
|
+
"subtitleCandidates": {
|
|
4207
|
+
${SUBTITLE_CANDIDATES.map((field) => `"${field}": ${field}`).join(`,
|
|
4208
|
+
`)}
|
|
4209
|
+
},
|
|
4210
|
+
"media": coalesce(
|
|
4211
|
+
select(
|
|
4212
|
+
defined(asset) => {"type": "image-asset", "_ref": asset._ref},
|
|
4213
|
+
defined(image.asset) => {"type": "image-asset", "_ref": image.asset._ref},
|
|
4214
|
+
defined(mainImage.asset) => {"type": "image-asset", "_ref": mainImage.asset._ref},
|
|
4215
|
+
null
|
|
4216
|
+
)
|
|
4217
|
+
),
|
|
4218
|
+
_type,
|
|
4219
|
+
_id,
|
|
4220
|
+
_updatedAt
|
|
4221
|
+
}`;
|
|
4222
|
+
}
|
|
4223
|
+
const PREVIEW_TAG = "preview", STABLE_EMPTY_PREVIEW = { data: null, isPending: !1 }, STABLE_ERROR_PREVIEW = {
|
|
4224
|
+
data: {
|
|
4225
|
+
title: "Preview Error",
|
|
4226
|
+
...!!getEnv("DEV") && { subtitle: "Check the console for more details" }
|
|
4227
|
+
},
|
|
4228
|
+
isPending: !1
|
|
4229
|
+
};
|
|
4230
|
+
function assetIdToUrl(assetId, projectId, dataset) {
|
|
4231
|
+
const pattern = /^image-(?<assetName>[A-Za-z0-9]+)-(?<dimensions>\d+x\d+)-(?<format>[a-z]+)$/, match = assetId.match(pattern);
|
|
4232
|
+
if (!match?.groups)
|
|
4233
|
+
throw new Error(
|
|
4234
|
+
`Invalid asset ID \`${assetId}\`. Expected: image-{assetName}-{width}x{height}-{format}`
|
|
4235
|
+
);
|
|
4236
|
+
const { assetName, dimensions, format } = match.groups;
|
|
4237
|
+
return `https://cdn.sanity.io/images/${projectId}/${dataset}/${assetName}-${dimensions}.${format}`;
|
|
4238
|
+
}
|
|
4239
|
+
function hasImageRef(value) {
|
|
4240
|
+
return lodashEs.isObject(value) && "_ref" in value && typeof value._ref == "string";
|
|
4241
|
+
}
|
|
4242
|
+
function normalizeMedia(media, projectId, dataset) {
|
|
4243
|
+
return !media || !hasImageRef(media) ? null : {
|
|
4244
|
+
type: "image-asset",
|
|
4245
|
+
_ref: media._ref,
|
|
4246
|
+
url: assetIdToUrl(media._ref, projectId, dataset)
|
|
4247
|
+
};
|
|
4248
|
+
}
|
|
4249
|
+
function findFirstDefined(fieldsToSearch, candidates, exclude) {
|
|
4250
|
+
if (candidates)
|
|
4251
|
+
for (const field of fieldsToSearch) {
|
|
4252
|
+
const value = candidates[field];
|
|
4253
|
+
if (typeof value == "string" && value.trim() !== "" && value !== exclude)
|
|
4254
|
+
return value;
|
|
4255
|
+
}
|
|
4256
|
+
}
|
|
4257
|
+
function processPreviewQuery({
|
|
4258
|
+
projectId,
|
|
4259
|
+
dataset,
|
|
4260
|
+
ids,
|
|
4261
|
+
results
|
|
4262
|
+
}) {
|
|
4263
|
+
const resultMap = results.reduce((acc, next) => (acc[next._id] = next, acc), {});
|
|
4264
|
+
return Object.fromEntries(
|
|
4265
|
+
Array.from(ids).map((id) => {
|
|
4266
|
+
const publishedId = getPublishedId(id), draftId = getDraftId(id), draftResult = resultMap[draftId], publishedResult = resultMap[publishedId];
|
|
4267
|
+
if (!draftResult && !publishedResult) return [id, STABLE_EMPTY_PREVIEW];
|
|
4268
|
+
try {
|
|
4269
|
+
const result = draftResult || publishedResult;
|
|
4270
|
+
if (!result) return [id, STABLE_EMPTY_PREVIEW];
|
|
4271
|
+
const title = findFirstDefined(TITLE_CANDIDATES, result.titleCandidates), subtitle = findFirstDefined(SUBTITLE_CANDIDATES, result.subtitleCandidates, title), preview = {
|
|
4272
|
+
title: String(title || `${result._type}: ${result._id}`),
|
|
4273
|
+
subtitle: subtitle || void 0,
|
|
4274
|
+
media: normalizeMedia(result.media, projectId, dataset)
|
|
4275
|
+
}, status = {
|
|
4276
|
+
...draftResult?._updatedAt && { lastEditedDraftAt: draftResult._updatedAt },
|
|
4277
|
+
...publishedResult?._updatedAt && { lastEditedPublishedAt: publishedResult._updatedAt }
|
|
4278
|
+
};
|
|
4279
|
+
return [id, { data: { ...preview, status }, isPending: !1 }];
|
|
4280
|
+
} catch (e3) {
|
|
4281
|
+
return console.warn(e3), [id, STABLE_ERROR_PREVIEW];
|
|
4282
|
+
}
|
|
4283
|
+
})
|
|
4284
|
+
);
|
|
4285
|
+
}
|
|
4286
|
+
function createPreviewQuery(documentIds) {
|
|
4287
|
+
const allIds = Array.from(documentIds).flatMap((id) => [getPublishedId(id), getDraftId(id)]), projection = getPreviewProjection(), queryHash = hashString(projection);
|
|
4288
|
+
return {
|
|
4289
|
+
query: `*[_id in $__ids_${queryHash}]${projection}`,
|
|
4290
|
+
params: {
|
|
4291
|
+
[`__ids_${queryHash}`]: allIds
|
|
4292
|
+
}
|
|
4293
|
+
};
|
|
4294
|
+
}
|
|
4295
|
+
const BATCH_DEBOUNCE_TIME$1 = 50, subscribeToStateAndFetchBatches$1 = createInternalAction(
|
|
4296
|
+
({ state, instance }) => function() {
|
|
4297
|
+
const client$ = getClientState(instance, { apiVersion: "vX" }).observable, documentTypes$ = state.observable.pipe(
|
|
4298
|
+
rxjs.map((i2) => i2.documentTypes),
|
|
4299
|
+
rxjs.distinctUntilChanged()
|
|
4300
|
+
), lastLiveEventId$ = state.observable.pipe(
|
|
4301
|
+
rxjs.map((i2) => i2.lastLiveEventId),
|
|
4302
|
+
rxjs.distinctUntilChanged()
|
|
4303
|
+
), newSubscriberIds$ = state.observable.pipe(
|
|
4304
|
+
rxjs.map(({ subscriptions }) => new Set(Object.keys(subscriptions))),
|
|
4305
|
+
rxjs.distinctUntilChanged(
|
|
4306
|
+
(a2, b2) => a2.size !== b2.size ? !1 : Array.from(a2).every((i2) => b2.has(i2))
|
|
4307
|
+
),
|
|
4308
|
+
rxjs.debounceTime(BATCH_DEBOUNCE_TIME$1),
|
|
4309
|
+
rxjs.startWith(/* @__PURE__ */ new Set()),
|
|
4310
|
+
rxjs.pairwise(),
|
|
4311
|
+
rxjs.tap(([prevIds, currIds]) => {
|
|
4312
|
+
const newIds = [...currIds].filter((element) => !prevIds.has(element));
|
|
4313
|
+
state.set("updatingPending", (prev) => {
|
|
4314
|
+
const pendingValues = newIds.reduce((acc, id) => {
|
|
4315
|
+
const prevValue = prev.values[id], value = prevValue?.data ? prevValue.data : null;
|
|
4316
|
+
return acc[id] = { data: value, isPending: !0 }, acc;
|
|
4317
|
+
}, {});
|
|
4318
|
+
return { values: { ...prev.values, ...pendingValues } };
|
|
4319
|
+
});
|
|
4320
|
+
}),
|
|
4321
|
+
rxjs.withLatestFrom(documentTypes$),
|
|
4322
|
+
rxjs.map(([[, ids], documentTypes]) => ({ ids, documentTypes }))
|
|
4323
|
+
);
|
|
4324
|
+
return rxjs.combineLatest([newSubscriberIds$, lastLiveEventId$, client$]).pipe(
|
|
4325
|
+
rxjs.switchMap(([{ ids }, lastLiveEventId, client2]) => {
|
|
4326
|
+
if (!ids.size) return rxjs.EMPTY;
|
|
4327
|
+
const { query, params } = createPreviewQuery(ids);
|
|
4328
|
+
return client2.observable.fetch(query, params, {
|
|
4329
|
+
filterResponse: !1,
|
|
4330
|
+
returnQuery: !1,
|
|
4331
|
+
perspective: "drafts",
|
|
4332
|
+
tag: PREVIEW_TAG,
|
|
4333
|
+
lastLiveEventId
|
|
4334
|
+
}).pipe(rxjs.map((response) => ({ ...response, ids })));
|
|
4335
|
+
}),
|
|
4336
|
+
rxjs.map(({ ids, result, syncTags }) => ({
|
|
4337
|
+
syncTags,
|
|
4338
|
+
values: processPreviewQuery({
|
|
4339
|
+
projectId: instance.identity.projectId,
|
|
4340
|
+
dataset: instance.identity.dataset,
|
|
4341
|
+
ids,
|
|
4342
|
+
results: result
|
|
4343
|
+
})
|
|
4344
|
+
}))
|
|
4345
|
+
).subscribe({
|
|
4346
|
+
next: ({ syncTags = [], values }) => {
|
|
4347
|
+
state.set("updateResult", (prev) => ({
|
|
4348
|
+
values: { ...prev.values, ...values },
|
|
4349
|
+
syncTags: syncTags.reduce((acc, next) => (acc[next] = !0, acc), {})
|
|
4350
|
+
}));
|
|
4351
|
+
}
|
|
4352
|
+
});
|
|
4353
|
+
}
|
|
4354
|
+
), previewStore = {
|
|
4355
|
+
name: "Preview",
|
|
4356
|
+
getInitialState() {
|
|
4357
|
+
return {
|
|
4358
|
+
documentTypes: {},
|
|
4359
|
+
lastLiveEventId: null,
|
|
4360
|
+
subscriptions: {},
|
|
4361
|
+
syncTags: {},
|
|
4362
|
+
values: {}
|
|
4363
|
+
};
|
|
4364
|
+
},
|
|
4365
|
+
initialize() {
|
|
4366
|
+
const subscribeToLiveAndSetLastLiveEventId = createLiveEventSubscriber(PREVIEW_TAG), stateSubscriptionForBatches = subscribeToStateAndFetchBatches$1(this), liveSubscription = subscribeToLiveAndSetLastLiveEventId(this);
|
|
4367
|
+
return () => {
|
|
4368
|
+
stateSubscriptionForBatches.unsubscribe(), liveSubscription.unsubscribe();
|
|
4369
|
+
};
|
|
4370
|
+
}
|
|
4371
|
+
}, _getPreviewState = createStateSourceAction(
|
|
4372
|
+
previewStore,
|
|
4373
|
+
(state, { document: document2 }) => state.values[document2._id] ?? STABLE_EMPTY_PREVIEW
|
|
4374
|
+
), getPreviewState = createAction(previewStore, ({ state }) => function({ document: document2 }) {
|
|
4375
|
+
const { _id, _type: documentType } = document2, documentId = getPublishedId(_id), previewState = _getPreviewState(this, { document: document2 });
|
|
4376
|
+
return {
|
|
4377
|
+
...previewState,
|
|
4378
|
+
subscribe: (subscriber) => {
|
|
4379
|
+
const subscriptionId = insecureRandomId();
|
|
4380
|
+
state.set("addSubscription", (prev) => ({
|
|
4381
|
+
documentTypes: {
|
|
4382
|
+
...prev.documentTypes,
|
|
4383
|
+
[documentId]: documentType
|
|
4384
|
+
},
|
|
4385
|
+
subscriptions: {
|
|
4386
|
+
...prev.subscriptions,
|
|
4387
|
+
[documentId]: {
|
|
4388
|
+
...prev.subscriptions[documentId],
|
|
4389
|
+
[subscriptionId]: !0
|
|
4390
|
+
}
|
|
4391
|
+
}
|
|
4392
|
+
}));
|
|
4393
|
+
const unsubscribe = previewState.subscribe(subscriber);
|
|
4394
|
+
return () => {
|
|
4395
|
+
unsubscribe(), state.set("removeSubscription", (prev) => {
|
|
4396
|
+
const documentSubscriptions = lodashEs.omit(prev.subscriptions[documentId], subscriptionId), hasSubscribers = !!Object.keys(documentSubscriptions).length, prevValue = prev.values[documentId], previewValue = prevValue?.data ? prevValue.data : null;
|
|
4397
|
+
return {
|
|
4398
|
+
subscriptions: hasSubscribers ? { ...prev.subscriptions, [documentId]: documentSubscriptions } : lodashEs.omit(prev.subscriptions, documentId),
|
|
4399
|
+
values: hasSubscribers ? prev.values : { ...prev.values, [documentId]: { data: previewValue, isPending: !1 } }
|
|
4400
|
+
};
|
|
4401
|
+
});
|
|
4402
|
+
};
|
|
4403
|
+
}
|
|
4404
|
+
};
|
|
4405
|
+
}), resolvePreview = createAction(previewStore, () => function({ document: document2 }) {
|
|
4406
|
+
const { getCurrent, subscribe } = getPreviewState(this, { document: document2 });
|
|
4407
|
+
return new Promise((resolve) => {
|
|
4408
|
+
const unsubscribe = subscribe(() => {
|
|
4409
|
+
const current = getCurrent();
|
|
4410
|
+
current?.data && (resolve(current), unsubscribe());
|
|
4411
|
+
});
|
|
4412
|
+
});
|
|
4413
|
+
}), project = createFetcherStore({
|
|
4414
|
+
name: "Project",
|
|
4415
|
+
getKey: (projectId) => projectId,
|
|
4416
|
+
fetcher: (instance) => (projectId) => getClientState(instance, { apiVersion: "vX", scope: "global" }).observable.pipe(
|
|
4417
|
+
rxjs.switchMap((client2) => client2.observable.projects.getById(projectId))
|
|
4418
|
+
)
|
|
4419
|
+
}), getProjectState = project.getState, resolveProject = project.resolveState, PROJECTION_TAG = "sdk.projection", STABLE_EMPTY_PROJECTION = {
|
|
4420
|
+
data: null,
|
|
4421
|
+
isPending: !1
|
|
4422
|
+
};
|
|
4423
|
+
function validateProjection(projection) {
|
|
4424
|
+
if (!projection.startsWith("{") || !projection.endsWith("}"))
|
|
4425
|
+
throw new Error(
|
|
4426
|
+
`Invalid projection format: "${projection}". Projections must be enclosed in curly braces, e.g. "{title, 'author': author.name}"`
|
|
4427
|
+
);
|
|
4428
|
+
return projection;
|
|
4429
|
+
}
|
|
4430
|
+
function createProjectionQuery(documentIds, documentProjections) {
|
|
4431
|
+
const projections = Array.from(documentIds).filter((id) => documentProjections[id]).map((id) => {
|
|
4432
|
+
const projection = validateProjection(documentProjections[id]), projectionHash = hashString(projection);
|
|
4433
|
+
return { documentId: id, projection, projectionHash };
|
|
4434
|
+
}).reduce((acc, { documentId, projection, projectionHash }) => {
|
|
4435
|
+
const obj = acc[projectionHash] ?? { documentIds: /* @__PURE__ */ new Set(), projection };
|
|
4436
|
+
return obj.documentIds.add(documentId), acc[projectionHash] = obj, acc;
|
|
4437
|
+
}, {}), query = `[${Object.entries(projections).map(([projectionHash, { projection }]) => `...*[_id in $__ids_${projectionHash}]{_id,_type,_updatedAt,"result":{...${projection}}}`).join(",")}]`, params = Object.fromEntries(
|
|
4438
|
+
Object.entries(projections).map(([projectionHash, value]) => {
|
|
4439
|
+
const idsInProjection = Array.from(value.documentIds).flatMap((id) => [
|
|
4440
|
+
getPublishedId(id),
|
|
4441
|
+
getDraftId(id)
|
|
4442
|
+
]);
|
|
4443
|
+
return [`__ids_${projectionHash}`, Array.from(idsInProjection)];
|
|
4444
|
+
})
|
|
4445
|
+
);
|
|
4446
|
+
return { query, params };
|
|
4447
|
+
}
|
|
4448
|
+
function processProjectionQuery({ ids, results }) {
|
|
4449
|
+
const resultMap = results.reduce(
|
|
4450
|
+
(acc, next) => (acc[next._id] = next, acc),
|
|
4451
|
+
{}
|
|
4452
|
+
);
|
|
4453
|
+
return Object.fromEntries(
|
|
4454
|
+
Array.from(ids).map((id) => {
|
|
4455
|
+
const publishedId = getPublishedId(id), draftId = getDraftId(id), draftResult = resultMap[draftId], publishedResult = resultMap[publishedId], projectionResult = draftResult?.result ?? publishedResult?.result;
|
|
4456
|
+
if (!projectionResult) return [id, { data: null, isPending: !1 }];
|
|
4457
|
+
const status = {
|
|
4458
|
+
...draftResult?._updatedAt && { lastEditedDraftAt: draftResult._updatedAt },
|
|
4459
|
+
...publishedResult?._updatedAt && { lastEditedPublishedAt: publishedResult._updatedAt }
|
|
4460
|
+
};
|
|
4461
|
+
return [id, { data: { ...projectionResult, status }, isPending: !1 }];
|
|
4462
|
+
})
|
|
4463
|
+
);
|
|
4464
|
+
}
|
|
4465
|
+
const BATCH_DEBOUNCE_TIME = 50, subscribeToStateAndFetchBatches = createInternalAction(
|
|
4466
|
+
({ state, instance }) => function() {
|
|
4467
|
+
const client$ = new rxjs.Observable(
|
|
4468
|
+
(observer) => getClientState(instance, { apiVersion: "vX" }).observable.subscribe(observer)
|
|
4469
|
+
), documentProjections$ = state.observable.pipe(
|
|
4470
|
+
rxjs.map((i2) => i2.documentProjections),
|
|
4471
|
+
rxjs.distinctUntilChanged()
|
|
4472
|
+
), lastLiveEventId$ = state.observable.pipe(
|
|
4473
|
+
rxjs.map((i2) => i2.lastLiveEventId),
|
|
4474
|
+
rxjs.distinctUntilChanged()
|
|
4475
|
+
), newSubscriberIds$ = state.observable.pipe(
|
|
4476
|
+
rxjs.map(({ subscriptions }) => new Set(Object.keys(subscriptions))),
|
|
4477
|
+
rxjs.distinctUntilChanged(
|
|
4478
|
+
(a2, b2) => a2.size !== b2.size ? !1 : Array.from(a2).every((i2) => b2.has(i2))
|
|
4479
|
+
),
|
|
4480
|
+
rxjs.debounceTime(BATCH_DEBOUNCE_TIME),
|
|
4481
|
+
rxjs.startWith(/* @__PURE__ */ new Set()),
|
|
4482
|
+
rxjs.pairwise(),
|
|
4483
|
+
rxjs.tap(([prevIds, currIds]) => {
|
|
4484
|
+
const newIds = [...currIds].filter((element) => !prevIds.has(element));
|
|
4485
|
+
state.set("updatingPending", (prev) => {
|
|
4486
|
+
const pendingValues = newIds.reduce((acc, id) => {
|
|
4487
|
+
const prevValue = prev.values[id], value = prevValue?.data ? prevValue.data : null;
|
|
4488
|
+
return acc[id] = { data: value, isPending: !0 }, acc;
|
|
4489
|
+
}, {});
|
|
4490
|
+
return { values: { ...prev.values, ...pendingValues } };
|
|
4491
|
+
});
|
|
4492
|
+
}),
|
|
4493
|
+
rxjs.withLatestFrom(documentProjections$),
|
|
4494
|
+
rxjs.map(([[, ids], documentProjections]) => ({ ids, documentProjections }))
|
|
4495
|
+
);
|
|
4496
|
+
return rxjs.combineLatest([newSubscriberIds$, lastLiveEventId$, client$]).pipe(
|
|
4497
|
+
rxjs.switchMap(([{ ids, documentProjections }, lastLiveEventId, client2]) => {
|
|
4498
|
+
if (!ids.size) return rxjs.EMPTY;
|
|
4499
|
+
const { query, params } = createProjectionQuery(ids, documentProjections);
|
|
4500
|
+
return client2.observable.fetch(query, params, {
|
|
4501
|
+
filterResponse: !1,
|
|
4502
|
+
returnQuery: !1,
|
|
4503
|
+
perspective: "drafts",
|
|
4504
|
+
tag: PROJECTION_TAG,
|
|
4505
|
+
lastLiveEventId
|
|
4506
|
+
}).pipe(rxjs.map((response) => ({ ...response, ids })));
|
|
4507
|
+
}),
|
|
4508
|
+
rxjs.map(({ ids, result, syncTags }) => ({
|
|
4509
|
+
syncTags,
|
|
4510
|
+
values: processProjectionQuery({
|
|
4511
|
+
ids,
|
|
4512
|
+
results: result
|
|
4513
|
+
})
|
|
4514
|
+
}))
|
|
4515
|
+
).subscribe({
|
|
4516
|
+
next: ({ syncTags = [], values }) => {
|
|
4517
|
+
state.set("updateResult", (prev) => ({
|
|
4518
|
+
values: { ...prev.values, ...values },
|
|
4519
|
+
syncTags: syncTags.reduce((acc, next) => (acc[next] = !0, acc), {})
|
|
4520
|
+
}));
|
|
4521
|
+
}
|
|
4522
|
+
});
|
|
4523
|
+
}
|
|
4524
|
+
), projectionStore = {
|
|
4525
|
+
name: "Projection",
|
|
4526
|
+
getInitialState() {
|
|
4527
|
+
return {
|
|
4528
|
+
values: {},
|
|
4529
|
+
documentProjections: {},
|
|
4530
|
+
subscriptions: {},
|
|
4531
|
+
syncTags: {},
|
|
4532
|
+
lastLiveEventId: null
|
|
4533
|
+
};
|
|
4534
|
+
},
|
|
4535
|
+
initialize() {
|
|
4536
|
+
const liveSubscription = createLiveEventSubscriber(PROJECTION_TAG)(this), batchSubscription = subscribeToStateAndFetchBatches(this);
|
|
4537
|
+
return () => {
|
|
4538
|
+
liveSubscription.unsubscribe(), batchSubscription.unsubscribe();
|
|
4539
|
+
};
|
|
4540
|
+
}
|
|
4541
|
+
}, getProjectStateSourceAction = createStateSourceAction(
|
|
4542
|
+
projectionStore,
|
|
4543
|
+
(state, { document: document2 }) => state.values[document2._id] ?? STABLE_EMPTY_PROJECTION
|
|
4544
|
+
);
|
|
4545
|
+
function getProjectionState(...args) {
|
|
4546
|
+
return _getProjectionState(...args);
|
|
4547
|
+
}
|
|
4548
|
+
const _getProjectionState = createAction(projectionStore, ({ state }) => function({
|
|
4549
|
+
document: document2,
|
|
4550
|
+
projection
|
|
4551
|
+
}) {
|
|
4552
|
+
const { _id } = document2, documentId = getPublishedId(_id), projectionState = getProjectStateSourceAction(this, { document: document2, projection });
|
|
4553
|
+
return {
|
|
4554
|
+
...projectionState,
|
|
4555
|
+
subscribe: (subscriber) => {
|
|
4556
|
+
const subscriptionId = insecureRandomId();
|
|
4557
|
+
state.set("addSubscription", (prev) => ({
|
|
4558
|
+
documentProjections: {
|
|
4559
|
+
...prev.documentProjections,
|
|
4560
|
+
[documentId]: validateProjection(projection)
|
|
4561
|
+
},
|
|
4562
|
+
subscriptions: {
|
|
4563
|
+
...prev.subscriptions,
|
|
4564
|
+
[documentId]: {
|
|
4565
|
+
...prev.subscriptions[documentId],
|
|
4566
|
+
[subscriptionId]: !0
|
|
4567
|
+
}
|
|
4568
|
+
}
|
|
4569
|
+
}));
|
|
4570
|
+
const unsubscribe = projectionState.subscribe(subscriber);
|
|
4571
|
+
return () => {
|
|
4572
|
+
unsubscribe(), state.set("removeSubscription", (prev) => {
|
|
4573
|
+
const documentSubscriptions = lodashEs.omit(prev.subscriptions[documentId], subscriptionId), hasSubscribers = !!Object.keys(documentSubscriptions).length, prevValue = prev.values[documentId], projectionValue = prevValue?.data ? prevValue.data : null;
|
|
4574
|
+
return {
|
|
4575
|
+
subscriptions: hasSubscribers ? { ...prev.subscriptions, [documentId]: documentSubscriptions } : lodashEs.omit(prev.subscriptions, documentId),
|
|
4576
|
+
values: hasSubscribers ? prev.values : { ...prev.values, [documentId]: { data: projectionValue, isPending: !1 } }
|
|
4577
|
+
};
|
|
4578
|
+
});
|
|
4579
|
+
};
|
|
4580
|
+
}
|
|
4581
|
+
};
|
|
4582
|
+
}), resolveProjection = createAction(projectionStore, () => function({ document: document2, projection }) {
|
|
4583
|
+
const { getCurrent, subscribe } = getProjectionState(this, { document: document2, projection });
|
|
4584
|
+
return new Promise((resolve) => {
|
|
4585
|
+
const unsubscribe = subscribe(() => {
|
|
4586
|
+
const current = getCurrent();
|
|
4587
|
+
current?.data && (resolve(current), unsubscribe());
|
|
4588
|
+
});
|
|
4589
|
+
});
|
|
4590
|
+
}), projects = createFetcherStore({
|
|
4591
|
+
name: "Projects",
|
|
4592
|
+
getKey: () => "projects",
|
|
4593
|
+
fetcher: (instance) => () => getClientState(instance, { apiVersion: "vX", scope: "global" }).observable.pipe(
|
|
4594
|
+
rxjs.switchMap((client2) => client2.observable.projects.list({ includeMembers: !1 }))
|
|
4595
|
+
)
|
|
4596
|
+
}), getProjectsState = projects.getState, resolveProjects = projects.resolveState, QUERY_STATE_CLEAR_DELAY = 1e3, setQueryError = (key, error) => (prev) => {
|
|
4597
|
+
const prevQuery = prev.queries[key];
|
|
4598
|
+
return prevQuery ? { ...prev, queries: { ...prev.queries, [key]: { ...prevQuery, error } } } : prev;
|
|
4599
|
+
}, setQueryData = (key, result, syncTags) => (prev) => {
|
|
4600
|
+
const prevQuery = prev.queries[key];
|
|
4601
|
+
return prevQuery ? {
|
|
4602
|
+
...prev,
|
|
4603
|
+
queries: { ...prev.queries, [key]: { ...prevQuery, result: result ?? null, syncTags } }
|
|
4604
|
+
} : prev;
|
|
4605
|
+
}, setLastLiveEventId = (key, lastLiveEventId) => (prev) => {
|
|
4606
|
+
const prevQuery = prev.queries[key];
|
|
4607
|
+
return prevQuery ? { ...prev, queries: { ...prev.queries, [key]: { ...prevQuery, lastLiveEventId } } } : prev;
|
|
4608
|
+
}, addSubscriber = (key, subscriptionId) => (prev) => {
|
|
4609
|
+
const prevQuery = prev.queries[key], subscribers = [...prevQuery?.subscribers ?? [], subscriptionId];
|
|
4610
|
+
return { ...prev, queries: { ...prev.queries, [key]: { ...prevQuery, subscribers } } };
|
|
4611
|
+
}, removeSubscriber = (key, subscriptionId) => (prev) => {
|
|
4612
|
+
const prevQuery = prev.queries[key];
|
|
4613
|
+
if (!prevQuery) return prev;
|
|
4614
|
+
const subscribers = prevQuery.subscribers.filter((id) => id !== subscriptionId);
|
|
4615
|
+
return subscribers.length ? { ...prev, queries: { ...prev.queries, [key]: { ...prevQuery, subscribers } } } : { ...prev, queries: lodashEs.omit(prev.queries, key) };
|
|
4616
|
+
}, cancelQuery = (key) => (prev) => {
|
|
4617
|
+
const prevQuery = prev.queries[key];
|
|
4618
|
+
return !prevQuery || prevQuery.subscribers.length ? prev : { ...prev, queries: lodashEs.omit(prev.queries, key) };
|
|
4619
|
+
}, initializeQuery = (key) => (prev) => prev.queries[key] ? prev : { ...prev, queries: { ...prev.queries, [key]: { subscribers: [] } } }, EMPTY_ARRAY = [], getQueryKey = (query, options = {}) => JSON.stringify({ query, options }), parseQueryKey = (key) => JSON.parse(key), queryStore = {
|
|
4620
|
+
name: "QueryStore",
|
|
4621
|
+
getInitialState: () => ({ queries: {} }),
|
|
4622
|
+
initialize() {
|
|
4623
|
+
const subscriptions = [
|
|
4624
|
+
listenForNewSubscribersAndFetch(this),
|
|
4625
|
+
listenToLiveClientAndSetLastLiveEventIds(this)
|
|
4626
|
+
];
|
|
4627
|
+
return () => {
|
|
4628
|
+
for (const subscription of subscriptions)
|
|
4629
|
+
subscription.unsubscribe();
|
|
4630
|
+
};
|
|
4631
|
+
}
|
|
4632
|
+
}, errorHandler = createInternalAction(({ state }) => function() {
|
|
4633
|
+
return (error) => state.set("setError", { error });
|
|
4634
|
+
}), listenForNewSubscribersAndFetch = createInternalAction(
|
|
4635
|
+
({ state, instance }) => function() {
|
|
4636
|
+
return state.observable.pipe(
|
|
4637
|
+
rxjs.map((s2) => new Set(Object.keys(s2.queries))),
|
|
4638
|
+
rxjs.distinctUntilChanged((curr, next) => curr.size !== next.size ? !1 : Array.from(next).every((i2) => curr.has(i2))),
|
|
4639
|
+
rxjs.startWith(/* @__PURE__ */ new Set()),
|
|
4640
|
+
rxjs.pairwise(),
|
|
4641
|
+
rxjs.mergeMap(([curr, next]) => {
|
|
4642
|
+
const added = Array.from(next).filter((i2) => !curr.has(i2)), removed = Array.from(curr).filter((i2) => !next.has(i2));
|
|
4643
|
+
return [
|
|
4644
|
+
...added.map((key) => ({ key, added: !0 })),
|
|
4645
|
+
...removed.map((key) => ({ key, added: !1 }))
|
|
4646
|
+
];
|
|
4647
|
+
}),
|
|
4648
|
+
rxjs.groupBy((i2) => i2.key),
|
|
4649
|
+
rxjs.mergeMap(
|
|
4650
|
+
(group$) => group$.pipe(
|
|
4651
|
+
rxjs.switchMap((e3) => {
|
|
4652
|
+
if (!e3.added) return rxjs.EMPTY;
|
|
4653
|
+
const lastLiveEventId$ = state.observable.pipe(
|
|
4654
|
+
rxjs.map((s2) => s2.queries[group$.key]?.lastLiveEventId),
|
|
4655
|
+
rxjs.distinctUntilChanged()
|
|
4656
|
+
), { query, options: { params, scope, ...options } = {} } = parseQueryKey(group$.key), client$ = getClientState(instance, { apiVersion: "vX", scope }).observable;
|
|
4657
|
+
return rxjs.combineLatest([lastLiveEventId$, client$]).pipe(
|
|
4658
|
+
rxjs.switchMap(
|
|
4659
|
+
([lastLiveEventId, client2]) => client2.observable.fetch(query, params, {
|
|
4660
|
+
...options,
|
|
4661
|
+
filterResponse: !1,
|
|
4662
|
+
returnQuery: !1,
|
|
4663
|
+
lastLiveEventId
|
|
4664
|
+
})
|
|
4665
|
+
)
|
|
4666
|
+
);
|
|
4667
|
+
}),
|
|
4668
|
+
rxjs.catchError((error) => (state.set("setQueryError", setQueryError(group$.key, error)), rxjs.EMPTY)),
|
|
4669
|
+
rxjs.tap(({ result, syncTags }) => {
|
|
4670
|
+
state.set("setQueryData", setQueryData(group$.key, result, syncTags));
|
|
4671
|
+
})
|
|
4672
|
+
)
|
|
4673
|
+
)
|
|
4674
|
+
).subscribe({ error: errorHandler(this) });
|
|
4675
|
+
}
|
|
4676
|
+
), listenToLiveClientAndSetLastLiveEventIds = createInternalAction(
|
|
4677
|
+
({ state, instance }) => function() {
|
|
4678
|
+
const liveMessages$ = getClientState(instance, { apiVersion: "vX" }).observable.pipe(
|
|
4679
|
+
rxjs.switchMap(
|
|
4680
|
+
(client2) => client2.live.events({ includeDrafts: !!client2.config().token, tag: "query-store" })
|
|
4681
|
+
),
|
|
4682
|
+
rxjs.share(),
|
|
4683
|
+
rxjs.filter((e3) => e3.type === "message")
|
|
4684
|
+
);
|
|
4685
|
+
return state.observable.pipe(
|
|
4686
|
+
rxjs.mergeMap((s2) => Object.entries(s2.queries)),
|
|
4687
|
+
rxjs.groupBy(([key]) => key),
|
|
4688
|
+
rxjs.mergeMap((group$) => {
|
|
4689
|
+
const syncTags$ = group$.pipe(
|
|
4690
|
+
rxjs.map(([, queryState]) => queryState),
|
|
4691
|
+
rxjs.map((i2) => i2?.syncTags ?? EMPTY_ARRAY),
|
|
4692
|
+
rxjs.distinctUntilChanged()
|
|
4693
|
+
);
|
|
4694
|
+
return rxjs.combineLatest([liveMessages$, syncTags$]).pipe(
|
|
4695
|
+
rxjs.filter(([message, syncTags]) => message.tags.some((tag) => syncTags.includes(tag))),
|
|
4696
|
+
rxjs.tap(([message]) => {
|
|
4697
|
+
state.set("setLastLiveEventId", setLastLiveEventId(group$.key, message.id));
|
|
4698
|
+
})
|
|
4699
|
+
);
|
|
4700
|
+
})
|
|
4701
|
+
).subscribe({ error: errorHandler(this) });
|
|
4702
|
+
}
|
|
4703
|
+
);
|
|
4704
|
+
function getQueryState(...args) {
|
|
4705
|
+
return _getQueryState(...args);
|
|
4706
|
+
}
|
|
4707
|
+
const _getQueryState = createStateSourceAction(queryStore, {
|
|
4708
|
+
selector: (state, query, options) => {
|
|
4709
|
+
if (state.error) throw state.error;
|
|
4710
|
+
const key = getQueryKey(query, options), queryState = state.queries[key];
|
|
4711
|
+
if (queryState?.error) throw queryState.error;
|
|
4712
|
+
return queryState?.result;
|
|
4713
|
+
},
|
|
4714
|
+
onSubscribe: ({ state }, query, options) => {
|
|
4715
|
+
const subscriptionId = insecureRandomId(), key = getQueryKey(query, options);
|
|
4716
|
+
return state.set("addSubscriber", addSubscriber(key, subscriptionId)), () => {
|
|
4717
|
+
setTimeout(
|
|
4718
|
+
() => state.set("removeSubscriber", removeSubscriber(key, subscriptionId)),
|
|
4719
|
+
QUERY_STATE_CLEAR_DELAY
|
|
4720
|
+
);
|
|
4721
|
+
};
|
|
4722
|
+
}
|
|
4723
|
+
});
|
|
4724
|
+
function resolveQuery(...args) {
|
|
4725
|
+
return _resolveQuery(...args);
|
|
4726
|
+
}
|
|
4727
|
+
const _resolveQuery = createAction(queryStore, ({ state }) => function(query, { signal, ...options } = {}) {
|
|
4728
|
+
const { getCurrent } = getQueryState(this, query, options), key = getQueryKey(query, options), aborted$ = signal ? new rxjs.Observable((observer) => {
|
|
4729
|
+
const cleanup = () => {
|
|
4730
|
+
signal.removeEventListener("abort", listener);
|
|
4731
|
+
}, listener = () => {
|
|
4732
|
+
observer.error(new DOMException("The operation was aborted.", "AbortError")), observer.complete(), cleanup();
|
|
4733
|
+
};
|
|
4734
|
+
return signal.addEventListener("abort", listener), cleanup;
|
|
4735
|
+
}).pipe(
|
|
4736
|
+
rxjs.catchError((error) => {
|
|
4737
|
+
throw error instanceof Error && error.name === "AbortError" && state.set("cancelQuery", cancelQuery(key)), error;
|
|
4738
|
+
})
|
|
4739
|
+
) : rxjs.NEVER;
|
|
4740
|
+
state.set("initializeQuery", initializeQuery(key));
|
|
4741
|
+
const resolved$ = state.observable.pipe(
|
|
4742
|
+
rxjs.map(getCurrent),
|
|
4743
|
+
rxjs.first((i2) => i2 !== void 0)
|
|
4744
|
+
);
|
|
4745
|
+
return rxjs.firstValueFrom(rxjs.race([resolved$, aborted$]));
|
|
4746
|
+
});
|
|
4747
|
+
function createStore(resource, actions) {
|
|
4748
|
+
return function(dependencies) {
|
|
4749
|
+
const instance = "instance" in dependencies ? dependencies.instance : dependencies, { state, dispose } = "state" in dependencies ? { state: dependencies.state, dispose: lodashEs.noop } : initializeResource(instance, resource), boundActions = Object.entries(actions).reduce((acc, [key, action]) => (acc[key] = action.bind(null, { state, instance }), acc), {});
|
|
4750
|
+
return { dispose, ...boundActions };
|
|
4751
|
+
};
|
|
4752
|
+
}
|
|
4753
|
+
const API_VERSION = "vX", usersStore = {
|
|
4754
|
+
name: "users",
|
|
4755
|
+
getInitialState: () => ({
|
|
4756
|
+
users: [],
|
|
4757
|
+
totalCount: 0,
|
|
4758
|
+
nextCursor: null,
|
|
4759
|
+
hasMore: !1,
|
|
4760
|
+
initialFetchCompleted: !1,
|
|
4761
|
+
options: {
|
|
4762
|
+
resourceType: "",
|
|
4763
|
+
resourceId: "",
|
|
4764
|
+
limit: 100
|
|
4765
|
+
}
|
|
4766
|
+
}),
|
|
4767
|
+
initialize() {
|
|
4768
|
+
return () => {
|
|
4769
|
+
};
|
|
4770
|
+
}
|
|
4771
|
+
}, getState = createStateSourceAction(
|
|
4772
|
+
usersStore,
|
|
4773
|
+
reselect.createSelector(
|
|
4774
|
+
[
|
|
4775
|
+
(state) => state.users,
|
|
4776
|
+
(state) => state.totalCount,
|
|
4777
|
+
(state) => state.nextCursor,
|
|
4778
|
+
(state) => state.hasMore,
|
|
4779
|
+
(state) => state.initialFetchCompleted,
|
|
4780
|
+
(state) => state.options
|
|
4781
|
+
],
|
|
4782
|
+
(users, totalCount, nextCursor, hasMore, initialFetchCompleted, options) => ({
|
|
4783
|
+
users,
|
|
4784
|
+
totalCount,
|
|
4785
|
+
nextCursor,
|
|
4786
|
+
hasMore,
|
|
4787
|
+
options,
|
|
4788
|
+
initialFetchCompleted
|
|
4789
|
+
})
|
|
4790
|
+
)
|
|
4791
|
+
), fetchUsers = (instance, params) => {
|
|
4792
|
+
const { resourceType, resourceId, nextCursor, limit = 100 } = params;
|
|
4793
|
+
return getClient(instance, { scope: "global", apiVersion: API_VERSION }).request({
|
|
4794
|
+
method: "GET",
|
|
4795
|
+
uri: `access/${resourceType}/${resourceId}/users`,
|
|
4796
|
+
query: nextCursor ? { nextCursor, limit: limit.toString() } : { limit: limit.toString() },
|
|
4797
|
+
tag: "users"
|
|
4798
|
+
});
|
|
4799
|
+
}, loadMore = createAction(usersStore, ({ state, instance }) => async function() {
|
|
4800
|
+
const { users, nextCursor, options } = state.get(), { resourceType, resourceId, limit } = options;
|
|
4801
|
+
if (!resourceType || !resourceId)
|
|
4802
|
+
throw new Error("Resource type and ID are required to load more users");
|
|
4803
|
+
const response = await fetchUsers(instance, { resourceType, resourceId, nextCursor, limit }), allUsers = [...users, ...response.data], hasMore = allUsers.length < response.totalCount;
|
|
4804
|
+
state.set("loadMore", {
|
|
4805
|
+
users: allUsers,
|
|
4806
|
+
totalCount: response.totalCount,
|
|
4807
|
+
nextCursor: response.nextCursor,
|
|
4808
|
+
hasMore
|
|
4809
|
+
});
|
|
4810
|
+
}), resolveUsers = createAction(usersStore, ({ state, instance }) => async function() {
|
|
4811
|
+
const { options } = state.get(), { resourceType, resourceId, limit } = options;
|
|
4812
|
+
if (!resourceType || !resourceId)
|
|
4813
|
+
throw new Error("Resource type and ID are required to resolve users");
|
|
4814
|
+
const response = await fetchUsers(instance, { resourceType, resourceId, limit }), hasMore = response.data.length < response.totalCount;
|
|
4815
|
+
return state.set("resolveUsers", {
|
|
4816
|
+
users: response.data,
|
|
4817
|
+
totalCount: response.totalCount,
|
|
4818
|
+
nextCursor: response.nextCursor,
|
|
4819
|
+
hasMore,
|
|
4820
|
+
initialFetchCompleted: !0
|
|
4821
|
+
}), response;
|
|
4822
|
+
}), setOptions = createAction(usersStore, ({ state }) => function(options) {
|
|
4823
|
+
state.set("options", {
|
|
4824
|
+
...state.get(),
|
|
4825
|
+
options: {
|
|
4826
|
+
...state.get().options,
|
|
4827
|
+
resourceType: options.resourceType,
|
|
4828
|
+
resourceId: options.resourceId
|
|
4829
|
+
}
|
|
4830
|
+
});
|
|
4831
|
+
}), createUsersStore = createStore(usersStore, {
|
|
4832
|
+
getState,
|
|
4833
|
+
loadMore,
|
|
4834
|
+
resolveUsers,
|
|
4835
|
+
setOptions
|
|
4836
|
+
});
|
|
4837
|
+
var version = "0.0.0-chore-react-18-compat.1";
|
|
4838
|
+
const CORE_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`;
|
|
4839
|
+
exports.AuthStateType = AuthStateType;
|
|
4840
|
+
exports.CORE_SDK_VERSION = CORE_SDK_VERSION;
|
|
4841
|
+
exports.applyDocumentActions = applyDocumentActions;
|
|
4842
|
+
exports.createDocument = createDocument;
|
|
4843
|
+
exports.createSanityInstance = createSanityInstance;
|
|
4844
|
+
exports.createUsersStore = createUsersStore;
|
|
4845
|
+
exports.deleteDocument = deleteDocument;
|
|
4846
|
+
exports.destroyController = destroyController;
|
|
4847
|
+
exports.discardDocument = discardDocument;
|
|
4848
|
+
exports.editDocument = editDocument;
|
|
4849
|
+
exports.fetchLoginUrls = fetchLoginUrls;
|
|
4850
|
+
exports.getAuthState = getAuthState;
|
|
4851
|
+
exports.getClient = getClient;
|
|
4852
|
+
exports.getClientState = getClientState;
|
|
4853
|
+
exports.getCurrentUserState = getCurrentUserState;
|
|
4854
|
+
exports.getDashboardOrganizationId = getDashboardOrganizationId;
|
|
4855
|
+
exports.getDatasetsState = getDatasetsState;
|
|
4856
|
+
exports.getDocumentState = getDocumentState;
|
|
4857
|
+
exports.getDocumentSyncStatus = getDocumentSyncStatus;
|
|
4858
|
+
exports.getLoginUrlsState = getLoginUrlsState;
|
|
4859
|
+
exports.getOrCreateChannel = getOrCreateChannel;
|
|
4860
|
+
exports.getOrCreateController = getOrCreateController;
|
|
4861
|
+
exports.getOrCreateNode = getOrCreateNode;
|
|
4862
|
+
exports.getPermissionsState = getPermissionsState;
|
|
4863
|
+
exports.getPreviewState = getPreviewState;
|
|
4864
|
+
exports.getProjectState = getProjectState;
|
|
4865
|
+
exports.getProjectionState = getProjectionState;
|
|
4866
|
+
exports.getProjectsState = getProjectsState;
|
|
4867
|
+
exports.getQueryKey = getQueryKey;
|
|
4868
|
+
exports.getQueryState = getQueryState;
|
|
4869
|
+
exports.getResourceId = getResourceId;
|
|
4870
|
+
exports.getTokenState = getTokenState;
|
|
4871
|
+
exports.handleAuthCallback = handleAuthCallback;
|
|
4872
|
+
exports.jsonMatch = jsonMatch;
|
|
4873
|
+
exports.logout = logout;
|
|
4874
|
+
exports.parseQueryKey = parseQueryKey;
|
|
4875
|
+
exports.publishDocument = publishDocument;
|
|
4876
|
+
exports.releaseChannel = releaseChannel;
|
|
4877
|
+
exports.releaseNode = releaseNode;
|
|
4878
|
+
exports.resolveDatasets = resolveDatasets;
|
|
4879
|
+
exports.resolveDocument = resolveDocument;
|
|
4880
|
+
exports.resolvePermissions = resolvePermissions;
|
|
4881
|
+
exports.resolvePreview = resolvePreview;
|
|
4882
|
+
exports.resolveProject = resolveProject;
|
|
4883
|
+
exports.resolveProjection = resolveProjection;
|
|
4884
|
+
exports.resolveProjects = resolveProjects;
|
|
4885
|
+
exports.resolveQuery = resolveQuery;
|
|
4886
|
+
exports.subscribeDocumentEvents = subscribeDocumentEvents;
|
|
4887
|
+
exports.unpublishDocument = unpublishDocument;
|
|
4888
|
+
//# sourceMappingURL=index.cjs.map
|