🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@sanity/mutate

Package Overview
Dependencies
Maintainers
114
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sanity/mutate - npm Package Compare versions

Comparing version
0.15.0
to
0.15.1-canary.0
+556
dist/_chunks-cjs/createOptimisticStore.cjs
"use strict";
var rxjs = require("rxjs"), encode = require("./encode.cjs"), nanoid = require("nanoid"), utils = require("./utils.cjs"), mendoza = require("mendoza"), uuid = require("@sanity/uuid"), diffMatchPatch = require("@sanity/diff-match-patch"), getAtPath = require("./getAtPath.cjs"), stringify = require("./stringify.cjs"), groupBy = require("lodash/groupBy.js");
function _interopDefaultCompat(e) {
return e && typeof e == "object" && "default" in e ? e : { default: e };
}
var groupBy__default = /* @__PURE__ */ _interopDefaultCompat(groupBy);
function getMutationDocumentId(mutation) {
if (mutation.type === "patch")
return mutation.id;
if (mutation.type === "create")
return mutation.document._id;
if (mutation.type === "delete")
return mutation.id;
if (mutation.type === "createIfNotExists" || mutation.type === "createOrReplace")
return mutation.document._id;
throw new Error("Invalid mutation type");
}
function applyAll(current, mutation) {
return mutation.reduce((doc, m) => {
const res = applyDocumentMutation(doc, m);
if (res.status === "error")
throw new Error(res.message);
return res.status === "noop" ? doc : res.after;
}, current);
}
function applyDocumentMutation(document, mutation) {
if (mutation.type === "create")
return create(document, mutation);
if (mutation.type === "createIfNotExists")
return createIfNotExists(document, mutation);
if (mutation.type === "delete")
return del(document, mutation);
if (mutation.type === "createOrReplace")
return createOrReplace(document, mutation);
if (mutation.type === "patch")
return patch(document, mutation);
throw new Error(`Invalid mutation type: ${mutation.type}`);
}
function create(document, mutation) {
if (document)
return { status: "error", message: "Document already exist" };
const result = utils.assignId(mutation.document, nanoid.nanoid);
return { status: "created", id: result._id, after: result };
}
function createIfNotExists(document, mutation) {
return utils.hasId(mutation.document) ? document ? { status: "noop" } : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function createOrReplace(document, mutation) {
return utils.hasId(mutation.document) ? document ? {
status: "updated",
id: mutation.document._id,
before: document,
after: mutation.document
} : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function del(document, mutation) {
return document ? mutation.id !== document._id ? { status: "error", message: "Delete mutation targeted wrong document" } : {
status: "deleted",
id: mutation.id,
before: document,
after: void 0
} : { status: "noop" };
}
function patch(document, mutation) {
if (!document)
return {
status: "error",
message: "Cannot apply patch on nonexistent document"
};
const next = utils.applyPatchMutation(mutation, document);
return document === next ? { status: "noop" } : { status: "updated", id: mutation.id, before: document, after: next };
}
function applyMutations(mutations, documentMap, transactionId) {
const updatedDocs = /* @__PURE__ */ Object.create(null);
for (const mutation of mutations) {
const documentId = getMutationDocumentId(mutation);
if (!documentId)
throw new Error("Unable to get document id from mutation");
const before = updatedDocs[documentId]?.after || documentMap.get(documentId), res = applyDocumentMutation(before, mutation);
if (res.status === "error")
throw new Error(res.message);
let entry = updatedDocs[documentId];
entry || (entry = { before, after: before, mutations: [] }, updatedDocs[documentId] = entry);
const after = transactionId ? { ...res.status === "noop" ? before : res.after, _rev: transactionId } : res.status === "noop" ? before : res.after;
documentMap.set(documentId, after), entry.after = after, entry.mutations.push(mutation);
}
return Object.entries(updatedDocs).map(
([id, { before, after, mutations: muts }]) => ({
id,
status: after ? before ? "updated" : "created" : "deleted",
mutations: muts,
before,
after
})
);
}
function commit(results, documentMap) {
results.forEach((result) => {
(result.status === "created" || result.status === "updated") && documentMap.set(result.id, result.after), result.status === "deleted" && documentMap.delete(result.id);
});
}
function takeUntilRight(arr, predicate, opts) {
const result = [];
for (const item of arr.slice().reverse()) {
if (predicate(item))
return result;
result.push(item);
}
return result.reverse();
}
function isEqualPath(p1, p2) {
return stringify.stringify(p1) === stringify.stringify(p2);
}
function supersedes(later, earlier) {
return (earlier.type === "set" || earlier.type === "unset") && (later.type === "set" || later.type === "unset");
}
function squashNodePatches(patches) {
return compactSetIfMissingPatches(
compactSetPatches(compactUnsetPatches(patches))
);
}
function compactUnsetPatches(patches) {
return patches.reduce(
(earlierPatches, laterPatch) => {
if (laterPatch.op.type !== "unset")
return earlierPatches.push(laterPatch), earlierPatches;
const unaffected = earlierPatches.filter(
(earlierPatch) => !stringify.startsWith(laterPatch.path, earlierPatch.path)
);
return unaffected.push(laterPatch), unaffected;
},
[]
);
}
function compactSetPatches(patches) {
return patches.reduceRight(
(laterPatches, earlierPatch) => (laterPatches.find(
(later) => supersedes(later.op, earlierPatch.op) && isEqualPath(later.path, earlierPatch.path)
) || laterPatches.unshift(earlierPatch), laterPatches),
[]
);
}
function compactSetIfMissingPatches(patches) {
return patches.reduce(
(previousPatches, laterPatch) => laterPatch.op.type !== "setIfMissing" ? (previousPatches.push(laterPatch), previousPatches) : (takeUntilRight(
previousPatches,
(patch2) => patch2.op.type === "unset"
).find(
(precedingPatch) => precedingPatch.op.type === "setIfMissing" && isEqualPath(precedingPatch.path, laterPatch.path)
) || previousPatches.push(laterPatch), previousPatches),
[]
);
}
function compactDMPSetPatches(base, patches) {
let edge = base;
return patches.reduce(
(earlierPatches, laterPatch) => {
const before = edge;
if (edge = utils.applyNodePatch(laterPatch, edge), laterPatch.op.type === "set" && typeof laterPatch.op.value == "string") {
const current = getAtPath.getAtPath(laterPatch.path, before);
if (typeof current == "string") {
const replaced = {
...laterPatch,
op: {
type: "diffMatchPatch",
value: diffMatchPatch.stringifyPatches(
diffMatchPatch.makePatches(current, laterPatch.op.value)
)
}
};
return earlierPatches.flatMap((ep) => isEqualPath(ep.path, laterPatch.path) && ep.op.type === "diffMatchPatch" ? [] : ep).concat(replaced);
}
}
return earlierPatches.push(laterPatch), earlierPatches;
},
[]
);
}
function squashDMPStrings(base, mutationGroups) {
return mutationGroups.map((mutationGroup) => ({
...mutationGroup,
mutations: dmpIfyMutations(base, mutationGroup.mutations)
}));
}
function dmpIfyMutations(store, mutations) {
return mutations.map((mutation, i) => {
if (mutation.type !== "patch")
return mutation;
const base = store.get(mutation.id);
return base ? dmpifyPatchMutation(base, mutation) : mutation;
});
}
function dmpifyPatchMutation(base, mutation) {
return {
...mutation,
patches: compactDMPSetPatches(base, mutation.patches)
};
}
function rebase(documentId, oldBase, newBase, localMutations) {
let edge = oldBase;
const dmpified = localMutations.map((transaction) => {
const mutations = transaction.mutations.flatMap((mut) => {
if (getMutationDocumentId(mut) !== documentId)
return [];
const before = edge;
return edge = applyAll(edge, [mut]), !before || mut.type !== "patch" ? mut : {
type: "dmpified",
mutation: {
...mut,
// Todo: make compactDMPSetPatches return pairs of patches that was dmpified with their
// original as dmpPatches and original is not 1:1 (e..g some of the original may not be dmpified)
dmpPatches: compactDMPSetPatches(before, mut.patches),
original: mut.patches
}
};
});
return { ...transaction, mutations };
});
let newBaseWithDMPForOldBaseApplied = newBase;
return dmpified.map((transaction) => {
const applied = [];
return transaction.mutations.forEach((mut) => {
if (mut.type === "dmpified")
try {
newBaseWithDMPForOldBaseApplied = utils.applyPatches(
mut.mutation.dmpPatches,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch {
console.warn("Failed to apply dmp patch, falling back to original");
try {
newBaseWithDMPForOldBaseApplied = utils.applyPatches(
mut.mutation.original,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch (second) {
throw new Error(
`Failed to apply patch for document "${documentId}": ${second.message}`
);
}
}
else
newBaseWithDMPForOldBaseApplied = applyAll(
newBaseWithDMPForOldBaseApplied,
[mut]
);
});
}), [localMutations.map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mut) => mut.type !== "patch" || getMutationDocumentId(mut) !== documentId ? mut : {
...mut,
patches: mut.patches.map((patch2) => patch2.op.type !== "set" ? patch2 : {
...patch2,
op: {
...patch2.op,
value: getAtPath.getAtPath(patch2.path, newBaseWithDMPForOldBaseApplied)
}
})
})
})), newBaseWithDMPForOldBaseApplied];
}
function mergeMutationGroups(mutationGroups) {
return chunkWhile(mutationGroups, (group) => !group.transaction).flatMap(
(chunk) => ({
...chunk[0],
mutations: chunk.flatMap((c) => c.mutations)
})
);
}
function chunkWhile(arr, predicate) {
const res = [];
let currentChunk = [];
return arr.forEach((item) => {
predicate(item) ? currentChunk.push(item) : (currentChunk.length > 0 && res.push(currentChunk), currentChunk = [], res.push([item]));
}), currentChunk.length > 0 && res.push(currentChunk), res;
}
function squashMutationGroups(staged) {
return mergeMutationGroups(staged).map((transaction) => ({
...transaction,
mutations: squashMutations(transaction.mutations)
})).map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mutation) => mutation.type !== "patch" ? mutation : {
...mutation,
patches: squashNodePatches(mutation.patches)
})
}));
}
function squashMutations(mutations) {
const byDocument = groupBy__default.default(mutations, getMutationDocumentId);
return Object.values(byDocument).flatMap((documentMutations) => squashCreateIfNotExists(squashDelete(documentMutations)).flat().reduce((acc, docMutation) => {
const prev = acc[acc.length - 1];
return (!prev || prev.type === "patch") && docMutation.type === "patch" ? acc.slice(0, -1).concat({
...docMutation,
patches: (prev?.patches || []).concat(docMutation.patches)
}) : acc.concat(docMutation);
}, []));
}
function squashCreateIfNotExists(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type !== "createIfNotExists" ? (previousMuts.push(laterMut), previousMuts) : (takeUntilRight(previousMuts, (m) => m.type === "delete").find(
(precedingPatch) => precedingPatch.type === "createIfNotExists"
) || previousMuts.push(laterMut), previousMuts), []);
}
function squashDelete(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type === "delete" ? [laterMut] : (previousMuts.push(laterMut), previousMuts), []);
}
function omitRev(document) {
if (document === void 0)
return;
const { _rev, ...doc } = document;
return doc;
}
function applyMendozaPatch(document, patch2, patchBaseRev) {
if (patchBaseRev !== document?._rev)
throw new Error(
"Invalid document revision. The provided patch is calculated from a different revision than the current document"
);
const next = mendoza.applyPatch(omitRev(document), patch2);
return next === null ? void 0 : next;
}
function applyMutationEventEffects(document, event) {
if (!event.effects)
throw new Error(
"Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?"
);
const next = applyMendozaPatch(
document,
event.effects.apply,
event.previousRev
);
return next ? { ...next, _rev: event.resultRev } : void 0;
}
function createDocumentMap() {
const documents = /* @__PURE__ */ new Map();
return {
set: (id, doc) => void documents.set(id, doc),
get: (id) => documents.get(id),
delete: (id) => documents.delete(id)
};
}
function createReplayMemoizer(expiry) {
const memo = /* @__PURE__ */ Object.create(null);
return function(key, observable) {
return key in memo || (memo[key] = observable.pipe(
rxjs.finalize(() => {
delete memo[key];
}),
rxjs.share({
connector: () => new rxjs.ReplaySubject(1),
resetOnRefCountZero: () => rxjs.timer(expiry)
})
)), memo[key];
};
}
function createTransactionId() {
return uuid.uuid();
}
function filterMutationGroupsById(mutationGroups, id) {
return mutationGroups.flatMap(
(mutationGroup) => mutationGroup.mutations.flatMap(
(mut) => getMutationDocumentId(mut) === id ? [mut] : []
)
);
}
function hasProperty(value, property) {
const val = value[property];
return typeof val < "u" && val !== null;
}
let didEmitMutationsAccessWarning = !1;
function warnNoMutationsReceived() {
didEmitMutationsAccessWarning || (console.warn(
new Error(
"No mutation received from backend. The listener is likely set up with `excludeMutations: true`. If your app need to know about mutations, make sure the listener is set up to include mutations"
)
), didEmitMutationsAccessWarning = !0);
}
const EMPTY_ARRAY = [];
function createOptimisticStore(backend) {
const local = createDocumentMap(), remote = createDocumentMap(), memoize = createReplayMemoizer(1e3);
let stagedChanges = [];
const remoteEvents$ = new rxjs.Subject(), localMutations$ = new rxjs.Subject(), stage$ = new rxjs.Subject();
function setStaged(nextPending) {
stagedChanges = nextPending, stage$.next();
}
function getLocalEvents(id) {
return localMutations$.pipe(rxjs.filter((event) => event.id === id));
}
function getRemoteEvents(id) {
return backend.listen(id).pipe(
rxjs.filter(
(event) => event.type !== "reconnect"
),
rxjs.mergeMap((event) => {
const oldLocal = local.get(id), oldRemote = remote.get(id);
if (event.type === "sync") {
const newRemote = event.document, [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
return rxjs.of({
type: "sync",
id,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
rebasedStage
});
} else if (event.type === "mutation") {
if (event.transactionId === oldRemote?._rev)
return rxjs.EMPTY;
let newRemote;
if (hasProperty(event, "effects"))
newRemote = applyMutationEventEffects(oldRemote, event);
else if (hasProperty(event, "mutations"))
newRemote = applyAll(oldRemote, encode.decodeAll(event.mutations));
else
throw new Error(
"Neither effects or mutations found on listener event"
);
const [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
newLocal && (newLocal._rev = event.transactionId);
const emittedEvent = {
type: "mutation",
id,
rebasedStage,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
effects: event.effects,
previousRev: event.previousRev,
resultRev: event.resultRev,
// overwritten below
mutations: EMPTY_ARRAY
};
return event.mutations ? emittedEvent.mutations = encode.decodeAll(
event.mutations
) : Object.defineProperty(
emittedEvent,
"mutations",
warnNoMutationsReceived
), rxjs.of(emittedEvent);
} else
throw new Error(`Unknown event type: ${event.type}`);
}),
rxjs.tap((event) => {
local.set(event.id, event.after.local), remote.set(event.id, event.after.remote), setStaged(event.rebasedStage);
}),
rxjs.tap({
next: (event) => remoteEvents$.next(event),
error: (err) => {
}
})
);
}
function listenEvents(id) {
return rxjs.defer(
() => memoize(id, rxjs.merge(getLocalEvents(id), getRemoteEvents(id)))
);
}
return {
meta: {
events: rxjs.merge(localMutations$, remoteEvents$),
stage: stage$.pipe(
rxjs.map(
() => (
// note: this should not be tampered with by consumers. We might want to do a deep-freeze during dev to avoid accidental mutations
stagedChanges
)
)
),
conflicts: rxjs.EMPTY
// does nothing for now
},
mutate: (mutations) => {
stagedChanges.push({ transaction: !1, mutations });
const results = applyMutations(mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
before: result.before,
after: result.after,
mutations: result.mutations,
id: result.id,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
transaction: (mutationsOrTransaction) => {
const transaction = Array.isArray(
mutationsOrTransaction
) ? { mutations: mutationsOrTransaction, transaction: !0 } : { ...mutationsOrTransaction, transaction: !0 };
stagedChanges.push(transaction);
const results = applyMutations(transaction.mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
mutations: result.mutations,
id: result.id,
before: result.before,
after: result.after,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
listenEvents,
listen: (id) => listenEvents(id).pipe(
rxjs.map(
(event) => event.type === "optimistic" ? event.after : event.after.local
)
),
optimize: () => {
setStaged(squashMutationGroups(stagedChanges));
},
submit: () => {
const pending = stagedChanges;
return setStaged([]), rxjs.lastValueFrom(
rxjs.from(
toTransactions(
// Squashing DMP strings is the last thing we do before submitting
squashDMPStrings(remote, squashMutationGroups(pending))
)
).pipe(
rxjs.concatMap((mut) => backend.submit(mut)),
rxjs.toArray()
)
);
}
};
}
function toTransactions(groups) {
return groups.map((group) => group.transaction && group.id !== void 0 ? { id: group.id, mutations: group.mutations } : { id: createTransactionId(), mutations: group.mutations });
}
exports.applyAll = applyAll;
exports.applyMutationEventEffects = applyMutationEventEffects;
exports.applyMutations = applyMutations;
exports.commit = commit;
exports.createDocumentMap = createDocumentMap;
exports.createOptimisticStore = createOptimisticStore;
exports.createTransactionId = createTransactionId;
exports.hasProperty = hasProperty;
exports.rebase = rebase;
exports.squashDMPStrings = squashDMPStrings;
exports.squashMutationGroups = squashMutationGroups;
exports.toTransactions = toTransactions;
//# sourceMappingURL=createOptimisticStore.cjs.map
{"version":3,"file":"createOptimisticStore.cjs","sources":["../../src/store/utils/getMutationDocumentId.ts","../../src/store/documentMap/applyDocumentMutation.ts","../../src/store/documentMap/applyMutations.ts","../../src/store/documentMap/commit.ts","../../src/store/utils/arrayUtils.ts","../../src/store/optimistic/optimizations/squashNodePatches.ts","../../src/store/optimistic/optimizations/squashDMPStrings.ts","../../src/store/optimistic/rebase.ts","../../src/store/utils/mergeMutationGroups.ts","../../src/store/optimistic/optimizations/squashMutations.ts","../../src/store/documentMap/applyMendoza.ts","../../src/store/documentMap/createDocumentMap.ts","../../src/store/utils/createReplayMemoizer.ts","../../src/store/utils/createTransactionId.ts","../../src/store/utils/filterMutationGroups.ts","../../src/store/utils/isEffectEvent.ts","../../src/store/optimistic/createOptimisticStore.ts"],"sourcesContent":["type MutationLike =\n | {type: 'patch'; id: string}\n | {type: 'create'; document: {_id: string}}\n | {type: 'delete'; id: string}\n | {type: 'createIfNotExists'; document: {_id: string}}\n | {type: 'createOrReplace'; document: {_id: string}}\n\nexport function getMutationDocumentId(mutation: MutationLike): string {\n if (mutation.type === 'patch') {\n return mutation.id\n }\n if (mutation.type === 'create') {\n return mutation.document._id\n }\n if (mutation.type === 'delete') {\n return mutation.id\n }\n if (mutation.type === 'createIfNotExists') {\n return mutation.document._id\n }\n if (mutation.type === 'createOrReplace') {\n return mutation.document._id\n }\n throw new Error('Invalid mutation type')\n}\n","import {nanoid} from 'nanoid'\n\nimport {applyPatchMutation, assignId, hasId} from '../../apply'\nimport {\n type CreateIfNotExistsMutation,\n type CreateMutation,\n type CreateOrReplaceMutation,\n type DeleteMutation,\n type Mutation,\n type PatchMutation,\n type SanityDocumentBase,\n} from '../../mutations/types'\n\nexport type MutationResult<Doc extends SanityDocumentBase> =\n | {\n id: string\n status: 'created'\n after: Doc\n }\n | {\n id: string\n status: 'updated'\n before: Doc\n after: Doc\n }\n | {\n id: string\n status: 'deleted'\n before: Doc | undefined\n after: undefined\n }\n | {\n status: 'error'\n message: string\n }\n | {\n status: 'noop'\n }\n\n/**\n * Applies a set of mutations to the provided document\n * @param current\n * @param mutation\n */\nexport function applyAll<Doc extends SanityDocumentBase>(\n current: Doc | undefined,\n mutation: Mutation<Doc>[],\n): Doc | undefined {\n return mutation.reduce((doc, m) => {\n const res = applyDocumentMutation(doc, m)\n if (res.status === 'error') {\n throw new Error(res.message)\n }\n return res.status === 'noop' ? doc : res.after\n }, current)\n}\n\n/**\n * Applies a mutation to the provided document\n * @param document\n * @param mutation\n */\nexport function applyDocumentMutation<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: Mutation<Doc>,\n): MutationResult<Doc> {\n if (mutation.type === 'create') {\n return create(document, mutation)\n }\n if (mutation.type === 'createIfNotExists') {\n return createIfNotExists(document, mutation)\n }\n if (mutation.type === 'delete') {\n return del(document, mutation)\n }\n if (mutation.type === 'createOrReplace') {\n return createOrReplace(document, mutation)\n }\n if (mutation.type === 'patch') {\n return patch(document, mutation)\n }\n // @ts-expect-error all cases should be covered\n throw new Error(`Invalid mutation type: ${mutation.type}`)\n}\n\nfunction create<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: CreateMutation<Doc>,\n): MutationResult<Doc> {\n if (document) {\n return {status: 'error', message: 'Document already exist'}\n }\n const result = assignId(mutation.document, nanoid)\n return {status: 'created', id: result._id, after: result}\n}\n\nfunction createIfNotExists<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: CreateIfNotExistsMutation<Doc>,\n): MutationResult<Doc> {\n if (!hasId(mutation.document)) {\n return {\n status: 'error',\n message: 'Cannot createIfNotExists on document without _id',\n }\n }\n return document\n ? {status: 'noop'}\n : {status: 'created', id: mutation.document._id, after: mutation.document}\n}\n\nfunction createOrReplace<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: CreateOrReplaceMutation<Doc>,\n): MutationResult<Doc> {\n if (!hasId(mutation.document)) {\n return {\n status: 'error',\n message: 'Cannot createIfNotExists on document without _id',\n }\n }\n\n return document\n ? {\n status: 'updated',\n id: mutation.document._id,\n before: document,\n after: mutation.document,\n }\n : {status: 'created', id: mutation.document._id, after: mutation.document}\n}\n\nfunction del<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: DeleteMutation,\n): MutationResult<Doc> {\n if (!document) {\n return {status: 'noop'}\n }\n if (mutation.id !== document._id) {\n return {status: 'error', message: 'Delete mutation targeted wrong document'}\n }\n return {\n status: 'deleted',\n id: mutation.id,\n before: document,\n after: undefined,\n }\n}\n\nfunction patch<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: PatchMutation,\n): MutationResult<Doc> {\n if (!document) {\n return {\n status: 'error',\n message: 'Cannot apply patch on nonexistent document',\n }\n }\n const next = applyPatchMutation(mutation, document)\n return document === next\n ? {status: 'noop'}\n : {status: 'updated', id: mutation.id, before: document, after: next}\n}\n","import {type Mutation, type SanityDocumentBase} from '../../mutations/types'\nimport {type DocumentMap} from '../types'\nimport {getMutationDocumentId} from '../utils/getMutationDocumentId'\nimport {applyDocumentMutation} from './applyDocumentMutation'\n\nexport interface UpdateResult<T extends SanityDocumentBase> {\n id: string\n status: 'created' | 'updated' | 'deleted'\n before?: T\n after?: T\n mutations: Mutation[]\n}\n\n/**\n * Takes a list of mutations and applies them to documents in a documentMap\n */\nexport function applyMutations<T extends SanityDocumentBase>(\n mutations: Mutation[],\n documentMap: DocumentMap<T>,\n /**\n * note: should never be set client side – only for test purposes\n */\n transactionId?: never,\n): UpdateResult<T>[] {\n const updatedDocs: Record<\n string,\n {\n before: T | undefined\n after: T | undefined\n mutations: Mutation[]\n }\n > = Object.create(null)\n\n for (const mutation of mutations) {\n const documentId = getMutationDocumentId(mutation)\n if (!documentId) {\n throw new Error('Unable to get document id from mutation')\n }\n\n const before = updatedDocs[documentId]?.after || documentMap.get(documentId)\n const res = applyDocumentMutation(before, mutation)\n if (res.status === 'error') {\n throw new Error(res.message)\n }\n\n let entry = updatedDocs[documentId]\n if (!entry) {\n entry = {before, after: before, mutations: []}\n updatedDocs[documentId] = entry\n }\n\n // Note: transactionId should never be set client side. Only for test purposes\n // if a transaction id is passed, set it as a new _rev\n const after = transactionId\n ? {...(res.status === 'noop' ? before : res.after), _rev: transactionId}\n : res.status === 'noop'\n ? before\n : res.after\n\n documentMap.set(documentId, after)\n entry.after = after\n entry.mutations.push(mutation)\n }\n\n return Object.entries(updatedDocs).map(\n ([id, {before, after, mutations: muts}]) => {\n return {\n id,\n status: after ? (before ? 'updated' : 'created') : 'deleted',\n mutations: muts,\n before,\n after,\n }\n },\n )\n}\n","import {type SanityDocumentBase} from '../../mutations/types'\nimport {type DocumentMap} from '../types'\nimport {type UpdateResult} from './applyMutations'\n\nexport function commit<Doc extends SanityDocumentBase>(\n results: UpdateResult<Doc>[],\n documentMap: DocumentMap<Doc>,\n) {\n results.forEach(result => {\n if (result.status === 'created' || result.status === 'updated') {\n documentMap.set(result.id, result.after)\n }\n if (result.status === 'deleted') {\n documentMap.delete(result.id)\n }\n })\n}\n","export function takeUntil<T>(\n arr: T[],\n predicate: (item: T) => boolean,\n opts?: {inclusive: boolean},\n) {\n const result = []\n for (const item of arr) {\n if (predicate(item)) {\n if (opts?.inclusive) {\n result.push(item)\n }\n return result\n }\n result.push(item)\n }\n return result\n}\n\nexport function takeUntilRight<T>(\n arr: T[],\n predicate: (item: T) => boolean,\n opts?: {inclusive: boolean},\n) {\n const result = []\n for (const item of arr.slice().reverse()) {\n if (predicate(item)) {\n if (opts?.inclusive) {\n result.push(item)\n }\n return result\n }\n result.push(item)\n }\n return result.reverse()\n}\n","import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'\n\nimport {applyNodePatch} from '../../../apply'\nimport {type Operation} from '../../../mutations/operations/types'\nimport {type NodePatch, type SanityDocumentBase} from '../../../mutations/types'\nimport {getAtPath, type Path, startsWith, stringify} from '../../../path'\nimport {takeUntilRight} from '../../utils/arrayUtils'\n\nfunction isEqualPath(p1: Path, p2: Path) {\n return stringify(p1) === stringify(p2)\n}\n\nfunction supersedes(later: Operation, earlier: Operation) {\n return (\n (earlier.type === 'set' || earlier.type === 'unset') &&\n (later.type === 'set' || later.type === 'unset')\n )\n}\n\nexport function squashNodePatches(patches: NodePatch[]) {\n return compactSetIfMissingPatches(\n compactSetPatches(compactUnsetPatches(patches)),\n )\n}\n\nexport function compactUnsetPatches(patches: NodePatch[]) {\n return patches.reduce(\n (earlierPatches: NodePatch[], laterPatch: NodePatch) => {\n if (laterPatch.op.type !== 'unset') {\n earlierPatches.push(laterPatch)\n return earlierPatches\n }\n // find all preceding patches that are affected by this unset\n const unaffected = earlierPatches.filter(\n earlierPatch => !startsWith(laterPatch.path, earlierPatch.path),\n )\n unaffected.push(laterPatch)\n return unaffected\n },\n [],\n )\n}\n\nexport function compactSetPatches(patches: NodePatch[]) {\n return patches.reduceRight(\n (laterPatches: NodePatch[], earlierPatch: NodePatch) => {\n const replacement = laterPatches.find(\n later =>\n supersedes(later.op, earlierPatch.op) &&\n isEqualPath(later.path, earlierPatch.path),\n )\n if (replacement) {\n // we already have another patch later in the chain that replaces this one\n return laterPatches\n }\n laterPatches.unshift(earlierPatch)\n return laterPatches\n },\n [],\n )\n}\n\nexport function compactSetIfMissingPatches(patches: NodePatch[]) {\n return patches.reduce(\n (previousPatches: NodePatch[], laterPatch: NodePatch) => {\n if (laterPatch.op.type !== 'setIfMissing') {\n previousPatches.push(laterPatch)\n return previousPatches\n }\n // look at preceding patches up until the first unset\n const check = takeUntilRight(\n previousPatches,\n patch => patch.op.type === 'unset',\n )\n const precedent = check.find(\n precedingPatch =>\n precedingPatch.op.type === 'setIfMissing' &&\n isEqualPath(precedingPatch.path, laterPatch.path),\n )\n if (precedent) {\n // we already have an identical patch earlier in the chain that voids this one\n return previousPatches\n }\n previousPatches.push(laterPatch)\n return previousPatches\n },\n [],\n )\n}\n\nexport function compactDMPSetPatches(\n base: SanityDocumentBase,\n patches: NodePatch[],\n) {\n let edge = base\n return patches.reduce(\n (earlierPatches: NodePatch[], laterPatch: NodePatch) => {\n const before = edge\n edge = applyNodePatch(laterPatch, edge)\n if (\n laterPatch.op.type === 'set' &&\n typeof laterPatch.op.value === 'string'\n ) {\n const current = getAtPath(laterPatch.path, before)\n if (typeof current === 'string') {\n // we can replace the earlier diffMatchPatches with a new one\n const replaced: NodePatch = {\n ...laterPatch,\n op: {\n type: 'diffMatchPatch',\n value: stringifyPatches(\n makePatches(current, laterPatch.op.value),\n ),\n },\n }\n return earlierPatches\n .flatMap(ep => {\n return isEqualPath(ep.path, laterPatch.path) &&\n ep.op.type === 'diffMatchPatch'\n ? []\n : ep\n })\n .concat(replaced)\n }\n }\n earlierPatches.push(laterPatch)\n return earlierPatches\n },\n [],\n )\n}\n","import {\n type Mutation,\n type NodePatch,\n type PatchMutation,\n type SanityDocumentBase,\n} from '../../../mutations/types'\nimport {type MutationGroup} from '../../types'\nimport {compactDMPSetPatches} from './squashNodePatches'\n\nexport interface DataStore {\n get: (id: string) => SanityDocumentBase | undefined\n}\nexport function squashDMPStrings(\n base: DataStore,\n mutationGroups: MutationGroup[],\n): MutationGroup[] {\n return mutationGroups.map(mutationGroup => ({\n ...mutationGroup,\n mutations: dmpIfyMutations(base, mutationGroup.mutations),\n }))\n}\n\nexport function dmpIfyMutations(\n store: DataStore,\n mutations: Mutation[],\n): Mutation[] {\n return mutations.map((mutation, i) => {\n if (mutation.type !== 'patch') {\n return mutation\n }\n const base = store.get(mutation.id)\n return base ? dmpifyPatchMutation(base, mutation) : mutation\n })\n}\n\nexport function dmpifyPatchMutation(\n base: SanityDocumentBase,\n mutation: PatchMutation,\n): PatchMutation {\n return {\n ...mutation,\n patches: compactDMPSetPatches(base, mutation.patches as NodePatch[]),\n }\n}\n","import {applyPatches} from '../../apply'\nimport {\n type Mutation,\n type NodePatch,\n type PatchMutation,\n type SanityDocumentBase,\n} from '../../mutations/types'\nimport {getAtPath} from '../../path'\nimport {applyAll} from '../documentMap/applyDocumentMutation'\nimport {type MutationGroup} from '../types'\nimport {getMutationDocumentId} from '../utils/getMutationDocumentId'\nimport {compactDMPSetPatches} from './optimizations/squashNodePatches'\n\ntype RebaseTransaction = {\n mutations: Mutation[]\n}\n\ntype FlatMutation = Exclude<Mutation, PatchMutation>\n\nfunction flattenMutations(mutations: Mutation[]) {\n return mutations.flatMap((mut): Mutation | Mutation[] => {\n if (mut.type === 'patch') {\n return mut.patches.map(\n (patch): PatchMutation => ({\n type: 'patch',\n id: mut.id,\n patches: [patch],\n }),\n )\n }\n return mut\n })\n}\n\nexport function rebase(\n documentId: string,\n oldBase: SanityDocumentBase | undefined,\n newBase: SanityDocumentBase | undefined,\n localMutations: MutationGroup[],\n): [newLocal: MutationGroup[], rebased: SanityDocumentBase | undefined] {\n // const flattened = flattenMutations(newStage.flatMap(t => t.mutations))\n\n // 1. get the dmpified mutations from the newStage based on the old base\n // 2. apply those to the new base\n // 3. convert those back into set patches based on the new base and return as a new newStage\n let edge = oldBase\n const dmpified = localMutations.map(transaction => {\n const mutations = transaction.mutations.flatMap(mut => {\n if (getMutationDocumentId(mut) !== documentId) {\n return []\n }\n const before = edge\n edge = applyAll(edge, [mut])\n if (!before) {\n return mut\n }\n if (mut.type !== 'patch') {\n return mut\n }\n return {\n type: 'dmpified' as const,\n mutation: {\n ...mut,\n // Todo: make compactDMPSetPatches return pairs of patches that was dmpified with their\n // original as dmpPatches and original is not 1:1 (e..g some of the original may not be dmpified)\n dmpPatches: compactDMPSetPatches(before, mut.patches as NodePatch[]),\n original: mut.patches,\n },\n }\n })\n return {...transaction, mutations}\n })\n\n let newBaseWithDMPForOldBaseApplied: SanityDocumentBase | undefined = newBase\n // NOTE: It might not be possible to apply them - if so, we fall back to applying the pending changes\n // todo: revisit this\n const appliedCleanly = dmpified.map(transaction => {\n const applied = []\n return transaction.mutations.forEach(mut => {\n if (mut.type === 'dmpified') {\n // go through all dmpified, try to apply, if they fail, use the original un-optimized set patch instead\n try {\n newBaseWithDMPForOldBaseApplied = applyPatches(\n mut.mutation.dmpPatches,\n newBaseWithDMPForOldBaseApplied,\n )\n applied.push(mut)\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to apply dmp patch, falling back to original')\n try {\n newBaseWithDMPForOldBaseApplied = applyPatches(\n mut.mutation.original,\n newBaseWithDMPForOldBaseApplied,\n )\n applied.push(mut)\n } catch (second: any) {\n throw new Error(\n `Failed to apply patch for document \"${documentId}\": ${second.message}`,\n )\n }\n }\n } else {\n newBaseWithDMPForOldBaseApplied = applyAll(\n newBaseWithDMPForOldBaseApplied,\n [mut],\n )\n }\n })\n })\n\n const newStage = localMutations.map((transaction): MutationGroup => {\n // update all set patches to set to the current value\n return {\n ...transaction,\n mutations: transaction.mutations.map(mut => {\n if (mut.type !== 'patch' || getMutationDocumentId(mut) !== documentId) {\n return mut\n }\n return {\n ...mut,\n patches: mut.patches.map(patch => {\n if (patch.op.type !== 'set') {\n return patch\n }\n return {\n ...patch,\n op: {\n ...patch.op,\n value: getAtPath(patch.path, newBaseWithDMPForOldBaseApplied),\n },\n }\n }),\n }\n }),\n }\n })\n return [newStage, newBaseWithDMPForOldBaseApplied]\n}\n","import {type MutationGroup} from '../types'\n\n/**\n * Merges adjacent non-transactional mutation groups, interleaving transactional mutations as-is\n * @param mutationGroups\n */\nexport function mergeMutationGroups(\n mutationGroups: MutationGroup[],\n): MutationGroup[] {\n return chunkWhile(mutationGroups, group => !group.transaction).flatMap(\n chunk => ({\n ...chunk[0]!,\n mutations: chunk.flatMap(c => c.mutations),\n }),\n )\n}\n\n/**\n * Groups subsequent mutations into transactions, leaves transactions as-is\n * @param arr\n * @param predicate\n */\nexport function chunkWhile<T>(\n arr: T[],\n predicate: (item: T) => boolean,\n): T[][] {\n const res: T[][] = []\n let currentChunk: T[] = []\n arr.forEach(item => {\n if (predicate(item)) {\n currentChunk.push(item)\n } else {\n if (currentChunk.length > 0) {\n res.push(currentChunk)\n }\n currentChunk = []\n res.push([item])\n }\n })\n if (currentChunk.length > 0) {\n res.push(currentChunk)\n }\n return res\n}\n","import {groupBy} from 'lodash'\n\nimport {type Mutation, type NodePatch} from '../../../mutations/types'\nimport {type MutationGroup} from '../../types'\nimport {takeUntilRight} from '../../utils/arrayUtils'\nimport {getMutationDocumentId} from '../../utils/getMutationDocumentId'\nimport {mergeMutationGroups} from '../../utils/mergeMutationGroups'\nimport {squashNodePatches} from './squashNodePatches'\n\nexport function squashMutationGroups(staged: MutationGroup[]): MutationGroup[] {\n return mergeMutationGroups(staged)\n .map(transaction => ({\n ...transaction,\n mutations: squashMutations(transaction.mutations),\n }))\n .map(transaction => ({\n ...transaction,\n mutations: transaction.mutations.map(mutation => {\n if (mutation.type !== 'patch') {\n return mutation\n }\n return {\n ...mutation,\n patches: squashNodePatches(mutation.patches as NodePatch[]),\n }\n }),\n }))\n}\n\ntype FIXME = Mutation[]\n\n/*\n assumptions:\n the order documents appear with their mutations within the same transaction doesn't matter\n */\nexport function squashMutations(mutations: Mutation[]): Mutation[] {\n const byDocument = groupBy(mutations, getMutationDocumentId)\n return Object.values(byDocument).flatMap(documentMutations => {\n // these are the mutations that happens for the document with <id> within the same transactions\n return squashCreateIfNotExists(squashDelete(documentMutations as FIXME))\n .flat()\n .reduce((acc: Mutation[], docMutation) => {\n const prev = acc[acc.length - 1]\n if ((!prev || prev.type === 'patch') && docMutation.type === 'patch') {\n return acc.slice(0, -1).concat({\n ...docMutation,\n patches: (prev?.patches || []).concat(docMutation.patches),\n })\n }\n return acc.concat(docMutation)\n }, [])\n })\n}\n\n/**\n * WARNING: This assumes that the mutations are only for a single document\n * @param mutations\n */\nexport function squashCreateIfNotExists(mutations: Mutation[]): Mutation[] {\n if (mutations.length === 0) {\n return mutations\n }\n\n return mutations.reduce((previousMuts: Mutation[], laterMut: Mutation) => {\n if (laterMut.type !== 'createIfNotExists') {\n previousMuts.push(laterMut)\n return previousMuts\n }\n const prev = takeUntilRight(previousMuts, m => m.type === 'delete')\n const precedent = prev.find(\n precedingPatch => precedingPatch.type === 'createIfNotExists',\n )\n if (precedent) {\n // we already have an identical patch earlier in the chain that voids this one\n return previousMuts\n }\n previousMuts.push(laterMut)\n return previousMuts\n }, [])\n}\n\nfunction squashDelete(mutations: Mutation[]): Mutation[] {\n if (mutations.length === 0) {\n return mutations\n }\n\n return mutations.reduce((previousMuts: Mutation[], laterMut: Mutation) => {\n if (laterMut.type === 'delete') {\n return [laterMut]\n }\n previousMuts.push(laterMut)\n return previousMuts\n }, [])\n}\n","import {applyPatch, type RawPatch} from 'mendoza'\n\nimport {type SanityDocumentBase} from '../../mutations/types'\n\nfunction omitRev(document: SanityDocumentBase | undefined) {\n if (document === undefined) {\n return undefined\n }\n const {_rev, ...doc} = document\n return doc\n}\n\nexport function applyMendozaPatch(\n document: SanityDocumentBase | undefined,\n patch: RawPatch,\n patchBaseRev?: string,\n): SanityDocumentBase | undefined {\n if (patchBaseRev !== document?._rev) {\n throw new Error(\n 'Invalid document revision. The provided patch is calculated from a different revision than the current document',\n )\n }\n const next = applyPatch(omitRev(document), patch)\n return next === null ? undefined : next\n}\n\nexport function applyMutationEventEffects(\n document: SanityDocumentBase | undefined,\n event: {effects: {apply: RawPatch}; previousRev?: string; resultRev?: string},\n) {\n if (!event.effects) {\n throw new Error(\n 'Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?',\n )\n }\n const next = applyMendozaPatch(\n document,\n event.effects.apply,\n event.previousRev,\n )\n // next will be undefined in case of deletion\n return next ? {...next, _rev: event.resultRev} : undefined\n}\n","import {type SanityDocumentBase} from '../../mutations/types'\n\n/**\n * Minimalistic dataset implementation that only supports what's strictly necessary\n */\nexport function createDocumentMap() {\n const documents = new Map<string, SanityDocumentBase | undefined>()\n return {\n set: (id: string, doc: SanityDocumentBase | undefined) =>\n void documents.set(id, doc),\n get: (id: string) => documents.get(id),\n delete: (id: string) => documents.delete(id),\n }\n}\n","import {finalize, type Observable, ReplaySubject, share, timer} from 'rxjs'\n\nexport function createReplayMemoizer(expiry: number) {\n const memo: {[key: string]: Observable<any>} = Object.create(null)\n return function memoize<T>(\n key: string,\n observable: Observable<T>,\n ): Observable<T> {\n if (!(key in memo)) {\n memo[key] = observable.pipe(\n finalize(() => {\n delete memo[key]\n }),\n share({\n connector: () => new ReplaySubject(1),\n resetOnRefCountZero: () => timer(expiry),\n }),\n )\n }\n return memo[key]!\n }\n}\n","import {uuid} from '@sanity/uuid'\n\nexport function createTransactionId() {\n return uuid()\n}\n","import {type Mutation} from '../../mutations/types'\nimport {type MutationGroup} from '../types'\nimport {getMutationDocumentId} from './getMutationDocumentId'\n\nexport function filterMutationGroupsById(\n mutationGroups: MutationGroup[],\n id: string,\n): Mutation[] {\n return mutationGroups.flatMap(mutationGroup =>\n mutationGroup.mutations.flatMap(mut =>\n getMutationDocumentId(mut) === id ? [mut] : [],\n ),\n )\n}\n","export function hasProperty<T, P extends keyof T>(\n value: T,\n property: P,\n): value is T & Required<Pick<T, P>> {\n const val = value[property]\n return typeof val !== 'undefined' && val !== null\n}\n","import {type ReconnectEvent} from '@sanity/client'\nimport {\n concatMap,\n defer,\n EMPTY,\n filter,\n from,\n lastValueFrom,\n map,\n merge,\n mergeMap,\n type Observable,\n of,\n Subject,\n tap,\n toArray,\n} from 'rxjs'\n\nimport {decodeAll, type SanityMutation} from '../../encoders/sanity'\nimport {type Transaction} from '../../mutations/types'\nimport {applyAll} from '../documentMap/applyDocumentMutation'\nimport {applyMutationEventEffects} from '../documentMap/applyMendoza'\nimport {applyMutations} from '../documentMap/applyMutations'\nimport {commit} from '../documentMap/commit'\nimport {createDocumentMap} from '../documentMap/createDocumentMap'\nimport {\n type ListenerEvent,\n type MutationGroup,\n type OptimisticDocumentEvent,\n type OptimisticStore,\n type RemoteDocumentEvent,\n type RemoteMutationEvent,\n type SubmitResult,\n type TransactionalMutationGroup,\n} from '../types'\nimport {createReplayMemoizer} from '../utils/createReplayMemoizer'\nimport {createTransactionId} from '../utils/createTransactionId'\nimport {filterMutationGroupsById} from '../utils/filterMutationGroups'\nimport {hasProperty} from '../utils/isEffectEvent'\nimport {squashDMPStrings} from './optimizations/squashDMPStrings'\nimport {squashMutationGroups} from './optimizations/squashMutations'\nimport {rebase} from './rebase'\n\nexport interface OptimisticStoreBackend {\n /**\n * Sets up a subscription to a document\n * The first event should either be a sync event or an error event.\n * After that, it should emit mutation events, error events or sync events\n * @param id\n */\n listen: (id: string) => Observable<ListenerEvent>\n submit: (mutationGroups: Transaction) => Observable<SubmitResult>\n}\n\nlet didEmitMutationsAccessWarning = false\n// certain components, like the portable text editor, rely on mutations to be present in the event\n// i.e. it's not enough to just have the mendoza-patches.\n// If the listener event did not include mutations (e.g. if excludeMutations was set to true),\n// this warning will be issued if a downstream consumers attempts to access event.mutations\nfunction warnNoMutationsReceived() {\n if (!didEmitMutationsAccessWarning) {\n // eslint-disable-next-line no-console\n console.warn(\n new Error(\n 'No mutation received from backend. The listener is likely set up with `excludeMutations: true`. If your app need to know about mutations, make sure the listener is set up to include mutations',\n ),\n )\n didEmitMutationsAccessWarning = true\n }\n}\n\nconst EMPTY_ARRAY: any[] = []\n\n/**\n * Creates a local dataset that allows subscribing to documents by id and submitting mutations to be optimistically applied\n * @param backend\n */\nexport function createOptimisticStore(\n backend: OptimisticStoreBackend,\n): OptimisticStore {\n const local = createDocumentMap()\n const remote = createDocumentMap()\n const memoize = createReplayMemoizer(1000)\n let stagedChanges: MutationGroup[] = []\n\n const remoteEvents$ = new Subject<RemoteDocumentEvent>()\n const localMutations$ = new Subject<OptimisticDocumentEvent>()\n\n const stage$ = new Subject<void>()\n\n function setStaged(nextPending: MutationGroup[]) {\n stagedChanges = nextPending\n stage$.next()\n }\n\n function getLocalEvents(id: string) {\n return localMutations$.pipe(filter(event => event.id === id))\n }\n\n function getRemoteEvents(id: string) {\n return backend.listen(id).pipe(\n filter(\n (event): event is Exclude<ListenerEvent, ReconnectEvent> =>\n event.type !== 'reconnect',\n ),\n mergeMap((event): Observable<RemoteDocumentEvent> => {\n const oldLocal = local.get(id)\n const oldRemote = remote.get(id)\n if (event.type === 'sync') {\n const newRemote = event.document\n const [rebasedStage, newLocal] = rebase(\n id,\n oldRemote,\n newRemote,\n stagedChanges,\n )\n return of({\n type: 'sync',\n id,\n before: {remote: oldRemote, local: oldLocal},\n after: {remote: newRemote, local: newLocal},\n rebasedStage,\n })\n } else if (event.type === 'mutation') {\n // we have already seen this mutation\n if (event.transactionId === oldRemote?._rev) {\n return EMPTY\n }\n let newRemote\n if (hasProperty(event, 'effects')) {\n newRemote = applyMutationEventEffects(oldRemote, event)\n } else if (hasProperty(event, 'mutations')) {\n newRemote = applyAll(oldRemote, decodeAll(event.mutations))\n } else {\n throw new Error(\n 'Neither effects or mutations found on listener event',\n )\n }\n const [rebasedStage, newLocal] = rebase(\n id,\n oldRemote,\n newRemote,\n stagedChanges,\n )\n\n if (newLocal) {\n newLocal._rev = event.transactionId\n }\n const emittedEvent: RemoteMutationEvent = {\n type: 'mutation',\n id,\n rebasedStage,\n before: {remote: oldRemote, local: oldLocal},\n after: {remote: newRemote, local: newLocal},\n effects: event.effects,\n previousRev: event.previousRev,\n resultRev: event.resultRev,\n // overwritten below\n mutations: EMPTY_ARRAY,\n }\n if (event.mutations) {\n emittedEvent.mutations = decodeAll(\n event.mutations as SanityMutation[],\n )\n } else {\n Object.defineProperty(\n emittedEvent,\n 'mutations',\n warnNoMutationsReceived,\n )\n }\n return of(emittedEvent)\n } else {\n // @ts-expect-error should have covered all cases\n throw new Error(`Unknown event type: ${event.type}`)\n }\n }),\n tap(event => {\n local.set(event.id, event.after.local)\n remote.set(event.id, event.after.remote)\n setStaged(event.rebasedStage)\n }),\n tap({\n next: event => remoteEvents$.next(event),\n error: err => {\n // todo: how to propagate errors?\n // remoteEvents$.next()\n },\n }),\n )\n }\n\n function listenEvents(id: string) {\n return defer(() =>\n memoize(id, merge(getLocalEvents(id), getRemoteEvents(id))),\n )\n }\n\n const metaEvents$ = merge(localMutations$, remoteEvents$)\n\n return {\n meta: {\n events: metaEvents$,\n stage: stage$.pipe(\n map(\n () =>\n // note: this should not be tampered with by consumers. We might want to do a deep-freeze during dev to avoid accidental mutations\n stagedChanges,\n ),\n ),\n conflicts: EMPTY, // does nothing for now\n },\n mutate: mutations => {\n // add mutations to list of pending changes\n stagedChanges.push({transaction: false, mutations})\n // Apply mutations to local dataset (note: this is immutable, and doesn't change the dataset)\n const results = applyMutations(mutations, local)\n // Write the updated results back to the \"local\" dataset\n commit(results, local)\n results.forEach(result => {\n localMutations$.next({\n type: 'optimistic',\n before: result.before,\n after: result.after,\n mutations: result.mutations,\n id: result.id,\n stagedChanges: filterMutationGroupsById(stagedChanges, result.id),\n })\n })\n return results\n },\n transaction: mutationsOrTransaction => {\n const transaction: TransactionalMutationGroup = Array.isArray(\n mutationsOrTransaction,\n )\n ? {mutations: mutationsOrTransaction, transaction: true}\n : {...mutationsOrTransaction, transaction: true}\n\n stagedChanges.push(transaction)\n const results = applyMutations(transaction.mutations, local)\n commit(results, local)\n results.forEach(result => {\n localMutations$.next({\n type: 'optimistic',\n mutations: result.mutations,\n id: result.id,\n before: result.before,\n after: result.after,\n stagedChanges: filterMutationGroupsById(stagedChanges, result.id),\n })\n })\n return results\n },\n listenEvents: listenEvents,\n listen: id =>\n listenEvents(id).pipe(\n map(event =>\n event.type === 'optimistic' ? event.after : event.after.local,\n ),\n ),\n optimize: () => {\n setStaged(squashMutationGroups(stagedChanges))\n },\n submit: () => {\n const pending = stagedChanges\n setStaged([])\n return lastValueFrom(\n from(\n toTransactions(\n // Squashing DMP strings is the last thing we do before submitting\n squashDMPStrings(remote, squashMutationGroups(pending)),\n ),\n ).pipe(\n concatMap(mut => backend.submit(mut)),\n toArray(),\n ),\n )\n },\n }\n}\n\nexport function toTransactions(groups: MutationGroup[]): Transaction[] {\n return groups.map(group => {\n if (group.transaction && group.id !== undefined) {\n return {id: group.id!, mutations: group.mutations}\n }\n return {id: createTransactionId(), mutations: group.mutations}\n })\n}\n"],"names":["assignId","nanoid","hasId","applyPatchMutation","stringify","startsWith","patch","applyNodePatch","getAtPath","stringifyPatches","makePatches","applyPatches","groupBy","applyPatch","finalize","share","ReplaySubject","timer","uuid","Subject","filter","mergeMap","of","EMPTY","decodeAll","tap","defer","merge","map","lastValueFrom","from","concatMap","toArray"],"mappings":";;;;;;AAOO,SAAS,sBAAsB,UAAgC;AACpE,MAAI,SAAS,SAAS;AACpB,WAAO,SAAS;AAElB,MAAI,SAAS,SAAS;AAC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CAAE,GACLC,KAAAA;AAAAA,QACLC,KAAAA;AAAAA,UACE;AAAA;AAAA,YAEE,iBAAiB,QAAQ,qBAAqB,OAAO,CAAC;AAAA,UAAA;AAAA,QACxD,EACA;AAAA,UACAC,KAAAA,UAAU,CAAA,QAAO,QAAQ,OAAO,GAAG,CAAC;AAAA,UACpCC,KAAAA,QAAA;AAAA,QAAQ;AAAA,MACV;AAAA,IAEJ;AAAA,EAAA;AAEJ;AAEO,SAAS,eAAe,QAAwC;AACrE,SAAO,OAAO,IAAI,CAAA,UACZ,MAAM,eAAe,MAAM,OAAO,SAC7B,EAAC,IAAI,MAAM,IAAK,WAAW,MAAM,UAAA,IAEnC,EAAC,IAAI,uBAAuB,WAAW,MAAM,WACrD;AACH;;;;;;;;;;;;;"}
import { AnyArray, ArrayElement, ElementType, Index, KeyedPathElement, NormalizeReadOnlyArray, Optional, Path, SafePath, Tuplify } from "./types.cjs";
import { AssignOp, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, IncOp, InsertIfMissingOp, InsertOp, Mutation, NodePatch, NodePatchList, Operation, PatchMutation, PatchOptions, RelativePosition, RemoveOp, ReplaceOp, SanityDocumentBase, SetIfMissingOp, SetOp, Transaction, TruncateOp, UnassignOp, UnsetOp, UpsertOp } from "./types2.cjs";
import { Insert, InsertAfter, InsertBefore, InsertReplace, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch } from "./types3.cjs";
declare function decodeAll<Doc extends SanityDocumentBase>(sanityMutations: SanityMutation<Doc>[]): Mutation[];
declare function decode$1<Doc extends SanityDocumentBase>(encodedMutation: SanityMutation<Doc>): Mutation;
type Id = string;
type RevisionLock = string;
type CompactPath = string;
type ItemRef$1 = string | number;
type DeleteMutation$1 = ['delete', Id];
type CreateMutation$1<Doc> = ['create', Doc];
type CreateIfNotExistsMutation$1<Doc> = ['createIfNotExists', Doc];
type CreateOrReplaceMutation$1<Doc> = ['createOrReplace', Doc];
type UnsetMutation = ['patch', 'unset', Id, CompactPath, [], RevisionLock?];
type InsertMutation = ['patch', 'insert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type UpsertMutation = ['patch', 'upsert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type InsertIfMissingMutation = ['patch', 'insertIfMissing', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type TruncateMutation = ['patch', 'truncate', Id, CompactPath, [startIndex: number, endIndex: number | undefined], RevisionLock?];
type IncMutation = ['patch', 'inc', Id, CompactPath, [number], RevisionLock?];
type DecMutation = ['patch', 'dec', Id, CompactPath, [number], RevisionLock?];
type AssignMutation = ['patch', 'assign', Id, CompactPath, [object], RevisionLock?];
type UnassignMutation = ['patch', 'assign', Id, CompactPath, [string[]], RevisionLock?];
type ReplaceMutation = ['patch', 'replace', Id, CompactPath, [ItemRef$1, AnyArray], RevisionLock?];
type RemoveMutation = ['patch', 'remove', Id, CompactPath, [ItemRef$1], RevisionLock?];
type SetMutation = ['patch', 'set', Id, CompactPath, any, RevisionLock?];
type SetIfMissingMutation = ['patch', 'setIfMissing', Id, CompactPath, [unknown], RevisionLock?];
type DiffMatchPatchMutation = ['patch', 'diffMatchPatch', Id, CompactPath, [string], RevisionLock?];
type CompactPatchMutation = UnsetMutation | InsertMutation | UpsertMutation | InsertIfMissingMutation | TruncateMutation | IncMutation | DecMutation | SetMutation | SetIfMissingMutation | DiffMatchPatchMutation | AssignMutation | UnassignMutation | ReplaceMutation | RemoveMutation;
type CompactMutation<Doc> = DeleteMutation$1 | CreateMutation$1<Doc> | CreateIfNotExistsMutation$1<Doc> | CreateOrReplaceMutation$1<Doc> | CompactPatchMutation;
declare function decode<Doc extends SanityDocumentBase>(mutations: CompactMutation<Doc>[]): Mutation[];
declare function encode$1<Doc extends SanityDocumentBase>(mutations: Mutation[]): CompactMutation<Doc>[];
declare namespace index_d_exports$2 {
export { AssignMutation, CompactMutation, CompactPatchMutation, CompactPath, CreateIfNotExistsMutation$1 as CreateIfNotExistsMutation, CreateMutation$1 as CreateMutation, CreateOrReplaceMutation$1 as CreateOrReplaceMutation, DecMutation, DeleteMutation$1 as DeleteMutation, DiffMatchPatchMutation, Id, IncMutation, InsertIfMissingMutation, InsertMutation, ItemRef$1 as ItemRef, RemoveMutation, ReplaceMutation, RevisionLock, SetIfMissingMutation, SetMutation, TruncateMutation, UnassignMutation, UnsetMutation, UpsertMutation, decode, encode$1 as encode };
}
/**
* @deprecated
*/
type FormPatchPathKeyedSegment = {
_key: string;
};
/**
* @deprecated
*/
type FormPatchPathIndexTuple = [number | '', number | ''];
/**
* @deprecated
*/
type FormPatchPathSegment = string | number | FormPatchPathKeyedSegment | FormPatchPathIndexTuple;
/**
* @deprecated
*/
type FormPatchPath = FormPatchPathSegment[];
/**
* A variant of the FormPath type that never contains index tupes
*/
type CompatPath = Exclude<ElementType<FormPatchPath>, FormPatchPathIndexTuple>[];
/**
*
* @internal
* @deprecated
*/
type FormPatchJSONValue = number | string | boolean | {
[key: string]: FormPatchJSONValue;
} | FormPatchJSONValue[];
/**
*
* @internal
* @deprecated
*/
type FormPatchOrigin = 'remote' | 'local' | 'internal';
/**
*
* @internal
* @deprecated
*/
interface FormSetPatch {
path: FormPatchPath;
type: 'set';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormIncPatch {
path: FormPatchPath;
type: 'inc';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormDecPatch {
path: FormPatchPath;
type: 'dec';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormSetIfMissingPatch {
path: FormPatchPath;
type: 'setIfMissing';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormUnsetPatch {
path: FormPatchPath;
type: 'unset';
}
/**
*
* @internal
* @deprecated
*/
type FormInsertPatchPosition = 'before' | 'after';
/**
*
* @internal
* @deprecated
*/
interface FormInsertPatch {
path: FormPatchPath;
type: 'insert';
position: FormInsertPatchPosition;
items: FormPatchJSONValue[];
}
/**
*
* @internal
* @deprecated
*/
interface FormDiffMatchPatch {
path: FormPatchPath;
type: 'diffMatchPatch';
value: string;
}
/**
*
* @internal
* @deprecated
*/
type FormPatchLike = FormSetPatch | FormSetIfMissingPatch | FormUnsetPatch | FormInsertPatch | FormDiffMatchPatch;
/**
* Convert a Sanity form patch (ie emitted from an input component) to a {@link NodePatch}
* Note the lack of encodeMutation here. Sanity forms never emit *mutations*, only patches
* @param patches - Array of {@link FormPatchLike}
* @internal
*/
declare function encodePatches(patches: FormPatchLike[]): NodePatch[];
declare namespace index_d_exports$3 {
export { CompatPath, FormDecPatch, FormDiffMatchPatch, FormIncPatch, FormInsertPatch, FormInsertPatchPosition, FormPatchJSONValue, FormPatchLike, FormPatchOrigin, FormPatchPath, FormPatchPathIndexTuple, FormPatchPathKeyedSegment, FormPatchPathSegment, FormSetIfMissingPatch, FormSetPatch, FormUnsetPatch, encodePatches };
}
declare namespace compact_d_exports {
export { ItemRef, format };
}
type ItemRef = string | number;
declare function format<Doc extends SanityDocumentBase>(mutations: Mutation[]): string;
declare function autoKeys<Item>(generateKey: (item: Item) => string): {
insert: <Pos extends RelativePosition, Ref extends Index | KeyedPathElement>(position: Pos, referenceItem: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], Pos, Ref>;
upsert: <Pos extends RelativePosition, ReferenceItem extends KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => UpsertOp<Arrify<Item & {
_key: string;
}>, Pos, ReferenceItem>;
replace: <Pos extends RelativePosition, ReferenceItem extends Index | KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => ReplaceOp<(Item & {
_key: string;
})[], ReferenceItem>;
insertBefore: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", Ref>;
prepend: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", 0>;
insertAfter: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", Ref>;
append: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", -1>;
};
declare function create<Doc extends Optional<SanityDocumentBase, '_id'>>(document: Doc): CreateMutation<Doc>;
declare function patch<P extends NodePatchList | NodePatch>(id: string, patches: P, options?: PatchOptions): PatchMutation<NormalizeReadOnlyArray<Tuplify<P>>>;
declare function at<const P extends Path, O extends Operation>(path: P, operation: O): NodePatch<NormalizeReadOnlyArray<P>, O>;
declare function at<const P extends string, O extends Operation>(path: P, operation: O): NodePatch<SafePath<P>, O>;
declare function createIfNotExists<Doc extends SanityDocumentBase>(document: Doc): CreateIfNotExistsMutation<Doc>;
declare function createOrReplace<Doc extends SanityDocumentBase>(document: Doc): CreateOrReplaceMutation<Doc>;
declare function delete_(id: string): DeleteMutation;
declare const del: typeof delete_;
declare const destroy: typeof delete_;
type Arrify<T> = (T extends (infer E)[] ? E : T)[];
declare const set: <const T>(value: T) => SetOp<T>;
declare const assign: <const T extends { [K in string]: unknown }>(value: T) => AssignOp<T>;
declare const unassign: <const K extends readonly string[]>(keys: K) => UnassignOp<K>;
declare const setIfMissing: <const T>(value: T) => SetIfMissingOp<T>;
declare const unset: () => UnsetOp;
declare const inc: <const N extends number = 1>(amount?: N) => IncOp<N>;
declare const dec: <const N extends number = 1>(amount?: N) => DecOp<N>;
declare const diffMatchPatch: (value: string) => DiffMatchPatchOp;
declare function insert<const Items extends AnyArray<unknown>, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, position: Pos, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, Pos, ReferenceItem>;
declare function append<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "after", -1>;
declare function prepend<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "before", 0>;
declare function insertBefore<const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, "before", ReferenceItem>;
declare const insertAfter: <const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem) => InsertOp<NormalizeReadOnlyArray<Items>, "after", ReferenceItem>;
declare function truncate(startIndex: number, endIndex?: number): TruncateOp;
declare function replace<Items extends any[], ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, referenceItem: ReferenceItem): ReplaceOp<Items, ReferenceItem>;
declare function remove<ReferenceItem extends Index | KeyedPathElement>(referenceItem: ReferenceItem): RemoveOp<ReferenceItem>;
declare function upsert<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): UpsertOp<Arrify<Item>, Pos, ReferenceItem>;
declare function insertIfMissing<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): InsertIfMissingOp<Arrify<Item>, Pos, ReferenceItem>;
declare function encode(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodeAll(mutations: Mutation[]): SanityMutation[];
declare function encodeTransaction(transaction: Transaction): {
transactionId: string | undefined;
mutations: SanityMutation[];
};
declare function encodeMutation(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodePatch(patch: NodePatch): {
unset: string[];
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
diffMatchPatch: {
[x: string]: string;
};
unset?: undefined;
insert?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
inc: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
dec?: undefined;
set?: undefined;
} | {
dec: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
set?: undefined;
} | {
[x: string]: {
[x: string]: unknown;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
unset: string[];
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
set: {
[k: string]: never;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
} | {
insert: {
replace: string;
items: AnyArray;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
};
declare namespace index_d_exports {
export { Insert, InsertAfter, InsertBefore, InsertReplace, Mutation, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, decode$1 as decode, decodeAll, encode, encodeAll, encodeMutation, encodePatch, encodeTransaction };
}
export { type Arrify, append, assign, at, autoKeys, compact_d_exports, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, index_d_exports, index_d_exports$3 as index_d_exports$1, index_d_exports$2, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert };
//# sourceMappingURL=index.d.cts.map
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/encoders/sanity/decode.ts","../../src/encoders/compact/types.ts","../../src/encoders/compact/decode.ts","../../src/encoders/compact/encode.ts","../../src/encoders/compact/index.ts","../../src/encoders/form-compat/form-patch-types.ts","../../src/encoders/form-compat/encode.ts","../../src/encoders/form-compat/index.ts","../../src/formatters/compact.ts","../../src/mutations/autoKeys.ts","../../src/mutations/creators.ts","../../src/utils/arrify.ts","../../src/mutations/operations/creators.ts","../../src/encoders/sanity/encode.ts","../../src/encoders/sanity/index.ts"],"sourcesContent":[],"mappings":";;;iBAiGgB,sBAAsB,qCACnB,eAAe,SAAM;iBAKxB,qBAAmB,qCAChB,eAAe,OAAI;KCrG1B,EAAA;KACA,YAAA;KACA,WAAA;KACA,SAAA;KAEA,gBAAA,cAA4B;KAC5B,mCAAiC;KACjC,yDAAuD;KACvD,qDAAmD;KAEnD,aAAA,aDoFI,OAAA,ECjFd,EDiFuB,EChFvB,WDgFoC,MC9EpC,YD+EsC,CAAA,CAAA;AAKxB,KClFJ,cAAA,GDkFU,CAAA,OAAA,UAAa,EC/EjC,IACA,WD+EiB,GC9EhB,gBD8EmC,EC9EjB,WAAS,QAvBhB,CACF,EAuBV,YAtBU,CAAA,CACZ;AAEY,KAsBA,cAAA,GAtBc,CACd,OAAA,EACA,QAAA,EAuBV,EAtBU,EAuBV,WArBU,EAAa,CAsBtB,gBAnBD,EAmBmB,SAlBnB,EAkB4B,QAhB5B,CAAY,EAiBZ,YAfU,CAAA,CAAc;AAGxB,KAeU,uBAAA,GAfV,QACA,mBACC,EAgBD,IACA,WAjB4B,GAkB3B,gBAjBW,EAiBO,SAdT,EAckB,QAdJ,GAexB,YAXA,CAAA;AACmB,KAaT,gBAAA,GAbS,QAAS,YAC5B,EAeA,EAfY,EAgBZ,WAbU,EAAuB,CAGjC,UAAA,EAAA,MAAA,EACA,QAAA,EAAA,M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,SAAA;KAGrB,CAAA,EAAA,SAAA;KACA,CAAA,EAAA,SAAA;;EAEY,MAAA,EAAA;IAEF,OAAA,EAAA,MAAc;IAAA,KAAA,UAAA;;OAIxB,CAAA,EAAA,SAAA;gBAEA,CAAA,EAAA,SAAA;EAAY,GAAA,CAAA,EAAA,SAAA;EAEF,GAAA,CAAA,EAAA,SAAA;EAAgB,GAAA,CAAA,EAAA,SAAA"}
import { AnyArray, ArrayElement, ElementType, Index, KeyedPathElement, NormalizeReadOnlyArray, Optional, Path, SafePath, Tuplify } from "./types.js";
import { AssignOp, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, IncOp, InsertIfMissingOp, InsertOp, Mutation, NodePatch, NodePatchList, Operation, PatchMutation, PatchOptions, RelativePosition, RemoveOp, ReplaceOp, SanityDocumentBase, SetIfMissingOp, SetOp, Transaction, TruncateOp, UnassignOp, UnsetOp, UpsertOp } from "./types2.js";
import { Insert, InsertAfter, InsertBefore, InsertReplace, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch } from "./types3.js";
declare function decodeAll<Doc extends SanityDocumentBase>(sanityMutations: SanityMutation<Doc>[]): Mutation[];
declare function decode$1<Doc extends SanityDocumentBase>(encodedMutation: SanityMutation<Doc>): Mutation;
type Id = string;
type RevisionLock = string;
type CompactPath = string;
type ItemRef$1 = string | number;
type DeleteMutation$1 = ['delete', Id];
type CreateMutation$1<Doc> = ['create', Doc];
type CreateIfNotExistsMutation$1<Doc> = ['createIfNotExists', Doc];
type CreateOrReplaceMutation$1<Doc> = ['createOrReplace', Doc];
type UnsetMutation = ['patch', 'unset', Id, CompactPath, [], RevisionLock?];
type InsertMutation = ['patch', 'insert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type UpsertMutation = ['patch', 'upsert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type InsertIfMissingMutation = ['patch', 'insertIfMissing', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type TruncateMutation = ['patch', 'truncate', Id, CompactPath, [startIndex: number, endIndex: number | undefined], RevisionLock?];
type IncMutation = ['patch', 'inc', Id, CompactPath, [number], RevisionLock?];
type DecMutation = ['patch', 'dec', Id, CompactPath, [number], RevisionLock?];
type AssignMutation = ['patch', 'assign', Id, CompactPath, [object], RevisionLock?];
type UnassignMutation = ['patch', 'assign', Id, CompactPath, [string[]], RevisionLock?];
type ReplaceMutation = ['patch', 'replace', Id, CompactPath, [ItemRef$1, AnyArray], RevisionLock?];
type RemoveMutation = ['patch', 'remove', Id, CompactPath, [ItemRef$1], RevisionLock?];
type SetMutation = ['patch', 'set', Id, CompactPath, any, RevisionLock?];
type SetIfMissingMutation = ['patch', 'setIfMissing', Id, CompactPath, [unknown], RevisionLock?];
type DiffMatchPatchMutation = ['patch', 'diffMatchPatch', Id, CompactPath, [string], RevisionLock?];
type CompactPatchMutation = UnsetMutation | InsertMutation | UpsertMutation | InsertIfMissingMutation | TruncateMutation | IncMutation | DecMutation | SetMutation | SetIfMissingMutation | DiffMatchPatchMutation | AssignMutation | UnassignMutation | ReplaceMutation | RemoveMutation;
type CompactMutation<Doc> = DeleteMutation$1 | CreateMutation$1<Doc> | CreateIfNotExistsMutation$1<Doc> | CreateOrReplaceMutation$1<Doc> | CompactPatchMutation;
declare function decode<Doc extends SanityDocumentBase>(mutations: CompactMutation<Doc>[]): Mutation[];
declare function encode$1<Doc extends SanityDocumentBase>(mutations: Mutation[]): CompactMutation<Doc>[];
declare namespace index_d_exports$2 {
export { AssignMutation, CompactMutation, CompactPatchMutation, CompactPath, CreateIfNotExistsMutation$1 as CreateIfNotExistsMutation, CreateMutation$1 as CreateMutation, CreateOrReplaceMutation$1 as CreateOrReplaceMutation, DecMutation, DeleteMutation$1 as DeleteMutation, DiffMatchPatchMutation, Id, IncMutation, InsertIfMissingMutation, InsertMutation, ItemRef$1 as ItemRef, RemoveMutation, ReplaceMutation, RevisionLock, SetIfMissingMutation, SetMutation, TruncateMutation, UnassignMutation, UnsetMutation, UpsertMutation, decode, encode$1 as encode };
}
/**
* @deprecated
*/
type FormPatchPathKeyedSegment = {
_key: string;
};
/**
* @deprecated
*/
type FormPatchPathIndexTuple = [number | '', number | ''];
/**
* @deprecated
*/
type FormPatchPathSegment = string | number | FormPatchPathKeyedSegment | FormPatchPathIndexTuple;
/**
* @deprecated
*/
type FormPatchPath = FormPatchPathSegment[];
/**
* A variant of the FormPath type that never contains index tupes
*/
type CompatPath = Exclude<ElementType<FormPatchPath>, FormPatchPathIndexTuple>[];
/**
*
* @internal
* @deprecated
*/
type FormPatchJSONValue = number | string | boolean | {
[key: string]: FormPatchJSONValue;
} | FormPatchJSONValue[];
/**
*
* @internal
* @deprecated
*/
type FormPatchOrigin = 'remote' | 'local' | 'internal';
/**
*
* @internal
* @deprecated
*/
interface FormSetPatch {
path: FormPatchPath;
type: 'set';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormIncPatch {
path: FormPatchPath;
type: 'inc';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormDecPatch {
path: FormPatchPath;
type: 'dec';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormSetIfMissingPatch {
path: FormPatchPath;
type: 'setIfMissing';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormUnsetPatch {
path: FormPatchPath;
type: 'unset';
}
/**
*
* @internal
* @deprecated
*/
type FormInsertPatchPosition = 'before' | 'after';
/**
*
* @internal
* @deprecated
*/
interface FormInsertPatch {
path: FormPatchPath;
type: 'insert';
position: FormInsertPatchPosition;
items: FormPatchJSONValue[];
}
/**
*
* @internal
* @deprecated
*/
interface FormDiffMatchPatch {
path: FormPatchPath;
type: 'diffMatchPatch';
value: string;
}
/**
*
* @internal
* @deprecated
*/
type FormPatchLike = FormSetPatch | FormSetIfMissingPatch | FormUnsetPatch | FormInsertPatch | FormDiffMatchPatch;
/**
* Convert a Sanity form patch (ie emitted from an input component) to a {@link NodePatch}
* Note the lack of encodeMutation here. Sanity forms never emit *mutations*, only patches
* @param patches - Array of {@link FormPatchLike}
* @internal
*/
declare function encodePatches(patches: FormPatchLike[]): NodePatch[];
declare namespace index_d_exports$3 {
export { CompatPath, FormDecPatch, FormDiffMatchPatch, FormIncPatch, FormInsertPatch, FormInsertPatchPosition, FormPatchJSONValue, FormPatchLike, FormPatchOrigin, FormPatchPath, FormPatchPathIndexTuple, FormPatchPathKeyedSegment, FormPatchPathSegment, FormSetIfMissingPatch, FormSetPatch, FormUnsetPatch, encodePatches };
}
declare namespace compact_d_exports {
export { ItemRef, format };
}
type ItemRef = string | number;
declare function format<Doc extends SanityDocumentBase>(mutations: Mutation[]): string;
declare function autoKeys<Item>(generateKey: (item: Item) => string): {
insert: <Pos extends RelativePosition, Ref extends Index | KeyedPathElement>(position: Pos, referenceItem: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], Pos, Ref>;
upsert: <Pos extends RelativePosition, ReferenceItem extends KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => UpsertOp<Arrify<Item & {
_key: string;
}>, Pos, ReferenceItem>;
replace: <Pos extends RelativePosition, ReferenceItem extends Index | KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => ReplaceOp<(Item & {
_key: string;
})[], ReferenceItem>;
insertBefore: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", Ref>;
prepend: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", 0>;
insertAfter: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", Ref>;
append: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", -1>;
};
declare function create<Doc extends Optional<SanityDocumentBase, '_id'>>(document: Doc): CreateMutation<Doc>;
declare function patch<P extends NodePatchList | NodePatch>(id: string, patches: P, options?: PatchOptions): PatchMutation<NormalizeReadOnlyArray<Tuplify<P>>>;
declare function at<const P extends Path, O extends Operation>(path: P, operation: O): NodePatch<NormalizeReadOnlyArray<P>, O>;
declare function at<const P extends string, O extends Operation>(path: P, operation: O): NodePatch<SafePath<P>, O>;
declare function createIfNotExists<Doc extends SanityDocumentBase>(document: Doc): CreateIfNotExistsMutation<Doc>;
declare function createOrReplace<Doc extends SanityDocumentBase>(document: Doc): CreateOrReplaceMutation<Doc>;
declare function delete_(id: string): DeleteMutation;
declare const del: typeof delete_;
declare const destroy: typeof delete_;
type Arrify<T> = (T extends (infer E)[] ? E : T)[];
declare const set: <const T>(value: T) => SetOp<T>;
declare const assign: <const T extends { [K in string]: unknown }>(value: T) => AssignOp<T>;
declare const unassign: <const K extends readonly string[]>(keys: K) => UnassignOp<K>;
declare const setIfMissing: <const T>(value: T) => SetIfMissingOp<T>;
declare const unset: () => UnsetOp;
declare const inc: <const N extends number = 1>(amount?: N) => IncOp<N>;
declare const dec: <const N extends number = 1>(amount?: N) => DecOp<N>;
declare const diffMatchPatch: (value: string) => DiffMatchPatchOp;
declare function insert<const Items extends AnyArray<unknown>, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, position: Pos, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, Pos, ReferenceItem>;
declare function append<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "after", -1>;
declare function prepend<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "before", 0>;
declare function insertBefore<const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, "before", ReferenceItem>;
declare const insertAfter: <const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem) => InsertOp<NormalizeReadOnlyArray<Items>, "after", ReferenceItem>;
declare function truncate(startIndex: number, endIndex?: number): TruncateOp;
declare function replace<Items extends any[], ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, referenceItem: ReferenceItem): ReplaceOp<Items, ReferenceItem>;
declare function remove<ReferenceItem extends Index | KeyedPathElement>(referenceItem: ReferenceItem): RemoveOp<ReferenceItem>;
declare function upsert<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): UpsertOp<Arrify<Item>, Pos, ReferenceItem>;
declare function insertIfMissing<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): InsertIfMissingOp<Arrify<Item>, Pos, ReferenceItem>;
declare function encode(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodeAll(mutations: Mutation[]): SanityMutation[];
declare function encodeTransaction(transaction: Transaction): {
transactionId: string | undefined;
mutations: SanityMutation[];
};
declare function encodeMutation(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodePatch(patch: NodePatch): {
unset: string[];
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
diffMatchPatch: {
[x: string]: string;
};
unset?: undefined;
insert?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
inc: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
dec?: undefined;
set?: undefined;
} | {
dec: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
set?: undefined;
} | {
[x: string]: {
[x: string]: unknown;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
unset: string[];
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
set: {
[k: string]: never;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
} | {
insert: {
replace: string;
items: AnyArray;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
};
declare namespace index_d_exports {
export { Insert, InsertAfter, InsertBefore, InsertReplace, Mutation, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, decode$1 as decode, decodeAll, encode, encodeAll, encodeMutation, encodePatch, encodeTransaction };
}
export { type Arrify, append, assign, at, autoKeys, compact_d_exports, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, index_d_exports, index_d_exports$3 as index_d_exports$1, index_d_exports$2, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert };
//# sourceMappingURL=index.d.ts.map
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/encoders/sanity/decode.ts","../../src/encoders/compact/types.ts","../../src/encoders/compact/decode.ts","../../src/encoders/compact/encode.ts","../../src/encoders/compact/index.ts","../../src/encoders/form-compat/form-patch-types.ts","../../src/encoders/form-compat/encode.ts","../../src/encoders/form-compat/index.ts","../../src/formatters/compact.ts","../../src/mutations/autoKeys.ts","../../src/mutations/creators.ts","../../src/utils/arrify.ts","../../src/mutations/operations/creators.ts","../../src/encoders/sanity/encode.ts","../../src/encoders/sanity/index.ts"],"sourcesContent":[],"mappings":";;;iBAiGgB,sBAAsB,qCACnB,eAAe,SAAM;iBAKxB,qBAAmB,qCAChB,eAAe,OAAI;KCrG1B,EAAA;KACA,YAAA;KACA,WAAA;KACA,SAAA;KAEA,gBAAA,cAA4B;KAC5B,mCAAiC;KACjC,yDAAuD;KACvD,qDAAmD;KAEnD,aAAA,aDoFI,OAAA,ECjFd,EDiFuB,EChFvB,WDgFoC,MC9EpC,YD+EsC,CAAA,CAAA;AAKxB,KClFJ,cAAA,GDkFU,CAAA,OAAA,UAAa,EC/EjC,IACA,WD+EiB,GC9EhB,gBD8EmC,EC9EjB,WAAS,QAvBhB,CACF,EAuBV,YAtBU,CAAA,CACZ;AAEY,KAsBA,cAAA,GAtBc,CACd,OAAA,EACA,QAAA,EAuBV,EAtBU,EAuBV,WArBU,EAAa,CAsBtB,gBAnBD,EAmBmB,SAlBnB,EAkB4B,QAhB5B,CAAY,EAiBZ,YAfU,CAAA,CAAc;AAGxB,KAeU,uBAAA,GAfV,QACA,mBACC,EAgBD,IACA,WAjB4B,GAkB3B,gBAjBW,EAiBO,SAdT,EAckB,QAdJ,GAexB,YAXA,CAAA;AACmB,KAaT,gBAAA,GAbS,QAAS,YAC5B,EAeA,EAfY,EAgBZ,WAbU,EAAuB,CAGjC,UAAA,EAAA,MAAA,EACA,QAAA,EAAA,MAAA,GAAA,SAAA,GAWA,YAVmB,CAAA;AACnB,KAYU,WAAA,GAZV,CAAY,OAAA,EAGF,KAAA,EAYV,EAZ0B,EAa1B,WAVA,GAGA,MAAA,CAAY,EASZ,YANU,CAAA,CAAW;AAGrB,KAKU,WAAA,GALV,QACA,OAEA,EAKA,EALY,EAMZ,WAJU,EAAW,CAGrB,MAA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EAAgB,GAAA,CAAA,EAAA,SAAA"}
import { Path } from "./types.cjs";
import { Mutation, SanityDocumentBase } from "./types2.cjs";
import { SanityMutation } from "./types3.cjs";
import { RawPatch } from "mendoza";
import { Observable } from "rxjs";
interface ListenerSyncEvent<Doc extends SanityDocumentBase = SanityDocumentBase> {
type: 'sync';
document: Doc | undefined;
}
interface ListenerMutationEvent {
type: 'mutation';
documentId: string;
transactionId: string;
resultRev?: string;
previousRev?: string;
effects?: {
apply: RawPatch;
};
mutations: SanityMutation[];
transition: 'update' | 'appear' | 'disappear';
}
interface ListenerReconnectEvent {
type: 'reconnect';
}
type ListenerChannelErrorEvent = {
type: 'channelError';
message: string;
};
type ListenerWelcomeEvent = {
type: 'welcome';
listenerName: string;
};
type ListenerDisconnectEvent = {
type: 'disconnect';
reason: string;
};
type ListenerEndpointEvent = ListenerWelcomeEvent | ListenerMutationEvent | ListenerReconnectEvent | ListenerChannelErrorEvent | ListenerDisconnectEvent;
type ListenerEvent<Doc extends SanityDocumentBase = SanityDocumentBase> = ListenerSyncEvent<Doc> | ListenerMutationEvent | ListenerReconnectEvent;
interface OptimisticDocumentEvent {
type: 'optimistic';
id: string;
before: SanityDocumentBase | undefined;
after: SanityDocumentBase | undefined;
mutations: Mutation[];
stagedChanges: Mutation[];
}
type QueryParams = Record<string, string | number | boolean | (string | number | boolean)[]>;
interface RemoteSyncEvent {
type: 'sync';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
rebasedStage: MutationGroup[];
}
interface RemoteMutationEvent {
type: 'mutation';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
effects?: {
apply: RawPatch;
};
previousRev?: string;
resultRev?: string;
mutations: Mutation[];
rebasedStage: MutationGroup[];
}
type RemoteDocumentEvent = RemoteSyncEvent | RemoteMutationEvent;
type DocumentMap<Doc extends SanityDocumentBase> = {
get(id: string): Doc | undefined;
set(id: string, doc: Doc | undefined): void;
delete(id: string): void;
};
interface MutationResult {}
interface SubmitResult {}
interface NonTransactionalMutationGroup {
transaction: false;
mutations: Mutation[];
}
interface TransactionalMutationGroup {
transaction: true;
id?: string;
mutations: Mutation[];
}
/**
* A mutation group represents an incoming, locally added group of mutations
* They can either be transactional or non-transactional
* - Transactional means that they must be submitted as a separate transaction (with an optional id) and no other mutations can be mixed with it
* – Non-transactional means that they can be combined with other mutations
*/
type MutationGroup = NonTransactionalMutationGroup | TransactionalMutationGroup;
type Conflict = {
path: Path;
error: Error;
base: SanityDocumentBase | undefined;
local: SanityDocumentBase | undefined;
};
interface OptimisticStore {
meta: {
/**
* A stream of events for anything that happens in the store
*/
events: Observable<OptimisticDocumentEvent | RemoteDocumentEvent>;
/**
* A stream of current staged changes
*/
stage: Observable<MutationGroup[]>;
/**
* A stream of current conflicts. TODO: Needs more work
*/
conflicts: Observable<Conflict[]>;
};
/**
* Applies the given mutations. Mutations are not guaranteed to be submitted in the same transaction
* Can this mutate both local and remote documents at the same time
*/
mutate(mutation: Mutation[]): MutationResult;
/**
* Makes sure the given mutations are posted in a single transaction
*/
transaction(transaction: {
id?: string;
mutations: Mutation[];
} | Mutation[]): MutationResult;
/**
* Checkout a document for editing. This is required to be able to see optimistic changes
*/
listen(id: string): Observable<SanityDocumentBase | undefined>;
/**
* Listen for events for a given document id
*/
listenEvents(id: string): Observable<RemoteDocumentEvent | OptimisticDocumentEvent>;
/**
* Optimize list of pending mutations
*/
optimize(): void;
/**
* Submit pending mutations
*/
submit(): Promise<SubmitResult[]>;
}
export { Conflict, DocumentMap, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MutationGroup, MutationResult, NonTransactionalMutationGroup, OptimisticDocumentEvent, OptimisticStore, QueryParams, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, SubmitResult, TransactionalMutationGroup };
//# sourceMappingURL=types4.d.cts.map
{"version":3,"file":"types4.d.cts","names":[],"sources":["../../src/store/types.ts"],"sourcesContent":[],"mappings":";;;;;UAOiB,8BACH,qBAAqB;EADlB,IAAA,EAAA,MAAA;EAAiB,QAAA,EAItB,GAJsB,GAAA,SAAA;;AACC,UAMlB,qBAAA,CANkB;MAGvB,EAAA,UAAA;EAAG,UAAA,EAAA,MAAA;EAGE,aAAA,EAAA,MAAA;EAAqB,SAAA,CAAA,EAAA,MAAA;aAMlB,CAAA,EAAA,MAAA;SACP,CAAA,EAAA;IAAc,KAAA,EADP,QACO;EAIV,CAAA;EAIL,SAAA,EARC,cAQD,EAAA;EAKA,UAAA,EAAA,QAAA,GAAoB,QAAA,GAAA,WAAA;AAKhC;AAIY,UAlBK,sBAAA,CAkBgB;EAAA,IAAA,EAAA,WAAA;;AAE7B,KAhBQ,yBAAA,GAgBR;MACA,EAAA,cAAA;SACA,EAAA,MAAA;;AACuB,KAdf,oBAAA,GAce;EAEf,IAAA,EAAA,SAAA;EAAa,YAAA,EAAA,MAAA;;AAAkC,KAX/C,uBAAA,GAW+C;MACvC,EAAA,YAAA;QAAlB,EAAA,MAAA;;AAAiD,KARvC,qBAAA,GACR,oBAO+C,GAN/C,qBAM+C,GAL/C,sBAK+C,GAJ/C,yBAI+C,GAH/C,uBAG+C;AAAsB,KAD7D,aAC6D,CAAA,YADnC,kBACmC,GADd,kBACc,CAAA,GAAvE,iBAAuE,CAArD,GAAqD,CAAA,GAA9C,qBAA8C,GAAtB,sBAAsB;AAExD,UAAA,uBAAA,CAAuB;EAAA,IAAA,EAAA,YAAA;MAG9B,MAAA;QACD,EADC,kBACD,GAAA,SAAA;OACI,EADJ,kBACI,GAAA,SAAA;WACI,EADJ,QACI,EAAA;EAAQ,aAAA,EAAR,QAAQ,EAAA;AAGzB;AAIiB,KAJL,WAAA,GAAc,MAIM,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AAA,EAAA,KAAA;EAGV,SAAA,EA1BJ,QA0BmB,EAAA;;AAMT,UA9BN,0BAAA,CA8BM;aAA0B,EAAA,IAAA;KAArC,EAAA,MAAA;WAKU,EAhCT,QAgCS,EAAA;;;;;;;;AAmBjB,KA1CO,aAAA,GACR,6BAyCC,GAxCD,0BAwCC;AAK4B,KA1CrB,QAAA,GA0CqB;MAAX,EAzCd,IAyCc;OAON,EA/CP,KA+CO;MAAsB,EA9C9B,kBA8C8B,GAAA,SAAA;OAAjC,EA7CI,kBA6CJ,GAAA,SAAA;;AAUO,UApDK,eAAA,CAoDL;EAAO,IAAA,EAAA;;;;YA9CP,WAAW,0BAA0B;;;;WAKtC,WAAW;;;;eAKP,WAAW;;;;;;mBAOP,aAAa;;;;;;eAMU;MAAc,aACnD;;;;sBAKiB,WAAW;;;;4BAO5B,WAAW,sBAAsB;;;;;;;;YAU1B,QAAQ"}
import { Path } from "./types.js";
import { Mutation, SanityDocumentBase } from "./types2.js";
import { SanityMutation } from "./types3.js";
import { RawPatch } from "mendoza";
import { Observable } from "rxjs";
interface ListenerSyncEvent<Doc extends SanityDocumentBase = SanityDocumentBase> {
type: 'sync';
document: Doc | undefined;
}
interface ListenerMutationEvent {
type: 'mutation';
documentId: string;
transactionId: string;
resultRev?: string;
previousRev?: string;
effects?: {
apply: RawPatch;
};
mutations: SanityMutation[];
transition: 'update' | 'appear' | 'disappear';
}
interface ListenerReconnectEvent {
type: 'reconnect';
}
type ListenerChannelErrorEvent = {
type: 'channelError';
message: string;
};
type ListenerWelcomeEvent = {
type: 'welcome';
listenerName: string;
};
type ListenerDisconnectEvent = {
type: 'disconnect';
reason: string;
};
type ListenerEndpointEvent = ListenerWelcomeEvent | ListenerMutationEvent | ListenerReconnectEvent | ListenerChannelErrorEvent | ListenerDisconnectEvent;
type ListenerEvent<Doc extends SanityDocumentBase = SanityDocumentBase> = ListenerSyncEvent<Doc> | ListenerMutationEvent | ListenerReconnectEvent;
interface OptimisticDocumentEvent {
type: 'optimistic';
id: string;
before: SanityDocumentBase | undefined;
after: SanityDocumentBase | undefined;
mutations: Mutation[];
stagedChanges: Mutation[];
}
type QueryParams = Record<string, string | number | boolean | (string | number | boolean)[]>;
interface RemoteSyncEvent {
type: 'sync';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
rebasedStage: MutationGroup[];
}
interface RemoteMutationEvent {
type: 'mutation';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
effects?: {
apply: RawPatch;
};
previousRev?: string;
resultRev?: string;
mutations: Mutation[];
rebasedStage: MutationGroup[];
}
type RemoteDocumentEvent = RemoteSyncEvent | RemoteMutationEvent;
type DocumentMap<Doc extends SanityDocumentBase> = {
get(id: string): Doc | undefined;
set(id: string, doc: Doc | undefined): void;
delete(id: string): void;
};
interface MutationResult {}
interface SubmitResult {}
interface NonTransactionalMutationGroup {
transaction: false;
mutations: Mutation[];
}
interface TransactionalMutationGroup {
transaction: true;
id?: string;
mutations: Mutation[];
}
/**
* A mutation group represents an incoming, locally added group of mutations
* They can either be transactional or non-transactional
* - Transactional means that they must be submitted as a separate transaction (with an optional id) and no other mutations can be mixed with it
* – Non-transactional means that they can be combined with other mutations
*/
type MutationGroup = NonTransactionalMutationGroup | TransactionalMutationGroup;
type Conflict = {
path: Path;
error: Error;
base: SanityDocumentBase | undefined;
local: SanityDocumentBase | undefined;
};
interface OptimisticStore {
meta: {
/**
* A stream of events for anything that happens in the store
*/
events: Observable<OptimisticDocumentEvent | RemoteDocumentEvent>;
/**
* A stream of current staged changes
*/
stage: Observable<MutationGroup[]>;
/**
* A stream of current conflicts. TODO: Needs more work
*/
conflicts: Observable<Conflict[]>;
};
/**
* Applies the given mutations. Mutations are not guaranteed to be submitted in the same transaction
* Can this mutate both local and remote documents at the same time
*/
mutate(mutation: Mutation[]): MutationResult;
/**
* Makes sure the given mutations are posted in a single transaction
*/
transaction(transaction: {
id?: string;
mutations: Mutation[];
} | Mutation[]): MutationResult;
/**
* Checkout a document for editing. This is required to be able to see optimistic changes
*/
listen(id: string): Observable<SanityDocumentBase | undefined>;
/**
* Listen for events for a given document id
*/
listenEvents(id: string): Observable<RemoteDocumentEvent | OptimisticDocumentEvent>;
/**
* Optimize list of pending mutations
*/
optimize(): void;
/**
* Submit pending mutations
*/
submit(): Promise<SubmitResult[]>;
}
export { Conflict, DocumentMap, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MutationGroup, MutationResult, NonTransactionalMutationGroup, OptimisticDocumentEvent, OptimisticStore, QueryParams, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, SubmitResult, TransactionalMutationGroup };
//# sourceMappingURL=types4.d.ts.map
{"version":3,"file":"types4.d.ts","names":[],"sources":["../../src/store/types.ts"],"sourcesContent":[],"mappings":";;;;;UAOiB,8BACH,qBAAqB;EADlB,IAAA,EAAA,MAAA;EAAiB,QAAA,EAItB,GAJsB,GAAA,SAAA;;AACC,UAMlB,qBAAA,CANkB;MAGvB,EAAA,UAAA;EAAG,UAAA,EAAA,MAAA;EAGE,aAAA,EAAA,MAAA;EAAqB,SAAA,CAAA,EAAA,MAAA;aAMlB,CAAA,EAAA,MAAA;SACP,CAAA,EAAA;IAAc,KAAA,EADP,QACO;EAIV,CAAA;EAIL,SAAA,EARC,cAQD,EAAA;EAKA,UAAA,EAAA,QAAA,GAAoB,QAAA,GAAA,WAAA;AAKhC;AAIY,UAlBK,sBAAA,CAkBgB;EAAA,IAAA,EAAA,WAAA;;AAE7B,KAhBQ,yBAAA,GAgBR;MACA,EAAA,cAAA;SACA,EAAA,MAAA;;AACuB,KAdf,oBAAA,GAce;EAEf,IAAA,EAAA,SAAA;EAAa,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T,SAAA,CAAA,EAAA,MAAc;EAGd,SAAA,EAfJ,QAegB,EAAA;EAEZ,YAAA,EAhBD,aAgBC,EAAA;AAIjB;AAYY,KA9BA,mBAAA,GAAsB,eA8BT,GA9B2B,mBA8B3B;AAAA,KA5Bb,WA4Ba,CAAA,YA5BW,kBA4BX,CAAA,GAAA;KACrB,CAAA,EAAA,EAAA,MAAA,CAAA,EA5Be,GA4Bf,GAAA,SAAA;KACA,CAAA,EAAA,EAAA,MAAA,EAAA,GAAA,EA5BmB,GA4BnB,GAAA,SAAA,CAAA,EAAA,IAAA;EAA0B,MAAA,CAAA,EAAA,EAAA,MAAA,CAAA,EAAA,IAAA;AAG9B,CAAA;AAAoB,UA1BH,cAAA,CA0BG;AAEX,UAzBQ,YAAA,CAyBR;AAEA,UAzBQ,6BAAA,CAyBR;EAAkB,WAAA,EAAA,KAAA;EAGV,SAAA,EA1BJ,QA0BmB,EAAA;;AAMT,UA9BN,0BAAA,CA8BM;aAA0B,EAAA,IAAA;KAArC,EAAA,MAAA;WAKU,EAhCT,QAgCS,EAAA;;;;;;;;AAmBjB,KA1CO,aAAA,GACR,6BAyCC,GAxCD,0BAwCC;AAK4B,KA1CrB,QAAA,GA0CqB;MAAX,EAzCd,IAyCc;OAON,EA/CP,KA+CO;MAAsB,EA9C9B,kBA8C8B,GAAA,SAAA;OAAjC,EA7CI,kBA6CJ,GAAA,SAAA;;AAUO,UApDK,eAAA,CAoDL;EAAO,IAAA,EAAA;;;;YA9CP,WAAW,0BAA0B;;;;WAKtC,WAAW;;;;eAKP,WAAW;;;;;;mBAOP,aAAa;;;;;;eAMU;MAAc,aACnD;;;;sBAKiB,WAAW;;;;4BAO5B,WAAW,sBAAsB;;;;;;;;YAU1B,QAAQ"}
import { finalize, share, timer, ReplaySubject, Subject, EMPTY, merge, lastValueFrom, from, concatMap, toArray, map, defer, filter, mergeMap, of, tap } from "rxjs";
import { decodeAll } from "./encode.js";
import { nanoid } from "nanoid";
import { assignId, hasId, applyPatchMutation, applyNodePatch, applyPatches } from "./utils.js";
import { applyPatch } from "mendoza";
import { uuid } from "@sanity/uuid";
import { stringifyPatches, makePatches } from "@sanity/diff-match-patch";
import { getAtPath } from "./getAtPath.js";
import { stringify, startsWith } from "./stringify.js";
import groupBy from "lodash/groupBy.js";
function getMutationDocumentId(mutation) {
if (mutation.type === "patch")
return mutation.id;
if (mutation.type === "create")
return mutation.document._id;
if (mutation.type === "delete")
return mutation.id;
if (mutation.type === "createIfNotExists" || mutation.type === "createOrReplace")
return mutation.document._id;
throw new Error("Invalid mutation type");
}
function applyAll(current, mutation) {
return mutation.reduce((doc, m) => {
const res = applyDocumentMutation(doc, m);
if (res.status === "error")
throw new Error(res.message);
return res.status === "noop" ? doc : res.after;
}, current);
}
function applyDocumentMutation(document, mutation) {
if (mutation.type === "create")
return create(document, mutation);
if (mutation.type === "createIfNotExists")
return createIfNotExists(document, mutation);
if (mutation.type === "delete")
return del(document, mutation);
if (mutation.type === "createOrReplace")
return createOrReplace(document, mutation);
if (mutation.type === "patch")
return patch(document, mutation);
throw new Error(`Invalid mutation type: ${mutation.type}`);
}
function create(document, mutation) {
if (document)
return { status: "error", message: "Document already exist" };
const result = assignId(mutation.document, nanoid);
return { status: "created", id: result._id, after: result };
}
function createIfNotExists(document, mutation) {
return hasId(mutation.document) ? document ? { status: "noop" } : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function createOrReplace(document, mutation) {
return hasId(mutation.document) ? document ? {
status: "updated",
id: mutation.document._id,
before: document,
after: mutation.document
} : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function del(document, mutation) {
return document ? mutation.id !== document._id ? { status: "error", message: "Delete mutation targeted wrong document" } : {
status: "deleted",
id: mutation.id,
before: document,
after: void 0
} : { status: "noop" };
}
function patch(document, mutation) {
if (!document)
return {
status: "error",
message: "Cannot apply patch on nonexistent document"
};
const next = applyPatchMutation(mutation, document);
return document === next ? { status: "noop" } : { status: "updated", id: mutation.id, before: document, after: next };
}
function applyMutations(mutations, documentMap, transactionId) {
const updatedDocs = /* @__PURE__ */ Object.create(null);
for (const mutation of mutations) {
const documentId = getMutationDocumentId(mutation);
if (!documentId)
throw new Error("Unable to get document id from mutation");
const before = updatedDocs[documentId]?.after || documentMap.get(documentId), res = applyDocumentMutation(before, mutation);
if (res.status === "error")
throw new Error(res.message);
let entry = updatedDocs[documentId];
entry || (entry = { before, after: before, mutations: [] }, updatedDocs[documentId] = entry);
const after = transactionId ? { ...res.status === "noop" ? before : res.after, _rev: transactionId } : res.status === "noop" ? before : res.after;
documentMap.set(documentId, after), entry.after = after, entry.mutations.push(mutation);
}
return Object.entries(updatedDocs).map(
([id, { before, after, mutations: muts }]) => ({
id,
status: after ? before ? "updated" : "created" : "deleted",
mutations: muts,
before,
after
})
);
}
function commit(results, documentMap) {
results.forEach((result) => {
(result.status === "created" || result.status === "updated") && documentMap.set(result.id, result.after), result.status === "deleted" && documentMap.delete(result.id);
});
}
function takeUntilRight(arr, predicate, opts) {
const result = [];
for (const item of arr.slice().reverse()) {
if (predicate(item))
return result;
result.push(item);
}
return result.reverse();
}
function isEqualPath(p1, p2) {
return stringify(p1) === stringify(p2);
}
function supersedes(later, earlier) {
return (earlier.type === "set" || earlier.type === "unset") && (later.type === "set" || later.type === "unset");
}
function squashNodePatches(patches) {
return compactSetIfMissingPatches(
compactSetPatches(compactUnsetPatches(patches))
);
}
function compactUnsetPatches(patches) {
return patches.reduce(
(earlierPatches, laterPatch) => {
if (laterPatch.op.type !== "unset")
return earlierPatches.push(laterPatch), earlierPatches;
const unaffected = earlierPatches.filter(
(earlierPatch) => !startsWith(laterPatch.path, earlierPatch.path)
);
return unaffected.push(laterPatch), unaffected;
},
[]
);
}
function compactSetPatches(patches) {
return patches.reduceRight(
(laterPatches, earlierPatch) => (laterPatches.find(
(later) => supersedes(later.op, earlierPatch.op) && isEqualPath(later.path, earlierPatch.path)
) || laterPatches.unshift(earlierPatch), laterPatches),
[]
);
}
function compactSetIfMissingPatches(patches) {
return patches.reduce(
(previousPatches, laterPatch) => laterPatch.op.type !== "setIfMissing" ? (previousPatches.push(laterPatch), previousPatches) : (takeUntilRight(
previousPatches,
(patch2) => patch2.op.type === "unset"
).find(
(precedingPatch) => precedingPatch.op.type === "setIfMissing" && isEqualPath(precedingPatch.path, laterPatch.path)
) || previousPatches.push(laterPatch), previousPatches),
[]
);
}
function compactDMPSetPatches(base, patches) {
let edge = base;
return patches.reduce(
(earlierPatches, laterPatch) => {
const before = edge;
if (edge = applyNodePatch(laterPatch, edge), laterPatch.op.type === "set" && typeof laterPatch.op.value == "string") {
const current = getAtPath(laterPatch.path, before);
if (typeof current == "string") {
const replaced = {
...laterPatch,
op: {
type: "diffMatchPatch",
value: stringifyPatches(
makePatches(current, laterPatch.op.value)
)
}
};
return earlierPatches.flatMap((ep) => isEqualPath(ep.path, laterPatch.path) && ep.op.type === "diffMatchPatch" ? [] : ep).concat(replaced);
}
}
return earlierPatches.push(laterPatch), earlierPatches;
},
[]
);
}
function squashDMPStrings(base, mutationGroups) {
return mutationGroups.map((mutationGroup) => ({
...mutationGroup,
mutations: dmpIfyMutations(base, mutationGroup.mutations)
}));
}
function dmpIfyMutations(store, mutations) {
return mutations.map((mutation, i) => {
if (mutation.type !== "patch")
return mutation;
const base = store.get(mutation.id);
return base ? dmpifyPatchMutation(base, mutation) : mutation;
});
}
function dmpifyPatchMutation(base, mutation) {
return {
...mutation,
patches: compactDMPSetPatches(base, mutation.patches)
};
}
function rebase(documentId, oldBase, newBase, localMutations) {
let edge = oldBase;
const dmpified = localMutations.map((transaction) => {
const mutations = transaction.mutations.flatMap((mut) => {
if (getMutationDocumentId(mut) !== documentId)
return [];
const before = edge;
return edge = applyAll(edge, [mut]), !before || mut.type !== "patch" ? mut : {
type: "dmpified",
mutation: {
...mut,
// Todo: make compactDMPSetPatches return pairs of patches that was dmpified with their
// original as dmpPatches and original is not 1:1 (e..g some of the original may not be dmpified)
dmpPatches: compactDMPSetPatches(before, mut.patches),
original: mut.patches
}
};
});
return { ...transaction, mutations };
});
let newBaseWithDMPForOldBaseApplied = newBase;
return dmpified.map((transaction) => {
const applied = [];
return transaction.mutations.forEach((mut) => {
if (mut.type === "dmpified")
try {
newBaseWithDMPForOldBaseApplied = applyPatches(
mut.mutation.dmpPatches,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch {
console.warn("Failed to apply dmp patch, falling back to original");
try {
newBaseWithDMPForOldBaseApplied = applyPatches(
mut.mutation.original,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch (second) {
throw new Error(
`Failed to apply patch for document "${documentId}": ${second.message}`
);
}
}
else
newBaseWithDMPForOldBaseApplied = applyAll(
newBaseWithDMPForOldBaseApplied,
[mut]
);
});
}), [localMutations.map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mut) => mut.type !== "patch" || getMutationDocumentId(mut) !== documentId ? mut : {
...mut,
patches: mut.patches.map((patch2) => patch2.op.type !== "set" ? patch2 : {
...patch2,
op: {
...patch2.op,
value: getAtPath(patch2.path, newBaseWithDMPForOldBaseApplied)
}
})
})
})), newBaseWithDMPForOldBaseApplied];
}
function mergeMutationGroups(mutationGroups) {
return chunkWhile(mutationGroups, (group) => !group.transaction).flatMap(
(chunk) => ({
...chunk[0],
mutations: chunk.flatMap((c) => c.mutations)
})
);
}
function chunkWhile(arr, predicate) {
const res = [];
let currentChunk = [];
return arr.forEach((item) => {
predicate(item) ? currentChunk.push(item) : (currentChunk.length > 0 && res.push(currentChunk), currentChunk = [], res.push([item]));
}), currentChunk.length > 0 && res.push(currentChunk), res;
}
function squashMutationGroups(staged) {
return mergeMutationGroups(staged).map((transaction) => ({
...transaction,
mutations: squashMutations(transaction.mutations)
})).map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mutation) => mutation.type !== "patch" ? mutation : {
...mutation,
patches: squashNodePatches(mutation.patches)
})
}));
}
function squashMutations(mutations) {
const byDocument = groupBy(mutations, getMutationDocumentId);
return Object.values(byDocument).flatMap((documentMutations) => squashCreateIfNotExists(squashDelete(documentMutations)).flat().reduce((acc, docMutation) => {
const prev = acc[acc.length - 1];
return (!prev || prev.type === "patch") && docMutation.type === "patch" ? acc.slice(0, -1).concat({
...docMutation,
patches: (prev?.patches || []).concat(docMutation.patches)
}) : acc.concat(docMutation);
}, []));
}
function squashCreateIfNotExists(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type !== "createIfNotExists" ? (previousMuts.push(laterMut), previousMuts) : (takeUntilRight(previousMuts, (m) => m.type === "delete").find(
(precedingPatch) => precedingPatch.type === "createIfNotExists"
) || previousMuts.push(laterMut), previousMuts), []);
}
function squashDelete(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type === "delete" ? [laterMut] : (previousMuts.push(laterMut), previousMuts), []);
}
function omitRev(document) {
if (document === void 0)
return;
const { _rev, ...doc } = document;
return doc;
}
function applyMendozaPatch(document, patch2, patchBaseRev) {
if (patchBaseRev !== document?._rev)
throw new Error(
"Invalid document revision. The provided patch is calculated from a different revision than the current document"
);
const next = applyPatch(omitRev(document), patch2);
return next === null ? void 0 : next;
}
function applyMutationEventEffects(document, event) {
if (!event.effects)
throw new Error(
"Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?"
);
const next = applyMendozaPatch(
document,
event.effects.apply,
event.previousRev
);
return next ? { ...next, _rev: event.resultRev } : void 0;
}
function createDocumentMap() {
const documents = /* @__PURE__ */ new Map();
return {
set: (id, doc) => void documents.set(id, doc),
get: (id) => documents.get(id),
delete: (id) => documents.delete(id)
};
}
function createReplayMemoizer(expiry) {
const memo = /* @__PURE__ */ Object.create(null);
return function(key, observable) {
return key in memo || (memo[key] = observable.pipe(
finalize(() => {
delete memo[key];
}),
share({
connector: () => new ReplaySubject(1),
resetOnRefCountZero: () => timer(expiry)
})
)), memo[key];
};
}
function createTransactionId() {
return uuid();
}
function filterMutationGroupsById(mutationGroups, id) {
return mutationGroups.flatMap(
(mutationGroup) => mutationGroup.mutations.flatMap(
(mut) => getMutationDocumentId(mut) === id ? [mut] : []
)
);
}
function hasProperty(value, property) {
const val = value[property];
return typeof val < "u" && val !== null;
}
let didEmitMutationsAccessWarning = !1;
function warnNoMutationsReceived() {
didEmitMutationsAccessWarning || (console.warn(
new Error(
"No mutation received from backend. The listener is likely set up with `excludeMutations: true`. If your app need to know about mutations, make sure the listener is set up to include mutations"
)
), didEmitMutationsAccessWarning = !0);
}
const EMPTY_ARRAY = [];
function createOptimisticStore(backend) {
const local = createDocumentMap(), remote = createDocumentMap(), memoize = createReplayMemoizer(1e3);
let stagedChanges = [];
const remoteEvents$ = new Subject(), localMutations$ = new Subject(), stage$ = new Subject();
function setStaged(nextPending) {
stagedChanges = nextPending, stage$.next();
}
function getLocalEvents(id) {
return localMutations$.pipe(filter((event) => event.id === id));
}
function getRemoteEvents(id) {
return backend.listen(id).pipe(
filter(
(event) => event.type !== "reconnect"
),
mergeMap((event) => {
const oldLocal = local.get(id), oldRemote = remote.get(id);
if (event.type === "sync") {
const newRemote = event.document, [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
return of({
type: "sync",
id,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
rebasedStage
});
} else if (event.type === "mutation") {
if (event.transactionId === oldRemote?._rev)
return EMPTY;
let newRemote;
if (hasProperty(event, "effects"))
newRemote = applyMutationEventEffects(oldRemote, event);
else if (hasProperty(event, "mutations"))
newRemote = applyAll(oldRemote, decodeAll(event.mutations));
else
throw new Error(
"Neither effects or mutations found on listener event"
);
const [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
newLocal && (newLocal._rev = event.transactionId);
const emittedEvent = {
type: "mutation",
id,
rebasedStage,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
effects: event.effects,
previousRev: event.previousRev,
resultRev: event.resultRev,
// overwritten below
mutations: EMPTY_ARRAY
};
return event.mutations ? emittedEvent.mutations = decodeAll(
event.mutations
) : Object.defineProperty(
emittedEvent,
"mutations",
warnNoMutationsReceived
), of(emittedEvent);
} else
throw new Error(`Unknown event type: ${event.type}`);
}),
tap((event) => {
local.set(event.id, event.after.local), remote.set(event.id, event.after.remote), setStaged(event.rebasedStage);
}),
tap({
next: (event) => remoteEvents$.next(event),
error: (err) => {
}
})
);
}
function listenEvents(id) {
return defer(
() => memoize(id, merge(getLocalEvents(id), getRemoteEvents(id)))
);
}
return {
meta: {
events: merge(localMutations$, remoteEvents$),
stage: stage$.pipe(
map(
() => (
// note: this should not be tampered with by consumers. We might want to do a deep-freeze during dev to avoid accidental mutations
stagedChanges
)
)
),
conflicts: EMPTY
// does nothing for now
},
mutate: (mutations) => {
stagedChanges.push({ transaction: !1, mutations });
const results = applyMutations(mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
before: result.before,
after: result.after,
mutations: result.mutations,
id: result.id,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
transaction: (mutationsOrTransaction) => {
const transaction = Array.isArray(
mutationsOrTransaction
) ? { mutations: mutationsOrTransaction, transaction: !0 } : { ...mutationsOrTransaction, transaction: !0 };
stagedChanges.push(transaction);
const results = applyMutations(transaction.mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
mutations: result.mutations,
id: result.id,
before: result.before,
after: result.after,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
listenEvents,
listen: (id) => listenEvents(id).pipe(
map(
(event) => event.type === "optimistic" ? event.after : event.after.local
)
),
optimize: () => {
setStaged(squashMutationGroups(stagedChanges));
},
submit: () => {
const pending = stagedChanges;
return setStaged([]), lastValueFrom(
from(
toTransactions(
// Squashing DMP strings is the last thing we do before submitting
squashDMPStrings(remote, squashMutationGroups(pending))
)
).pipe(
concatMap((mut) => backend.submit(mut)),
toArray()
)
);
}
};
}
function toTransactions(groups) {
return groups.map((group) => group.transaction && group.id !== void 0 ? { id: group.id, mutations: group.mutations } : { id: createTransactionId(), mutations: group.mutations });
}
export {
applyAll,
applyMutationEventEffects,
applyMutations,
commit,
createDocumentMap,
createOptimisticStore,
createTransactionId,
hasProperty,
rebase,
squashDMPStrings,
squashMutationGroups,
toTransactions
};
//# sourceMappingURL=createOptimisticStore.js.map
{"version":3,"file":"createOptimisticStore.js","sources":["../../src/store/utils/getMutationDocumentId.ts","../../src/store/documentMap/applyDocumentMutation.ts","../../src/store/documentMap/applyMutations.ts","../../src/store/documentMap/commit.ts","../../src/store/utils/arrayUtils.ts","../../src/store/optimistic/optimizations/squashNodePatches.ts","../../src/store/optimistic/optimizations/squashDMPStrings.ts","../../src/store/optimistic/rebase.ts","../../src/store/utils/mergeMutationGroups.ts","../../src/store/optimistic/optimizations/squashMutations.ts","../../src/store/documentMap/applyMendoza.ts","../../src/store/documentMap/createDocumentMap.ts","../../src/store/utils/createReplayMemoizer.ts","../../src/store/utils/createTransactionId.ts","../../src/store/utils/filterMutationGroups.ts","../../src/store/utils/isEffectEvent.ts","../../src/store/optimistic/createOptimisticStore.ts"],"sourcesContent":["type MutationLike =\n | {type: 'patch'; id: string}\n | {type: 'create'; document: {_id: string}}\n | {type: 'delete'; id: string}\n | {type: 'createIfNotExists'; document: {_id: string}}\n | {type: 'createOrReplace'; document: {_id: string}}\n\nexport function getMutationDocumentId(mutation: MutationLike): string {\n if (mutation.type === 'patch') {\n return mutation.id\n }\n if (mutation.type === 'create') {\n return mutation.document._id\n }\n if (mutation.type === 'delete') {\n return mutation.id\n }\n if (mutation.type === 'createIfNotExists') {\n return mutation.document._id\n }\n if (mutation.type === 'createOrReplace') {\n return mutation.document._id\n }\n throw new Error('Invalid mutation type')\n}\n","import {nanoid} from 'nanoid'\n\nimport {applyPatchMutation, assignId, hasId} from '../../apply'\nimport {\n type CreateIfNotExistsMutation,\n type CreateMutation,\n type CreateOrReplaceMutation,\n type DeleteMutation,\n type Mutation,\n type PatchMutation,\n type SanityDocumentBase,\n} from '../../mutations/types'\n\nexport type MutationResult<Doc extends SanityDocumentBase> =\n | {\n id: string\n status: 'created'\n after: Doc\n }\n | {\n id: string\n status: 'updated'\n before: Doc\n after: Doc\n }\n | {\n id: string\n status: 'deleted'\n before: Doc | undefined\n after: undefined\n }\n | {\n status: 'error'\n message: string\n }\n | {\n status: 'noop'\n }\n\n/**\n * Applies a set of mutations to the provided document\n * @param current\n * @param mutation\n */\nexport function applyAll<Doc extends SanityDocumentBase>(\n current: Doc | undefined,\n mutation: Mutation<Doc>[],\n): Doc | undefined {\n return mutation.reduce((doc, m) => {\n const res = applyDocumentMutation(doc, m)\n if (res.status === 'error') {\n throw new Error(res.message)\n }\n return res.status === 'noop' ? doc : res.after\n }, current)\n}\n\n/**\n * Applies a mutation to the provided document\n * @param document\n * @param mutation\n */\nexport function applyDocumentMutation<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: Mutation<Doc>,\n): MutationResult<Doc> {\n if (mutation.type === 'create') {\n return create(document, mutation)\n }\n if (mutation.type === 'createIfNotExists') {\n return createIfNotExists(document, mutation)\n }\n if (mutation.type === 'delete') {\n return del(document, mutation)\n }\n if (mutation.type === 'createOrReplace') {\n return createOrReplace(document, mutation)\n }\n if (mutation.type === 'patch') {\n return patch(document, mutation)\n }\n // @ts-expect-error all cases should be covered\n throw new Error(`Invalid mutation type: ${mutation.type}`)\n}\n\nfunction create<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: CreateMutation<Doc>,\n): MutationResult<Doc> {\n if (document) {\n return {status: 'error', message: 'Document already exist'}\n }\n const result = assignId(mutation.document, nanoid)\n return {status: 'created', id: result._id, after: result}\n}\n\nfunction createIfNotExists<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: CreateIfNotExistsMutation<Doc>,\n): MutationResult<Doc> {\n if (!hasId(mutation.document)) {\n return {\n status: 'error',\n message: 'Cannot createIfNotExists on document without _id',\n }\n }\n return document\n ? {status: 'noop'}\n : {status: 'created', id: mutation.document._id, after: mutation.document}\n}\n\nfunction createOrReplace<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: CreateOrReplaceMutation<Doc>,\n): MutationResult<Doc> {\n if (!hasId(mutation.document)) {\n return {\n status: 'error',\n message: 'Cannot createIfNotExists on document without _id',\n }\n }\n\n return document\n ? {\n status: 'updated',\n id: mutation.document._id,\n before: document,\n after: mutation.document,\n }\n : {status: 'created', id: mutation.document._id, after: mutation.document}\n}\n\nfunction del<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: DeleteMutation,\n): MutationResult<Doc> {\n if (!document) {\n return {status: 'noop'}\n }\n if (mutation.id !== document._id) {\n return {status: 'error', message: 'Delete mutation targeted wrong document'}\n }\n return {\n status: 'deleted',\n id: mutation.id,\n before: document,\n after: undefined,\n }\n}\n\nfunction patch<Doc extends SanityDocumentBase>(\n document: Doc | undefined,\n mutation: PatchMutation,\n): MutationResult<Doc> {\n if (!document) {\n return {\n status: 'error',\n message: 'Cannot apply patch on nonexistent document',\n }\n }\n const next = applyPatchMutation(mutation, document)\n return document === next\n ? {status: 'noop'}\n : {status: 'updated', id: mutation.id, before: document, after: next}\n}\n","import {type Mutation, type SanityDocumentBase} from '../../mutations/types'\nimport {type DocumentMap} from '../types'\nimport {getMutationDocumentId} from '../utils/getMutationDocumentId'\nimport {applyDocumentMutation} from './applyDocumentMutation'\n\nexport interface UpdateResult<T extends SanityDocumentBase> {\n id: string\n status: 'created' | 'updated' | 'deleted'\n before?: T\n after?: T\n mutations: Mutation[]\n}\n\n/**\n * Takes a list of mutations and applies them to documents in a documentMap\n */\nexport function applyMutations<T extends SanityDocumentBase>(\n mutations: Mutation[],\n documentMap: DocumentMap<T>,\n /**\n * note: should never be set client side – only for test purposes\n */\n transactionId?: never,\n): UpdateResult<T>[] {\n const updatedDocs: Record<\n string,\n {\n before: T | undefined\n after: T | undefined\n mutations: Mutation[]\n }\n > = Object.create(null)\n\n for (const mutation of mutations) {\n const documentId = getMutationDocumentId(mutation)\n if (!documentId) {\n throw new Error('Unable to get document id from mutation')\n }\n\n const before = updatedDocs[documentId]?.after || documentMap.get(documentId)\n const res = applyDocumentMutation(before, mutation)\n if (res.status === 'error') {\n throw new Error(res.message)\n }\n\n let entry = updatedDocs[documentId]\n if (!entry) {\n entry = {before, after: before, mutations: []}\n updatedDocs[documentId] = entry\n }\n\n // Note: transactionId should never be set client side. Only for test purposes\n // if a transaction id is passed, set it as a new _rev\n const after = transactionId\n ? {...(res.status === 'noop' ? before : res.after), _rev: transactionId}\n : res.status === 'noop'\n ? before\n : res.after\n\n documentMap.set(documentId, after)\n entry.after = after\n entry.mutations.push(mutation)\n }\n\n return Object.entries(updatedDocs).map(\n ([id, {before, after, mutations: muts}]) => {\n return {\n id,\n status: after ? (before ? 'updated' : 'created') : 'deleted',\n mutations: muts,\n before,\n after,\n }\n },\n )\n}\n","import {type SanityDocumentBase} from '../../mutations/types'\nimport {type DocumentMap} from '../types'\nimport {type UpdateResult} from './applyMutations'\n\nexport function commit<Doc extends SanityDocumentBase>(\n results: UpdateResult<Doc>[],\n documentMap: DocumentMap<Doc>,\n) {\n results.forEach(result => {\n if (result.status === 'created' || result.status === 'updated') {\n documentMap.set(result.id, result.after)\n }\n if (result.status === 'deleted') {\n documentMap.delete(result.id)\n }\n })\n}\n","export function takeUntil<T>(\n arr: T[],\n predicate: (item: T) => boolean,\n opts?: {inclusive: boolean},\n) {\n const result = []\n for (const item of arr) {\n if (predicate(item)) {\n if (opts?.inclusive) {\n result.push(item)\n }\n return result\n }\n result.push(item)\n }\n return result\n}\n\nexport function takeUntilRight<T>(\n arr: T[],\n predicate: (item: T) => boolean,\n opts?: {inclusive: boolean},\n) {\n const result = []\n for (const item of arr.slice().reverse()) {\n if (predicate(item)) {\n if (opts?.inclusive) {\n result.push(item)\n }\n return result\n }\n result.push(item)\n }\n return result.reverse()\n}\n","import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'\n\nimport {applyNodePatch} from '../../../apply'\nimport {type Operation} from '../../../mutations/operations/types'\nimport {type NodePatch, type SanityDocumentBase} from '../../../mutations/types'\nimport {getAtPath, type Path, startsWith, stringify} from '../../../path'\nimport {takeUntilRight} from '../../utils/arrayUtils'\n\nfunction isEqualPath(p1: Path, p2: Path) {\n return stringify(p1) === stringify(p2)\n}\n\nfunction supersedes(later: Operation, earlier: Operation) {\n return (\n (earlier.type === 'set' || earlier.type === 'unset') &&\n (later.type === 'set' || later.type === 'unset')\n )\n}\n\nexport function squashNodePatches(patches: NodePatch[]) {\n return compactSetIfMissingPatches(\n compactSetPatches(compactUnsetPatches(patches)),\n )\n}\n\nexport function compactUnsetPatches(patches: NodePatch[]) {\n return patches.reduce(\n (earlierPatches: NodePatch[], laterPatch: NodePatch) => {\n if (laterPatch.op.type !== 'unset') {\n earlierPatches.push(laterPatch)\n return earlierPatches\n }\n // find all preceding patches that are affected by this unset\n const unaffected = earlierPatches.filter(\n earlierPatch => !startsWith(laterPatch.path, earlierPatch.path),\n )\n unaffected.push(laterPatch)\n return unaffected\n },\n [],\n )\n}\n\nexport function compactSetPatches(patches: NodePatch[]) {\n return patches.reduceRight(\n (laterPatches: NodePatch[], earlierPatch: NodePatch) => {\n const replacement = laterPatches.find(\n later =>\n supersedes(later.op, earlierPatch.op) &&\n isEqualPath(later.path, earlierPatch.path),\n )\n if (replacement) {\n // we already have another patch later in the chain that replaces this one\n return laterPatches\n }\n laterPatches.unshift(earlierPatch)\n return laterPatches\n },\n [],\n )\n}\n\nexport function compactSetIfMissingPatches(patches: NodePatch[]) {\n return patches.reduce(\n (previousPatches: NodePatch[], laterPatch: NodePatch) => {\n if (laterPatch.op.type !== 'setIfMissing') {\n previousPatches.push(laterPatch)\n return previousPatches\n }\n // look at preceding patches up until the first unset\n const check = takeUntilRight(\n previousPatches,\n patch => patch.op.type === 'unset',\n )\n const precedent = check.find(\n precedingPatch =>\n precedingPatch.op.type === 'setIfMissing' &&\n isEqualPath(precedingPatch.path, laterPatch.path),\n )\n if (precedent) {\n // we already have an identical patch earlier in the chain that voids this one\n return previousPatches\n }\n previousPatches.push(laterPatch)\n return previousPatches\n },\n [],\n )\n}\n\nexport function compactDMPSetPatches(\n base: SanityDocumentBase,\n patches: NodePatch[],\n) {\n let edge = base\n return patches.reduce(\n (earlierPatches: NodePatch[], laterPatch: NodePatch) => {\n const before = edge\n edge = applyNodePatch(laterPatch, edge)\n if (\n laterPatch.op.type === 'set' &&\n typeof laterPatch.op.value === 'string'\n ) {\n const current = getAtPath(laterPatch.path, before)\n if (typeof current === 'string') {\n // we can replace the earlier diffMatchPatches with a new one\n const replaced: NodePatch = {\n ...laterPatch,\n op: {\n type: 'diffMatchPatch',\n value: stringifyPatches(\n makePatches(current, laterPatch.op.value),\n ),\n },\n }\n return earlierPatches\n .flatMap(ep => {\n return isEqualPath(ep.path, laterPatch.path) &&\n ep.op.type === 'diffMatchPatch'\n ? []\n : ep\n })\n .concat(replaced)\n }\n }\n earlierPatches.push(laterPatch)\n return earlierPatches\n },\n [],\n )\n}\n","import {\n type Mutation,\n type NodePatch,\n type PatchMutation,\n type SanityDocumentBase,\n} from '../../../mutations/types'\nimport {type MutationGroup} from '../../types'\nimport {compactDMPSetPatches} from './squashNodePatches'\n\nexport interface DataStore {\n get: (id: string) => SanityDocumentBase | undefined\n}\nexport function squashDMPStrings(\n base: DataStore,\n mutationGroups: MutationGroup[],\n): MutationGroup[] {\n return mutationGroups.map(mutationGroup => ({\n ...mutationGroup,\n mutations: dmpIfyMutations(base, mutationGroup.mutations),\n }))\n}\n\nexport function dmpIfyMutations(\n store: DataStore,\n mutations: Mutation[],\n): Mutation[] {\n return mutations.map((mutation, i) => {\n if (mutation.type !== 'patch') {\n return mutation\n }\n const base = store.get(mutation.id)\n return base ? dmpifyPatchMutation(base, mutation) : mutation\n })\n}\n\nexport function dmpifyPatchMutation(\n base: SanityDocumentBase,\n mutation: PatchMutation,\n): PatchMutation {\n return {\n ...mutation,\n patches: compactDMPSetPatches(base, mutation.patches as NodePatch[]),\n }\n}\n","import {applyPatches} from '../../apply'\nimport {\n type Mutation,\n type NodePatch,\n type PatchMutation,\n type SanityDocumentBase,\n} from '../../mutations/types'\nimport {getAtPath} from '../../path'\nimport {applyAll} from '../documentMap/applyDocumentMutation'\nimport {type MutationGroup} from '../types'\nimport {getMutationDocumentId} from '../utils/getMutationDocumentId'\nimport {compactDMPSetPatches} from './optimizations/squashNodePatches'\n\ntype RebaseTransaction = {\n mutations: Mutation[]\n}\n\ntype FlatMutation = Exclude<Mutation, PatchMutation>\n\nfunction flattenMutations(mutations: Mutation[]) {\n return mutations.flatMap((mut): Mutation | Mutation[] => {\n if (mut.type === 'patch') {\n return mut.patches.map(\n (patch): PatchMutation => ({\n type: 'patch',\n id: mut.id,\n patches: [patch],\n }),\n )\n }\n return mut\n })\n}\n\nexport function rebase(\n documentId: string,\n oldBase: SanityDocumentBase | undefined,\n newBase: SanityDocumentBase | undefined,\n localMutations: MutationGroup[],\n): [newLocal: MutationGroup[], rebased: SanityDocumentBase | undefined] {\n // const flattened = flattenMutations(newStage.flatMap(t => t.mutations))\n\n // 1. get the dmpified mutations from the newStage based on the old base\n // 2. apply those to the new base\n // 3. convert those back into set patches based on the new base and return as a new newStage\n let edge = oldBase\n const dmpified = localMutations.map(transaction => {\n const mutations = transaction.mutations.flatMap(mut => {\n if (getMutationDocumentId(mut) !== documentId) {\n return []\n }\n const before = edge\n edge = applyAll(edge, [mut])\n if (!before) {\n return mut\n }\n if (mut.type !== 'patch') {\n return mut\n }\n return {\n type: 'dmpified' as const,\n mutation: {\n ...mut,\n // Todo: make compactDMPSetPatches return pairs of patches that was dmpified with their\n // original as dmpPatches and original is not 1:1 (e..g some of the original may not be dmpified)\n dmpPatches: compactDMPSetPatches(before, mut.patches as NodePatch[]),\n original: mut.patches,\n },\n }\n })\n return {...transaction, mutations}\n })\n\n let newBaseWithDMPForOldBaseApplied: SanityDocumentBase | undefined = newBase\n // NOTE: It might not be possible to apply them - if so, we fall back to applying the pending changes\n // todo: revisit this\n const appliedCleanly = dmpified.map(transaction => {\n const applied = []\n return transaction.mutations.forEach(mut => {\n if (mut.type === 'dmpified') {\n // go through all dmpified, try to apply, if they fail, use the original un-optimized set patch instead\n try {\n newBaseWithDMPForOldBaseApplied = applyPatches(\n mut.mutation.dmpPatches,\n newBaseWithDMPForOldBaseApplied,\n )\n applied.push(mut)\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to apply dmp patch, falling back to original')\n try {\n newBaseWithDMPForOldBaseApplied = applyPatches(\n mut.mutation.original,\n newBaseWithDMPForOldBaseApplied,\n )\n applied.push(mut)\n } catch (second: any) {\n throw new Error(\n `Failed to apply patch for document \"${documentId}\": ${second.message}`,\n )\n }\n }\n } else {\n newBaseWithDMPForOldBaseApplied = applyAll(\n newBaseWithDMPForOldBaseApplied,\n [mut],\n )\n }\n })\n })\n\n const newStage = localMutations.map((transaction): MutationGroup => {\n // update all set patches to set to the current value\n return {\n ...transaction,\n mutations: transaction.mutations.map(mut => {\n if (mut.type !== 'patch' || getMutationDocumentId(mut) !== documentId) {\n return mut\n }\n return {\n ...mut,\n patches: mut.patches.map(patch => {\n if (patch.op.type !== 'set') {\n return patch\n }\n return {\n ...patch,\n op: {\n ...patch.op,\n value: getAtPath(patch.path, newBaseWithDMPForOldBaseApplied),\n },\n }\n }),\n }\n }),\n }\n })\n return [newStage, newBaseWithDMPForOldBaseApplied]\n}\n","import {type MutationGroup} from '../types'\n\n/**\n * Merges adjacent non-transactional mutation groups, interleaving transactional mutations as-is\n * @param mutationGroups\n */\nexport function mergeMutationGroups(\n mutationGroups: MutationGroup[],\n): MutationGroup[] {\n return chunkWhile(mutationGroups, group => !group.transaction).flatMap(\n chunk => ({\n ...chunk[0]!,\n mutations: chunk.flatMap(c => c.mutations),\n }),\n )\n}\n\n/**\n * Groups subsequent mutations into transactions, leaves transactions as-is\n * @param arr\n * @param predicate\n */\nexport function chunkWhile<T>(\n arr: T[],\n predicate: (item: T) => boolean,\n): T[][] {\n const res: T[][] = []\n let currentChunk: T[] = []\n arr.forEach(item => {\n if (predicate(item)) {\n currentChunk.push(item)\n } else {\n if (currentChunk.length > 0) {\n res.push(currentChunk)\n }\n currentChunk = []\n res.push([item])\n }\n })\n if (currentChunk.length > 0) {\n res.push(currentChunk)\n }\n return res\n}\n","import {groupBy} from 'lodash'\n\nimport {type Mutation, type NodePatch} from '../../../mutations/types'\nimport {type MutationGroup} from '../../types'\nimport {takeUntilRight} from '../../utils/arrayUtils'\nimport {getMutationDocumentId} from '../../utils/getMutationDocumentId'\nimport {mergeMutationGroups} from '../../utils/mergeMutationGroups'\nimport {squashNodePatches} from './squashNodePatches'\n\nexport function squashMutationGroups(staged: MutationGroup[]): MutationGroup[] {\n return mergeMutationGroups(staged)\n .map(transaction => ({\n ...transaction,\n mutations: squashMutations(transaction.mutations),\n }))\n .map(transaction => ({\n ...transaction,\n mutations: transaction.mutations.map(mutation => {\n if (mutation.type !== 'patch') {\n return mutation\n }\n return {\n ...mutation,\n patches: squashNodePatches(mutation.patches as NodePatch[]),\n }\n }),\n }))\n}\n\ntype FIXME = Mutation[]\n\n/*\n assumptions:\n the order documents appear with their mutations within the same transaction doesn't matter\n */\nexport function squashMutations(mutations: Mutation[]): Mutation[] {\n const byDocument = groupBy(mutations, getMutationDocumentId)\n return Object.values(byDocument).flatMap(documentMutations => {\n // these are the mutations that happens for the document with <id> within the same transactions\n return squashCreateIfNotExists(squashDelete(documentMutations as FIXME))\n .flat()\n .reduce((acc: Mutation[], docMutation) => {\n const prev = acc[acc.length - 1]\n if ((!prev || prev.type === 'patch') && docMutation.type === 'patch') {\n return acc.slice(0, -1).concat({\n ...docMutation,\n patches: (prev?.patches || []).concat(docMutation.patches),\n })\n }\n return acc.concat(docMutation)\n }, [])\n })\n}\n\n/**\n * WARNING: This assumes that the mutations are only for a single document\n * @param mutations\n */\nexport function squashCreateIfNotExists(mutations: Mutation[]): Mutation[] {\n if (mutations.length === 0) {\n return mutations\n }\n\n return mutations.reduce((previousMuts: Mutation[], laterMut: Mutation) => {\n if (laterMut.type !== 'createIfNotExists') {\n previousMuts.push(laterMut)\n return previousMuts\n }\n const prev = takeUntilRight(previousMuts, m => m.type === 'delete')\n const precedent = prev.find(\n precedingPatch => precedingPatch.type === 'createIfNotExists',\n )\n if (precedent) {\n // we already have an identical patch earlier in the chain that voids this one\n return previousMuts\n }\n previousMuts.push(laterMut)\n return previousMuts\n }, [])\n}\n\nfunction squashDelete(mutations: Mutation[]): Mutation[] {\n if (mutations.length === 0) {\n return mutations\n }\n\n return mutations.reduce((previousMuts: Mutation[], laterMut: Mutation) => {\n if (laterMut.type === 'delete') {\n return [laterMut]\n }\n previousMuts.push(laterMut)\n return previousMuts\n }, [])\n}\n","import {applyPatch, type RawPatch} from 'mendoza'\n\nimport {type SanityDocumentBase} from '../../mutations/types'\n\nfunction omitRev(document: SanityDocumentBase | undefined) {\n if (document === undefined) {\n return undefined\n }\n const {_rev, ...doc} = document\n return doc\n}\n\nexport function applyMendozaPatch(\n document: SanityDocumentBase | undefined,\n patch: RawPatch,\n patchBaseRev?: string,\n): SanityDocumentBase | undefined {\n if (patchBaseRev !== document?._rev) {\n throw new Error(\n 'Invalid document revision. The provided patch is calculated from a different revision than the current document',\n )\n }\n const next = applyPatch(omitRev(document), patch)\n return next === null ? undefined : next\n}\n\nexport function applyMutationEventEffects(\n document: SanityDocumentBase | undefined,\n event: {effects: {apply: RawPatch}; previousRev?: string; resultRev?: string},\n) {\n if (!event.effects) {\n throw new Error(\n 'Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?',\n )\n }\n const next = applyMendozaPatch(\n document,\n event.effects.apply,\n event.previousRev,\n )\n // next will be undefined in case of deletion\n return next ? {...next, _rev: event.resultRev} : undefined\n}\n","import {type SanityDocumentBase} from '../../mutations/types'\n\n/**\n * Minimalistic dataset implementation that only supports what's strictly necessary\n */\nexport function createDocumentMap() {\n const documents = new Map<string, SanityDocumentBase | undefined>()\n return {\n set: (id: string, doc: SanityDocumentBase | undefined) =>\n void documents.set(id, doc),\n get: (id: string) => documents.get(id),\n delete: (id: string) => documents.delete(id),\n }\n}\n","import {finalize, type Observable, ReplaySubject, share, timer} from 'rxjs'\n\nexport function createReplayMemoizer(expiry: number) {\n const memo: {[key: string]: Observable<any>} = Object.create(null)\n return function memoize<T>(\n key: string,\n observable: Observable<T>,\n ): Observable<T> {\n if (!(key in memo)) {\n memo[key] = observable.pipe(\n finalize(() => {\n delete memo[key]\n }),\n share({\n connector: () => new ReplaySubject(1),\n resetOnRefCountZero: () => timer(expiry),\n }),\n )\n }\n return memo[key]!\n }\n}\n","import {uuid} from '@sanity/uuid'\n\nexport function createTransactionId() {\n return uuid()\n}\n","import {type Mutation} from '../../mutations/types'\nimport {type MutationGroup} from '../types'\nimport {getMutationDocumentId} from './getMutationDocumentId'\n\nexport function filterMutationGroupsById(\n mutationGroups: MutationGroup[],\n id: string,\n): Mutation[] {\n return mutationGroups.flatMap(mutationGroup =>\n mutationGroup.mutations.flatMap(mut =>\n getMutationDocumentId(mut) === id ? [mut] : [],\n ),\n )\n}\n","export function hasProperty<T, P extends keyof T>(\n value: T,\n property: P,\n): value is T & Required<Pick<T, P>> {\n const val = value[property]\n return typeof val !== 'undefined' && val !== null\n}\n","import {type ReconnectEvent} from '@sanity/client'\nimport {\n concatMap,\n defer,\n EMPTY,\n filter,\n from,\n lastValueFrom,\n map,\n merge,\n mergeMap,\n type Observable,\n of,\n Subject,\n tap,\n toArray,\n} from 'rxjs'\n\nimport {decodeAll, type SanityMutation} from '../../encoders/sanity'\nimport {type Transaction} from '../../mutations/types'\nimport {applyAll} from '../documentMap/applyDocumentMutation'\nimport {applyMutationEventEffects} from '../documentMap/applyMendoza'\nimport {applyMutations} from '../documentMap/applyMutations'\nimport {commit} from '../documentMap/commit'\nimport {createDocumentMap} from '../documentMap/createDocumentMap'\nimport {\n type ListenerEvent,\n type MutationGroup,\n type OptimisticDocumentEvent,\n type OptimisticStore,\n type RemoteDocumentEvent,\n type RemoteMutationEvent,\n type SubmitResult,\n type TransactionalMutationGroup,\n} from '../types'\nimport {createReplayMemoizer} from '../utils/createReplayMemoizer'\nimport {createTransactionId} from '../utils/createTransactionId'\nimport {filterMutationGroupsById} from '../utils/filterMutationGroups'\nimport {hasProperty} from '../utils/isEffectEvent'\nimport {squashDMPStrings} from './optimizations/squashDMPStrings'\nimport {squashMutationGroups} from './optimizations/squashMutations'\nimport {rebase} from './rebase'\n\nexport interface OptimisticStoreBackend {\n /**\n * Sets up a subscription to a document\n * The first event should either be a sync event or an error event.\n * After that, it should emit mutation events, error events or sync events\n * @param id\n */\n listen: (id: string) => Observable<ListenerEvent>\n submit: (mutationGroups: Transaction) => Observable<SubmitResult>\n}\n\nlet didEmitMutationsAccessWarning = false\n// certain components, like the portable text editor, rely on mutations to be present in the event\n// i.e. it's not enough to just have the mendoza-patches.\n// If the listener event did not include mutations (e.g. if excludeMutations was set to true),\n// this warning will be issued if a downstream consumers attempts to access event.mutations\nfunction warnNoMutationsReceived() {\n if (!didEmitMutationsAccessWarning) {\n // eslint-disable-next-line no-console\n console.warn(\n new Error(\n 'No mutation received from backend. The listener is likely set up with `excludeMutations: true`. If your app need to know about mutations, make sure the listener is set up to include mutations',\n ),\n )\n didEmitMutationsAccessWarning = true\n }\n}\n\nconst EMPTY_ARRAY: any[] = []\n\n/**\n * Creates a local dataset that allows subscribing to documents by id and submitting mutations to be optimistically applied\n * @param backend\n */\nexport function createOptimisticStore(\n backend: OptimisticStoreBackend,\n): OptimisticStore {\n const local = createDocumentMap()\n const remote = createDocumentMap()\n const memoize = createReplayMemoizer(1000)\n let stagedChanges: MutationGroup[] = []\n\n const remoteEvents$ = new Subject<RemoteDocumentEvent>()\n const localMutations$ = new Subject<OptimisticDocumentEvent>()\n\n const stage$ = new Subject<void>()\n\n function setStaged(nextPending: MutationGroup[]) {\n stagedChanges = nextPending\n stage$.next()\n }\n\n function getLocalEvents(id: string) {\n return localMutations$.pipe(filter(event => event.id === id))\n }\n\n function getRemoteEvents(id: string) {\n return backend.listen(id).pipe(\n filter(\n (event): event is Exclude<ListenerEvent, ReconnectEvent> =>\n event.type !== 'reconnect',\n ),\n mergeMap((event): Observable<RemoteDocumentEvent> => {\n const oldLocal = local.get(id)\n const oldRemote = remote.get(id)\n if (event.type === 'sync') {\n const newRemote = event.document\n const [rebasedStage, newLocal] = rebase(\n id,\n oldRemote,\n newRemote,\n stagedChanges,\n )\n return of({\n type: 'sync',\n id,\n before: {remote: oldRemote, local: oldLocal},\n after: {remote: newRemote, local: newLocal},\n rebasedStage,\n })\n } else if (event.type === 'mutation') {\n // we have already seen this mutation\n if (event.transactionId === oldRemote?._rev) {\n return EMPTY\n }\n let newRemote\n if (hasProperty(event, 'effects')) {\n newRemote = applyMutationEventEffects(oldRemote, event)\n } else if (hasProperty(event, 'mutations')) {\n newRemote = applyAll(oldRemote, decodeAll(event.mutations))\n } else {\n throw new Error(\n 'Neither effects or mutations found on listener event',\n )\n }\n const [rebasedStage, newLocal] = rebase(\n id,\n oldRemote,\n newRemote,\n stagedChanges,\n )\n\n if (newLocal) {\n newLocal._rev = event.transactionId\n }\n const emittedEvent: RemoteMutationEvent = {\n type: 'mutation',\n id,\n rebasedStage,\n before: {remote: oldRemote, local: oldLocal},\n after: {remote: newRemote, local: newLocal},\n effects: event.effects,\n previousRev: event.previousRev,\n resultRev: event.resultRev,\n // overwritten below\n mutations: EMPTY_ARRAY,\n }\n if (event.mutations) {\n emittedEvent.mutations = decodeAll(\n event.mutations as SanityMutation[],\n )\n } else {\n Object.defineProperty(\n emittedEvent,\n 'mutations',\n warnNoMutationsReceived,\n )\n }\n return of(emittedEvent)\n } else {\n // @ts-expect-error should have covered all cases\n throw new Error(`Unknown event type: ${event.type}`)\n }\n }),\n tap(event => {\n local.set(event.id, event.after.local)\n remote.set(event.id, event.after.remote)\n setStaged(event.rebasedStage)\n }),\n tap({\n next: event => remoteEvents$.next(event),\n error: err => {\n // todo: how to propagate errors?\n // remoteEvents$.next()\n },\n }),\n )\n }\n\n function listenEvents(id: string) {\n return defer(() =>\n memoize(id, merge(getLocalEvents(id), getRemoteEvents(id))),\n )\n }\n\n const metaEvents$ = merge(localMutations$, remoteEvents$)\n\n return {\n meta: {\n events: metaEvents$,\n stage: stage$.pipe(\n map(\n () =>\n // note: this should not be tampered with by consumers. We might want to do a deep-freeze during dev to avoid accidental mutations\n stagedChanges,\n ),\n ),\n conflicts: EMPTY, // does nothing for now\n },\n mutate: mutations => {\n // add mutations to list of pending changes\n stagedChanges.push({transaction: false, mutations})\n // Apply mutations to local dataset (note: this is immutable, and doesn't change the dataset)\n const results = applyMutations(mutations, local)\n // Write the updated results back to the \"local\" dataset\n commit(results, local)\n results.forEach(result => {\n localMutations$.next({\n type: 'optimistic',\n before: result.before,\n after: result.after,\n mutations: result.mutations,\n id: result.id,\n stagedChanges: filterMutationGroupsById(stagedChanges, result.id),\n })\n })\n return results\n },\n transaction: mutationsOrTransaction => {\n const transaction: TransactionalMutationGroup = Array.isArray(\n mutationsOrTransaction,\n )\n ? {mutations: mutationsOrTransaction, transaction: true}\n : {...mutationsOrTransaction, transaction: true}\n\n stagedChanges.push(transaction)\n const results = applyMutations(transaction.mutations, local)\n commit(results, local)\n results.forEach(result => {\n localMutations$.next({\n type: 'optimistic',\n mutations: result.mutations,\n id: result.id,\n before: result.before,\n after: result.after,\n stagedChanges: filterMutationGroupsById(stagedChanges, result.id),\n })\n })\n return results\n },\n listenEvents: listenEvents,\n listen: id =>\n listenEvents(id).pipe(\n map(event =>\n event.type === 'optimistic' ? event.after : event.after.local,\n ),\n ),\n optimize: () => {\n setStaged(squashMutationGroups(stagedChanges))\n },\n submit: () => {\n const pending = stagedChanges\n setStaged([])\n return lastValueFrom(\n from(\n toTransactions(\n // Squashing DMP strings is the last thing we do before submitting\n squashDMPStrings(remote, squashMutationGroups(pending)),\n ),\n ).pipe(\n concatMap(mut => backend.submit(mut)),\n toArray(),\n ),\n )\n },\n }\n}\n\nexport function toTransactions(groups: MutationGroup[]): Transaction[] {\n return groups.map(group => {\n if (group.transaction && group.id !== undefined) {\n return {id: group.id!, mutations: group.mutations}\n }\n return {id: createTransactionId(), mutations: group.mutations}\n })\n}\n"],"names":["patch"],"mappings":";;;;;;;;;;AAOO,SAAS,sBAAsB,UAAgC;AACpE,MAAI,SAAS,SAAS;AACpB,WAAO,SAAS;AAElB,MAAI,SAAS,SAAS;AACpB,WAAO,SAAS,SAAS;AAE3B,MAAI,SAAS,SAAS;AACpB,WAAO,SAAS;AAKlB,MAHI,SAAS,SAAS,uBAGlB,SAAS,SAAS;AACpB,WAAO,SAAS,SAAS;AAE3B,QAAM,IAAI,MAAM,uBAAuB;AACzC;ACoBO,SAAS,SACd,SACA,UACiB;AACjB,SAAO,SAAS,OAAO,CAAC,KAAK,MAAM;AACjC,UAAM,MAAM,sBAAsB,KAAK,CAAC;AACxC,QAAI,IAAI,WAAW;AACjB,YAAM,IAAI,MAAM,IAAI,OAAO;AAE7B,WAAO,IAAI,WAAW,SAAS,MAAM,IAAI;AAAA,EAC3C,GAAG,OAAO;AACZ;AAOO,SAAS,sBACd,UACA,UACqB;AACrB,MAAI,SAAS,SAAS;AACpB,WAAO,OAAO,UAAU,QAAQ;AAElC,MAAI,SAAS,SAAS;AACpB,WAAO,kBAAkB,UAAU,QAAQ;AAE7C,MAAI,SAAS,SAAS;AACpB,WAAO,IAAI,UAAU,QAAQ;AAE/B,MAAI,SAAS,SAAS;AACpB,WAAO,gBAAgB,UAAU,QAAQ;AAE3C,MAAI,SAAS,SAAS;AACpB,WAAO,MAAM,UAAU,QAAQ;AAGjC,QAAM,IAAI,MAAM,0BAA0B,SAAS,IAAI,EAAE;AAC3D;AAEA,SAAS,OACP,UACA,UACqB;AACrB,MAAI;AACF,WAAO,EAAC,QAAQ,SAAS,SAAS,yBAAA;AAEpC,QAAM,SAAS,SAAS,SAAS,UAAU,MAAM;AACjD,SAAO,EAAC,QAAQ,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AA,CAAE,GACL;AAAA,QACL;AAAA,UACE;AAAA;AAAA,YAEE,iBAAiB,QAAQ,qBAAqB,OAAO,CAAC;AAAA,UAAA;AAAA,QACxD,EACA;AAAA,UACA,UAAU,CAAA,QAAO,QAAQ,OAAO,GAAG,CAAC;AAAA,UACpC,QAAA;AAAA,QAAQ;AAAA,MACV;AAAA,IAEJ;AAAA,EAAA;AAEJ;AAEO,SAAS,eAAe,QAAwC;AACrE,SAAO,OAAO,IAAI,CAAA,UACZ,MAAM,eAAe,MAAM,OAAO,SAC7B,EAAC,IAAI,MAAM,IAAK,WAAW,MAAM,UAAA,IAEnC,EAAC,IAAI,uBAAuB,WAAW,MAAM,WACrD;AACH;"}
"use strict";
Object.defineProperty(exports, "__esModule", { value: !0 });
var mendoza = require("mendoza"), rxjs = require("rxjs"), xstate = require("xstate"), encode = require("./_chunks-cjs/encode.cjs"), createOptimisticStore = require("./_chunks-cjs/createOptimisticStore.cjs");
function createSharedListener(client) {
const allEvents$ = client.listen(
'*[!(_id in path("_.**"))]',
{},
{
events: ["welcome", "mutation", "reconnect"],
includeResult: !1,
includePreviousRevision: !1,
visibility: "transaction",
effectFormat: "mendoza",
includeMutations: !1
}
).pipe(rxjs.share({ resetOnRefCountZero: !0 })), reconnect = allEvents$.pipe(
rxjs.filter((event) => event.type === "reconnect")
), welcome = allEvents$.pipe(
rxjs.filter((event) => event.type === "welcome")
), mutations = allEvents$.pipe(
rxjs.filter((event) => event.type === "mutation")
), replayWelcome = rxjs.merge(welcome, reconnect).pipe(
rxjs.shareReplay({ bufferSize: 1, refCount: !0 })
).pipe(
rxjs.filter((latestConnectionEvent) => latestConnectionEvent.type === "welcome")
);
return rxjs.merge(replayWelcome, mutations, reconnect);
}
const documentMutatorMachine = xstate.setup({
types: {},
actions: {
"assign error to context": xstate.assign({ error: ({ event }) => event }),
"clear error from context": xstate.assign({ error: void 0 }),
"connect to server-sent events": xstate.raise({ type: "connect" }),
"listen to server-sent events": xstate.spawnChild("server-sent events", {
id: "listener",
input: ({ context }) => ({
listener: context.sharedListener || createSharedListener(context.client),
id: context.id
})
}),
"stop listening to server-sent events": xstate.stopChild("listener"),
"buffer remote mutation events": xstate.assign({
mutationEvents: ({ event, context }) => (xstate.assertEvent(event, "mutation"), [...context.mutationEvents, event])
}),
"restore stashed changes": xstate.assign({
stagedChanges: ({ event, context }) => (xstate.assertEvent(event, "xstate.done.actor.submitTransactions"), context.stashedChanges),
stashedChanges: []
}),
"rebase fetched remote snapshot": xstate.enqueueActions(({ enqueue }) => {
enqueue.assign(({ event, context }) => {
xstate.assertEvent(event, "xstate.done.actor.getDocument");
const previousRemote = context.remote;
let nextRemote = event.output, seenCurrentRev = !1;
for (const patch of context.mutationEvents)
!patch.effects?.apply || !patch.previousRev && patch.transition !== "appear" || (!seenCurrentRev && patch.previousRev === nextRemote?._rev && (seenCurrentRev = !0), seenCurrentRev && (nextRemote = applyMendozaPatch(
nextRemote,
patch.effects.apply,
patch.resultRev
)));
context.cache && // If the shared cache don't have the document already we can just set it
(!context.cache.has(context.id) || // But when it's in the cache, make sure it's necessary to update it
context.cache.get(context.id)._rev !== nextRemote?._rev) && context.cache.set(context.id, nextRemote);
const [stagedChanges, local] = createOptimisticStore.rebase(
context.id,
// It's annoying to convert between null and undefined, reach consensus
previousRemote === null ? void 0 : previousRemote,
nextRemote === null ? void 0 : nextRemote,
context.stagedChanges
);
return {
remote: nextRemote,
local,
stagedChanges,
// Since the snapshot handler applies all the patches they are no longer needed, allow GC
mutationEvents: []
};
}), enqueue.sendParent(
({ context }) => ({
type: "rebased.remote",
id: context.id,
document: context.remote
})
);
}),
"apply mendoza patch": xstate.assign(({ event, context }) => {
xstate.assertEvent(event, "mutation");
const previousRemote = context.remote;
if (event.transactionId === previousRemote?._rev)
return {};
const nextRemote = applyMendozaPatch(
previousRemote,
event.effects.apply,
event.resultRev
);
context.cache && // If the shared cache don't have the document already we can just set it
(!context.cache.has(context.id) || // But when it's in the cache, make sure it's necessary to update it
context.cache.get(context.id)._rev !== nextRemote?._rev) && context.cache.set(context.id, nextRemote);
const [stagedChanges, local] = createOptimisticStore.rebase(
context.id,
// It's annoying to convert between null and undefined, reach consensus
previousRemote === null ? void 0 : previousRemote,
nextRemote === null ? void 0 : nextRemote,
context.stagedChanges
);
return {
remote: nextRemote,
local,
stagedChanges
};
}),
"increment fetch attempts": xstate.assign({
fetchRemoteSnapshotAttempts: ({ context }) => context.fetchRemoteSnapshotAttempts + 1
}),
"reset fetch attempts": xstate.assign({
fetchRemoteSnapshotAttempts: 0
}),
"increment submit attempts": xstate.assign({
submitTransactionsAttempts: ({ context }) => context.submitTransactionsAttempts + 1
}),
"reset submit attempts": xstate.assign({
submitTransactionsAttempts: 0
}),
"stage mutation": xstate.assign({
stagedChanges: ({ event, context }) => (xstate.assertEvent(event, "mutate"), [
...context.stagedChanges,
{ transaction: !1, mutations: event.mutations }
])
}),
"stash mutation": xstate.assign({
stashedChanges: ({ event, context }) => (xstate.assertEvent(event, "mutate"), [
...context.stashedChanges,
{ transaction: !1, mutations: event.mutations }
])
}),
"rebase local snapshot": xstate.enqueueActions(({ enqueue }) => {
enqueue.assign({
local: ({ event, context }) => {
xstate.assertEvent(event, "mutate");
const localDataset = /* @__PURE__ */ new Map();
context.local && localDataset.set(context.id, context.local);
const results = createOptimisticStore.applyMutations(event.mutations, localDataset);
return createOptimisticStore.commit(results, localDataset), localDataset.get(context.id);
}
}), enqueue.sendParent(
({ context }) => ({
type: "rebased.local",
id: context.id,
document: context.local
})
);
}),
"send pristine event to parent": xstate.sendParent(
({ context }) => ({
type: "pristine",
id: context.id
})
),
"send sync event to parent": xstate.sendParent(
({ context }) => ({
type: "sync",
id: context.id,
document: context.remote
})
),
"send mutation event to parent": xstate.sendParent(({ context, event }) => (xstate.assertEvent(event, "mutation"), {
type: "mutation",
id: context.id,
previousRev: event.previousRev,
resultRev: event.resultRev,
effects: event.effects
}))
},
actors: {
"server-sent events": xstate.fromEventObservable(
({
input
}) => {
const { listener, id } = input;
return rxjs.defer(() => listener).pipe(
rxjs.filter(
(event) => event.type === "welcome" || event.type === "reconnect" || event.type === "mutation" && event.documentId === id
),
// This is necessary to avoid sync emitted events from `shareReplay` from happening before the actor is ready to receive them
rxjs.observeOn(rxjs.asapScheduler)
);
}
),
"fetch remote snapshot": xstate.fromPromise(
async ({
input,
signal
}) => {
const { client, id } = input;
return await client.getDocument(id, {
signal
}).catch((e) => {
if (!(e instanceof Error && e.name === "AbortError"))
throw e;
});
}
),
"submit mutations as transactions": xstate.fromPromise(
async ({
input,
signal
}) => {
const { client, transactions } = input;
for (const transaction of transactions) {
if (signal.aborted) return;
await client.dataRequest("mutate", encode.encodeTransaction(transaction), {
visibility: "async",
returnDocuments: !1,
signal
}).catch((e) => {
if (!(e instanceof Error && e.name === "AbortError"))
throw e;
});
}
}
)
},
delays: {
// Exponential backoff delay function
fetchRemoteSnapshotTimeout: ({ context }) => Math.pow(2, context.fetchRemoteSnapshotAttempts) * 1e3,
submitTransactionsTimeout: ({ context }) => Math.pow(2, context.submitTransactionsAttempts) * 1e3
}
}).createMachine({
/** @xstate-layout N4IgpgJg5mDOIC5QQPYGMCuBbMA7ALgLRYb4CG+KATgMQnn5gDaADALqKgAOKsAlvj4pcnEAA9EADhYAWAHQA2GSwUBmAKwBOaQEZJkhQBoQAT0Q6ATAF8rx1JhwFipCtTkQ+sNMNxg0jCBpvXF9-Vg4kEB5+QWFRCQQLFhY5PQB2dRU1SQsdGSVjMwRlHTkWNM00nR1VKryKmzt0bDwielcqOWDQwVwoGgB3MAAbbxxw0WiBIRFIhPUKuQ1NVU0tTU0WFdVCxAt1dTlNhX2WdRltGUk061sQexandspO7r9e-qo-H3eJyKnYrNQPNJJollpVutNttdghVCo5MoTgoMpo8jIkqpGvdmo42i4Xl0fv4+H0aGAqFRqH9uLxpnE5ogFrCLFd5CtNBYFJkdOpuaosXcHnjnAw3G9-AAxMh8YYYL5BYn4GlROmA+KIFEs1R6ORpZYWHIXGR6bHC1qijpyL4Sj6D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-klILzUhYDSJVRpnCONNOcWxWRKBRDYO4uAUD7XgJEMuIdqDi2GgWQgOhgxMyRKyFc8IuQkXUDvK0HgvAHmIR9bCD4SoeSWCoLkoZpxrmXIw0OLEMxsNJgkSc418KhnrHyG4oZYTcPhMifhJx4SCiDjrABSpgHiLtogAUhwW77DRIGXkk55wexKCrJQsg1jBTnPsYRqZviiL6PohuORgyhhBhGKMsZYzxhcXrf8EBPHulUJOPCtRlABWIu7IoORVBIIhMpNYGJyghKHmEvaYjQEkOwhkxQrJtBES0JDOBPlkgKD1JYZSjZORyTXNkwBsVwkFPYTJVYS58JxPKbOYM0gUj7FjGcEMOpciaJxMHXWOTWJV2avFRKpIwARILJRGJBF4mZBIkDE0KtIxLSSDkDYGhWl70Ru1Tq6zsLURBkoLyWRmz8PmlUZmcY1zXDKdMghcy2mIyFh8W5ZN4RFmOFyKaZwiLeT2GVJcy5pBrguCiMK2tvyDwBYbIWejOkSMQBkeQORJq0RNCUDIDNondxuGpPQmRqIXPhiPECuKMpdMkbILZ-SEnLxyjqOJMZsj1jRTYIAA */
id: "document-mutator",
context: ({ input }) => ({
client: input.client.withConfig({ allowReconfigure: !1 }),
sharedListener: input.sharedListener,
id: input.id,
remote: void 0,
local: void 0,
mutationEvents: [],
stagedChanges: [],
stashedChanges: [],
error: void 0,
fetchRemoteSnapshotAttempts: 0,
submitTransactionsAttempts: 0,
cache: input.cache
}),
// Auto start the connection by default
entry: ["connect to server-sent events"],
on: {
mutate: {
actions: ["rebase local snapshot", "stage mutation"]
}
},
initial: "disconnected",
states: {
disconnected: {
on: {
connect: {
target: "connecting",
actions: ["listen to server-sent events"]
}
}
},
connecting: {
on: {
welcome: "connected",
reconnect: "reconnecting",
error: "connectFailure"
},
tags: ["busy"]
},
connectFailure: {
on: {
connect: {
target: "connecting",
actions: ["listen to server-sent events"]
}
},
entry: [
"stop listening to server-sent events",
"assign error to context"
],
exit: ["clear error from context"],
tags: ["error"]
},
reconnecting: {
on: {
welcome: {
target: "connected"
},
error: {
target: "connectFailure"
}
},
tags: ["busy", "error"]
},
connected: {
on: {
mutation: {
actions: ["buffer remote mutation events"]
},
reconnect: "reconnecting"
},
entry: ["clear error from context"],
initial: "loading",
states: {
loading: {
invoke: {
src: "fetch remote snapshot",
id: "getDocument",
input: ({ context }) => ({
client: context.client,
id: context.id
}),
onError: {
target: "loadFailure"
},
onDone: {
target: "loaded",
actions: [
"rebase fetched remote snapshot",
"reset fetch attempts"
]
}
},
tags: ["busy"]
},
loaded: {
entry: ["send sync event to parent"],
on: {
mutation: {
actions: ["apply mendoza patch", "send mutation event to parent"]
}
},
initial: "pristine",
states: {
pristine: {
on: {
mutate: {
actions: ["rebase local snapshot", "stage mutation"],
target: "dirty"
}
},
tags: ["ready"]
},
dirty: {
on: {
submit: "submitting"
},
tags: ["ready"]
},
submitting: {
on: {
mutate: {
actions: ["rebase local snapshot", "stash mutation"]
}
},
invoke: {
src: "submit mutations as transactions",
id: "submitTransactions",
input: ({ context }) => {
const remoteDataset = /* @__PURE__ */ new Map();
return remoteDataset.set(context.id, context.remote), {
client: context.client,
transactions: createOptimisticStore.toTransactions(
// Squashing DMP strings is the last thing we do before submitting
createOptimisticStore.squashDMPStrings(
remoteDataset,
createOptimisticStore.squashMutationGroups(context.stagedChanges)
)
)
};
},
onError: {
target: "submitFailure"
},
onDone: {
target: "pristine",
actions: [
"restore stashed changes",
"reset submit attempts",
"send pristine event to parent"
]
}
},
/**
* 'busy' means we should show a spinner, 'ready' means we can still accept mutations, they'll be applied optimistically right away, and queued for submissions after the current submission settles
*/
tags: ["busy", "ready"]
},
submitFailure: {
exit: ["clear error from context"],
after: {
submitTransactionsTimeout: {
actions: ["increment submit attempts"],
target: "submitting"
}
},
on: {
retry: "submitting"
},
/**
* How can it be both `ready` and `error`? `ready` means it can receive mutations, optimistically apply them, and queue them for submission. `error` means it failed to submit previously applied mutations.
* It's completely fine to keep queueing up more mutations and applying them optimistically, while showing UI that notifies that mutations didn't submit, and show a count down until the next automatic retry.
*/
tags: ["error", "ready"]
}
}
},
loadFailure: {
exit: ["clear error from context"],
after: {
fetchRemoteSnapshotTimeout: {
actions: ["increment fetch attempts"],
target: "loading"
}
},
on: {
retry: "loading"
},
tags: ["error"]
}
}
}
}
});
function applyMendozaPatch(document, patch, nextRevision) {
const next = mendoza.applyPatch(omitRev(document), patch);
return next ? Object.assign(next, { _rev: nextRevision }) : null;
}
function omitRev(document) {
if (!document)
return null;
const { _rev, ...doc } = document;
return doc;
}
exports.createSharedListener = createSharedListener;
exports.documentMutatorMachine = documentMutatorMachine;
//# sourceMappingURL=_unstable_machine.cjs.map
{"version":3,"file":"_unstable_machine.cjs","sources":["../src/machine/listener.ts","../src/machine/documentMutatorMachine.ts"],"sourcesContent":["import {\n type MutationEvent,\n type ReconnectEvent,\n type SanityClient,\n type WelcomeEvent,\n} from '@sanity/client'\nimport {filter, merge, type ObservedValueOf, share, shareReplay} from 'rxjs'\n\n/**\n * Creates a single, shared, listener EventSource that strems remote mutations, and notifies when it's online (welcome), offline (reconnect).\n */\nexport function createSharedListener(client: SanityClient) {\n const allEvents$ = client\n .listen(\n '*[!(_id in path(\"_.**\"))]',\n {},\n {\n events: ['welcome', 'mutation', 'reconnect'],\n includeResult: false,\n includePreviousRevision: false,\n visibility: 'transaction',\n effectFormat: 'mendoza',\n includeMutations: false,\n },\n )\n .pipe(share({resetOnRefCountZero: true}))\n\n // Reconnect events emitted in case the connection is lost\n const reconnect = allEvents$.pipe(\n filter((event): event is ReconnectEvent => event.type === 'reconnect'),\n )\n\n // Welcome events are emitted when the listener is (re)connected\n const welcome = allEvents$.pipe(\n filter((event): event is WelcomeEvent => event.type === 'welcome'),\n )\n\n // Mutation events coming from the listener\n const mutations = allEvents$.pipe(\n filter((event): event is MutationEvent => event.type === 'mutation'),\n )\n\n // Replay the latest connection event that was emitted either when the connection was disconnected ('reconnect'), established or re-established ('welcome')\n const connectionEvent = merge(welcome, reconnect).pipe(\n shareReplay({bufferSize: 1, refCount: true}),\n )\n\n // Emit the welcome event if the latest connection event was the 'welcome' event.\n // Downstream subscribers will typically map the welcome event to an initial fetch\n const replayWelcome = connectionEvent.pipe(\n filter(latestConnectionEvent => latestConnectionEvent.type === 'welcome'),\n )\n\n // Combine into a single stream\n return merge(replayWelcome, mutations, reconnect)\n}\n\nexport type SharedListenerEvents = ObservedValueOf<\n ReturnType<typeof createSharedListener>\n>\n","import {\n type MutationEvent,\n type SanityClient,\n type SanityDocument,\n} from '@sanity/client'\nimport {applyPatch, type RawPatch} from 'mendoza'\nimport {asapScheduler, defer, filter, observeOn} from 'rxjs'\nimport {\n assertEvent,\n assign,\n enqueueActions,\n fromEventObservable,\n fromPromise,\n raise,\n sendParent,\n setup,\n spawnChild,\n stopChild,\n} from 'xstate'\n\nimport {encodeTransaction, type Mutation} from '../encoders/sanity'\nimport {\n type MutationGroup,\n type SanityDocumentBase,\n type Transaction,\n} from '../store'\nimport {applyMutations} from '../store/documentMap/applyMutations'\nimport {commit} from '../store/documentMap/commit'\nimport {createSharedListener, type SharedListenerEvents} from './listener'\nimport { squashDMPStrings } from '../store/optimistic/optimizations/squashDMPStrings'\nimport { rebase } from '../store/optimistic/rebase'\nimport { squashMutationGroups } from '../store/optimistic/optimizations/squashMutations'\nimport { toTransactions } from '../store/optimistic/createOptimisticStore'\n\nexport {createSharedListener}\n\nexport interface DocumentMutatorMachineInput {\n id: string\n client: SanityClient\n /** A shared listener can be provided, if not it'll be created using `client.listen()` */\n sharedListener?: ReturnType<typeof createSharedListener>\n /* Preferrably a LRU cache map that is compatible with an ES6 Map, and have documents that allow unique ids to a particular dataset */\n cache?: Map<string, SanityDocument | null>\n}\n\nexport type DocumentMutatorMachineParentEvent =\n | {type: 'sync'; id: string; document: SanityDocumentBase}\n | {\n type: 'mutation'\n id: string\n effects: {apply: RawPatch}\n previousRev: string\n resultRev: string\n }\n | {type: 'rebased.local'; id: string; document: SanityDocumentBase}\n | {type: 'rebased.remote'; id: string; document: SanityDocumentBase}\n | {type: 'pristine'; id: string}\n\nexport const documentMutatorMachine = setup({\n types: {} as {\n children: {\n getDocument: 'fetch remote snapshot'\n submitTransactions: 'submit mutations as transactions'\n }\n tags: 'busy' | 'error' | 'ready'\n context: {\n client: SanityClient\n /** A shared listener can be provided, if not it'll be created using `client.listen()` */\n sharedListener?: ReturnType<typeof createSharedListener>\n /** The document id */\n id: string\n /* Preferrably a LRU cache map that is compatible with an ES6 Map, and have documents that allow unique ids to a particular dataset */\n cache?: Map<string, SanityDocument | null>\n /* The remote snapshot of what the document looks like in Content Lake, kept in sync by applying Mendoza patches in real time. undefined means it's unknown if it exists yet, null means its known that it doesn't exist. */\n remote: SanityDocument | null | undefined\n /* Local snapshot, that is rebased to the remote snapshot whenever that snapshot changes, and allows optimistic local mutations. undefined means it's unknown if the document exists in content lake yet, if both `remote` and `local` is `null` it means it's known that it doesn't exist. If `remote` is defined, and `local` is `null` it means it's optimistically deleted. If `remote` is `null` and `local` defined then it's optimistically created. */\n local: SanityDocument | null | undefined\n /* Remote mendoza mutation events, needs a better name to differentiate from optimistic mutations */\n mutationEvents: MutationEvent[]\n /* Track staged mutations that can be submitted */\n stagedChanges: MutationGroup[]\n /* Queue mutations mutations that should be staged after an ongoing submission settles */\n stashedChanges: MutationGroup[]\n /* Any kind of error object that the UI can parse and decide how to display/report */\n error: unknown\n /* Used for automatic retrying of loading the remote snapshot */\n fetchRemoteSnapshotAttempts: number\n /* Used for automatic retrying of submitting mutations to Content Lake as a transaction */\n submitTransactionsAttempts: number\n }\n events:\n | SharedListenerEvents\n | {type: 'error'}\n | {type: 'retry'}\n | {type: 'connect'}\n | {type: 'reconnect'}\n | {type: 'welcome'}\n | {type: 'mutate'; mutations: Mutation[]}\n | {type: 'submit'}\n | {\n type: 'xstate.done.actor.getDocument'\n output: SanityDocument\n }\n | {\n type: 'xstate.done.actor.submitTransactions'\n output: undefined\n }\n input: DocumentMutatorMachineInput\n },\n actions: {\n 'assign error to context': assign({error: ({event}) => event}),\n 'clear error from context': assign({error: undefined}),\n 'connect to server-sent events': raise({type: 'connect'}),\n 'listen to server-sent events': spawnChild('server-sent events', {\n id: 'listener',\n input: ({context}) => ({\n listener:\n context.sharedListener || createSharedListener(context.client),\n id: context.id,\n }),\n }),\n 'stop listening to server-sent events': stopChild('listener'),\n 'buffer remote mutation events': assign({\n mutationEvents: ({event, context}) => {\n assertEvent(event, 'mutation')\n return [...context.mutationEvents, event]\n },\n }),\n 'restore stashed changes': assign({\n stagedChanges: ({event, context}) => {\n assertEvent(event, 'xstate.done.actor.submitTransactions')\n return context.stashedChanges\n },\n stashedChanges: [],\n }),\n 'rebase fetched remote snapshot': enqueueActions(({enqueue}) => {\n enqueue.assign(({event, context}) => {\n assertEvent(event, 'xstate.done.actor.getDocument')\n const previousRemote = context.remote\n let nextRemote = event.output\n\n /**\n * We assume all patches that happen while we're waiting for the document to resolve are already applied.\n * But if we do see a patch that has the same revision as the document we just fetched, we should apply any patches following it\n */\n let seenCurrentRev = false\n for (const patch of context.mutationEvents) {\n if (\n !patch.effects?.apply ||\n (!patch.previousRev && patch.transition !== 'appear')\n )\n continue\n if (!seenCurrentRev && patch.previousRev === nextRemote?._rev) {\n seenCurrentRev = true\n }\n if (seenCurrentRev) {\n nextRemote = applyMendozaPatch(\n nextRemote,\n patch.effects.apply,\n patch.resultRev,\n )\n }\n }\n\n if (\n context.cache &&\n // If the shared cache don't have the document already we can just set it\n (!context.cache.has(context.id) ||\n // But when it's in the cache, make sure it's necessary to update it\n context.cache.get(context.id)!._rev !== nextRemote?._rev)\n ) {\n context.cache.set(context.id, nextRemote as unknown as any)\n }\n\n const [stagedChanges, local] = rebase(\n context.id,\n // It's annoying to convert between null and undefined, reach consensus\n previousRemote === null ? undefined : previousRemote,\n nextRemote === null ? undefined : (nextRemote as unknown as any),\n context.stagedChanges,\n )\n\n return {\n remote: nextRemote as unknown as any,\n local: local as unknown as any,\n stagedChanges,\n // Since the snapshot handler applies all the patches they are no longer needed, allow GC\n mutationEvents: [],\n }\n })\n enqueue.sendParent(\n ({context}) =>\n ({\n type: 'rebased.remote',\n id: context.id,\n document: context.remote!,\n }) satisfies DocumentMutatorMachineParentEvent,\n )\n }),\n 'apply mendoza patch': assign(({event, context}) => {\n assertEvent(event, 'mutation')\n const previousRemote = context.remote\n // We have already seen this mutation\n if (event.transactionId === previousRemote?._rev) {\n return {}\n }\n\n const nextRemote = applyMendozaPatch(\n previousRemote!,\n event.effects!.apply,\n event.resultRev,\n )\n\n if (\n context.cache &&\n // If the shared cache don't have the document already we can just set it\n (!context.cache.has(context.id) ||\n // But when it's in the cache, make sure it's necessary to update it\n context.cache.get(context.id)!._rev !== nextRemote?._rev)\n ) {\n context.cache.set(context.id, nextRemote as unknown as any)\n }\n\n const [stagedChanges, local] = rebase(\n context.id,\n // It's annoying to convert between null and undefined, reach consensus\n previousRemote === null ? undefined : previousRemote,\n nextRemote === null ? undefined : (nextRemote as unknown as any),\n context.stagedChanges,\n )\n\n return {\n remote: nextRemote as unknown as any,\n local: local as unknown as any,\n stagedChanges,\n }\n }),\n 'increment fetch attempts': assign({\n fetchRemoteSnapshotAttempts: ({context}) =>\n context.fetchRemoteSnapshotAttempts + 1,\n }),\n 'reset fetch attempts': assign({\n fetchRemoteSnapshotAttempts: 0,\n }),\n 'increment submit attempts': assign({\n submitTransactionsAttempts: ({context}) =>\n context.submitTransactionsAttempts + 1,\n }),\n 'reset submit attempts': assign({\n submitTransactionsAttempts: 0,\n }),\n 'stage mutation': assign({\n stagedChanges: ({event, context}) => {\n assertEvent(event, 'mutate')\n return [\n ...context.stagedChanges,\n {transaction: false, mutations: event.mutations},\n ]\n },\n }),\n 'stash mutation': assign({\n stashedChanges: ({event, context}) => {\n assertEvent(event, 'mutate')\n return [\n ...context.stashedChanges,\n {transaction: false, mutations: event.mutations},\n ]\n },\n }),\n 'rebase local snapshot': enqueueActions(({enqueue}) => {\n enqueue.assign({\n local: ({event, context}) => {\n assertEvent(event, 'mutate')\n // @TODO would be helpful to not have to convert back and forth between maps\n const localDataset = new Map()\n if (context.local) {\n localDataset.set(context.id, context.local)\n }\n // Apply mutations to local dataset (note: this is immutable, and doesn't change the dataset)\n const results = applyMutations(event.mutations, localDataset)\n // Write the updated results back to the \"local\" dataset\n commit(results, localDataset)\n // Read the result from the local dataset again\n return localDataset.get(context.id)\n },\n })\n enqueue.sendParent(\n ({context}) =>\n ({\n type: 'rebased.local',\n id: context.id,\n document: context.local!,\n }) satisfies DocumentMutatorMachineParentEvent,\n )\n }),\n 'send pristine event to parent': sendParent(\n ({context}) =>\n ({\n type: 'pristine',\n id: context.id,\n }) satisfies DocumentMutatorMachineParentEvent,\n ),\n 'send sync event to parent': sendParent(\n ({context}) =>\n ({\n type: 'sync',\n id: context.id,\n document: context.remote!,\n }) satisfies DocumentMutatorMachineParentEvent,\n ),\n 'send mutation event to parent': sendParent(({context, event}) => {\n assertEvent(event, 'mutation')\n return {\n type: 'mutation',\n id: context.id,\n previousRev: event.previousRev!,\n resultRev: event.resultRev!,\n effects: event.effects!,\n } satisfies DocumentMutatorMachineParentEvent\n }),\n },\n actors: {\n 'server-sent events': fromEventObservable(\n ({\n input,\n }: {\n input: {listener: ReturnType<typeof createSharedListener>; id: string}\n }) => {\n const {listener, id} = input\n return defer(() => listener).pipe(\n filter(\n event =>\n event.type === 'welcome' ||\n event.type === 'reconnect' ||\n (event.type === 'mutation' && event.documentId === id),\n ),\n // This is necessary to avoid sync emitted events from `shareReplay` from happening before the actor is ready to receive them\n observeOn(asapScheduler),\n )\n },\n ),\n 'fetch remote snapshot': fromPromise(\n async ({\n input,\n signal,\n }: {\n input: {client: SanityClient; id: string}\n signal: AbortSignal\n }) => {\n const {client, id} = input\n const document = await client\n .getDocument(id, {\n signal,\n })\n .catch(e => {\n if (e instanceof Error && e.name === 'AbortError') return\n throw e\n })\n\n return document\n },\n ),\n 'submit mutations as transactions': fromPromise(\n async ({\n input,\n signal,\n }: {\n input: {client: SanityClient; transactions: Transaction[]}\n signal: AbortSignal\n }) => {\n const {client, transactions} = input\n for (const transaction of transactions) {\n if (signal.aborted) return\n await client\n .dataRequest('mutate', encodeTransaction(transaction), {\n visibility: 'async',\n returnDocuments: false,\n signal,\n })\n .catch(e => {\n if (e instanceof Error && e.name === 'AbortError') return\n throw e\n })\n }\n },\n ),\n },\n delays: {\n // Exponential backoff delay function\n fetchRemoteSnapshotTimeout: ({context}) =>\n Math.pow(2, context.fetchRemoteSnapshotAttempts) * 1000,\n submitTransactionsTimeout: ({context}) =>\n Math.pow(2, context.submitTransactionsAttempts) * 1000,\n },\n}).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QQPYGMCuBbMA7ALgLRYb4CG+KATgMQnn5gDaADALqKgAOKsAlvj4pcnEAA9EADhYAWAHQA2GSwUBmAKwBOaQEZJkhQBoQAT0Q6ATAF8rx1JhwFipCtTkQ+sNMNxg0jCBpvXF9-Vg4kEB5+QWFRCQQLFhY5PQB2dRU1SQsdGSVjMwRlHTkWNM00nR1VKryKmzt0bDwielcqOWDQwVwoGgB3MAAbbxxw0WiBIRFIhPUKuQ1NVU0tTU0WFdVCxAt1dTlNhX2WdRltGUk061sQexandspO7r9e-qo-H3eJyKnYrNQPNJJollpVutNttdghVCo5MoTgoMpo8jIkqpGvdmo42i4Xl0fv4+H0aGAqFRqH9uLxpnE5ogFrCLFd5CtNBYFJkdOpuaosXcHnjnAw3G9-AAxMh8YYYL5BYn4GlROmA+KIFEs1R6ORpZYWHIXGR6bHC1qijpyL4Sj6DEZjZjsSZqmYaxK1ORcvlc-ZqSoyNKwnRpGTyK4WDK5BQ6BQ5BRm3EW55uG1K0n9ClUqgqgFuxketJe7nIv2rUNB0x7LmSL2qGMsSySevcmSJhzJgnipWQOgEma510M4HmcqHZYyWqaOMqTQyWGh0osVSGiwC5uGyftx74sWvHuBNMhX7O-5DoHiPae72lvnlwPBydFlRVS7qPIl7cilP74-+SByMMKBkB4ZKoL4cikgAbigADWYByDA+AACJJgQg4xPmI7FHkZQrKGsjqKcCiaMG9YpJOxySBiCiy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0JDOBPlkgKD1JYZSjZORyTXNkwBsVwkFPYTJVYS58JxPKbOYM0gUj7FjGcEMOpciaJxMHXWOTWJV2avFRKpIwARILJRGJBF4mZBIkDE0KtIxLSSDkDYGhWl70Ru1Tq6zsLURBkoLyWRmz8PmlUZmcY1zXDKdMghcy2mIyFh8W5ZN4RFmOFyKaZwiLeT2GVJcy5pBrguCiMK2tvyDwBYbIWejOkSMQBkeQORJq0RNCUDIDNondxuGpPQmRqIXPhiPECuKMpdMkbILZ-SEnLxyjqOJMZsj1jRTYIAA */\n\n id: 'document-mutator',\n\n context: ({input}) => ({\n client: input.client.withConfig({allowReconfigure: false}),\n sharedListener: input.sharedListener,\n id: input.id,\n remote: undefined,\n local: undefined,\n mutationEvents: [],\n stagedChanges: [],\n stashedChanges: [],\n error: undefined,\n fetchRemoteSnapshotAttempts: 0,\n submitTransactionsAttempts: 0,\n cache: input.cache,\n }),\n\n // Auto start the connection by default\n entry: ['connect to server-sent events'],\n\n on: {\n mutate: {\n actions: ['rebase local snapshot', 'stage mutation'],\n },\n },\n initial: 'disconnected',\n states: {\n disconnected: {\n on: {\n connect: {\n target: 'connecting',\n actions: ['listen to server-sent events'],\n },\n },\n },\n connecting: {\n on: {\n welcome: 'connected',\n reconnect: 'reconnecting',\n error: 'connectFailure',\n },\n tags: ['busy'],\n },\n connectFailure: {\n on: {\n connect: {\n target: 'connecting',\n actions: ['listen to server-sent events'],\n },\n },\n entry: [\n 'stop listening to server-sent events',\n 'assign error to context',\n ],\n exit: ['clear error from context'],\n tags: ['error'],\n },\n reconnecting: {\n on: {\n welcome: {\n target: 'connected',\n },\n error: {\n target: 'connectFailure',\n },\n },\n tags: ['busy', 'error'],\n },\n connected: {\n on: {\n mutation: {\n actions: ['buffer remote mutation events'],\n },\n reconnect: 'reconnecting',\n },\n entry: ['clear error from context'],\n initial: 'loading',\n states: {\n loading: {\n invoke: {\n src: 'fetch remote snapshot',\n id: 'getDocument',\n input: ({context}) => ({\n client: context.client,\n id: context.id,\n }),\n onError: {\n target: 'loadFailure',\n },\n onDone: {\n target: 'loaded',\n actions: [\n 'rebase fetched remote snapshot',\n 'reset fetch attempts',\n ],\n },\n },\n\n tags: ['busy'],\n },\n\n loaded: {\n entry: ['send sync event to parent'],\n on: {\n mutation: {\n actions: ['apply mendoza patch', 'send mutation event to parent'],\n },\n },\n initial: 'pristine',\n\n states: {\n pristine: {\n on: {\n mutate: {\n actions: ['rebase local snapshot', 'stage mutation'],\n target: 'dirty',\n },\n },\n tags: ['ready'],\n },\n dirty: {\n on: {\n submit: 'submitting',\n },\n tags: ['ready'],\n },\n submitting: {\n on: {\n mutate: {\n actions: ['rebase local snapshot', 'stash mutation'],\n },\n },\n invoke: {\n src: 'submit mutations as transactions',\n id: 'submitTransactions',\n input: ({context}) => {\n // @TODO perhaps separate utils to be lower level and operate on single documents at a time instead of expecting a local dataset\n const remoteDataset = new Map()\n remoteDataset.set(context.id, context.remote)\n return {\n client: context.client,\n transactions: toTransactions(\n // Squashing DMP strings is the last thing we do before submitting\n squashDMPStrings(\n remoteDataset,\n squashMutationGroups(context.stagedChanges),\n ),\n ),\n }\n },\n onError: {\n target: 'submitFailure',\n },\n\n onDone: {\n target: 'pristine',\n actions: [\n 'restore stashed changes',\n 'reset submit attempts',\n 'send pristine event to parent',\n ],\n },\n },\n /**\n * 'busy' means we should show a spinner, 'ready' means we can still accept mutations, they'll be applied optimistically right away, and queued for submissions after the current submission settles\n */\n tags: ['busy', 'ready'],\n },\n submitFailure: {\n exit: ['clear error from context'],\n after: {\n submitTransactionsTimeout: {\n actions: ['increment submit attempts'],\n target: 'submitting',\n },\n },\n on: {\n retry: 'submitting',\n },\n /**\n * How can it be both `ready` and `error`? `ready` means it can receive mutations, optimistically apply them, and queue them for submission. `error` means it failed to submit previously applied mutations.\n * It's completely fine to keep queueing up more mutations and applying them optimistically, while showing UI that notifies that mutations didn't submit, and show a count down until the next automatic retry.\n */\n tags: ['error', 'ready'],\n },\n },\n },\n\n loadFailure: {\n exit: ['clear error from context'],\n after: {\n fetchRemoteSnapshotTimeout: {\n actions: ['increment fetch attempts'],\n target: 'loading',\n },\n },\n on: {\n retry: 'loading',\n },\n tags: ['error'],\n },\n },\n },\n },\n})\n\nfunction applyMendozaPatch<const DocumentType extends SanityDocumentBase>(\n document: DocumentType | undefined,\n patch: RawPatch,\n nextRevision: string | undefined,\n) {\n const next = applyPatch(omitRev(document), patch)\n if (!next) {\n return null\n }\n return Object.assign(next, {_rev: nextRevision})\n}\n\nfunction omitRev<const DocumentType extends SanityDocumentBase>(\n document: DocumentType | undefined,\n) {\n if (!document) {\n return null\n }\n // eslint-disable-next-line unused-imports/no-unused-vars\n const {_rev, ...doc} = document\n return doc\n}\n"],"names":["share","filter","merge","shareReplay","setup","assign","raise","spawnChild","stopChild","assertEvent","enqueueActions","rebase","applyMutations","commit","sendParent","fromEventObservable","defer","observeOn","asapScheduler","fromPromise","encodeTransaction","toTransactions","squashDMPStrings","squashMutationGroups","applyPatch"],"mappings":";;;AAWO,SAAS,qBAAqB,QAAsB;AACzD,QAAM,aAAa,OAChB;AAAA,IACC;AAAA,IACA,CAAA;AAAA,IACA;AAAA,MACE,QAAQ,CAAC,WAAW,YAAY,WAAW;AAAA,MAC3C,eAAe;AAAA,MACf,yBAAyB;AAAA,MACzB,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,kBAAkB;AAAA,IAAA;AAAA,EACpB,EAED,KAAKA,KAAAA,MAAM,EAAC,qBAAqB,IAAK,CAAC,GAGpC,YAAY,WAAW;AAAA,IAC3BC,KAAAA,OAAO,CAAC,UAAmC,MAAM,SAAS,WAAW;AAAA,EAAA,GAIjE,UAAU,WAAW;AAAA,IACzBA,KAAAA,OAAO,CAAC,UAAiC,MAAM,SAAS,SAAS;AAAA,EAAA,GAI7D,YAAY,WAAW;AAAA,IAC3BA,KAAAA,OAAO,CAAC,UAAkC,MAAM,SAAS,UAAU;AAAA,EAAA,GAU/D,gBANkBC,KAAAA,MAAM,SAAS,SAAS,E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AM,GAAG,IAAA,IAAO;AACvB,SAAO;AACT;;;"}
import "./_chunks-dts/index.cjs";
import { AnyArray, AnyEmptyArray, ByIndex, Concat, ConcatInner, Digit, ElementType, Err, FindBy, FindInArray, Index, KeyedPathElement, Merge, MergeInner, Ok, OnlyDigits, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, Path, PathElement, PropertyName, Result, SafePath, Split, SplitAll, StringToPath, StripError, ToArray, ToNumber, Trim, TrimLeft, TrimRight, Try, Unwrap } from "./_chunks-dts/types.cjs";
import { Get, GetAtPath, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify } from "./_chunks-dts/predicates.cjs";
import { AnyOp, ArrayOp, AssignOp, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, IncOp, InsertIfMissingOp, InsertOp, Mutation, NodePatch, NodePatchList, NumberOp, ObjectOp, Operation, PatchMutation, PatchOptions, PrimitiveOp, RelativePosition, RemoveOp, ReplaceOp, SanityDocumentBase, SetIfMissingOp, SetOp, StringOp, Transaction, TruncateOp, UnassignOp, UnsetOp, UpsertOp } from "./_chunks-dts/types2.cjs";
import "./_chunks-dts/types3.cjs";
import { Conflict, DocumentMap, MutationGroup, MutationResult, NonTransactionalMutationGroup, OptimisticDocumentEvent, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, SubmitResult, TransactionalMutationGroup } from "./_chunks-dts/types4.cjs";
import { RawPatch } from "mendoza";
import * as rxjs0 from "rxjs";
import * as _sanity_client5 from "@sanity/client";
import { MutationEvent, ReconnectEvent, SanityClient, SanityDocument, WelcomeEvent } from "@sanity/client";
import * as xstate43 from "xstate";
interface UpdateResult<T extends SanityDocumentBase> {
id: string;
status: 'created' | 'updated' | 'deleted';
before?: T;
after?: T;
mutations: Mutation[];
}
/**
* Takes a list of mutations and applies them to documents in a documentMap
*/
interface DataStore {
get: (id: string) => SanityDocumentBase | undefined;
}
/**
* Creates a single, shared, listener EventSource that strems remote mutations, and notifies when it's online (welcome), offline (reconnect).
*/
declare function createSharedListener(client: SanityClient): rxjs0.Observable<ReconnectEvent | WelcomeEvent | MutationEvent>;
interface DocumentMutatorMachineInput {
id: string;
client: SanityClient;
/** A shared listener can be provided, if not it'll be created using `client.listen()` */
sharedListener?: ReturnType<typeof createSharedListener>;
cache?: Map<string, SanityDocument | null>;
}
type DocumentMutatorMachineParentEvent = {
type: 'sync';
id: string;
document: SanityDocumentBase;
} | {
type: 'mutation';
id: string;
effects: {
apply: RawPatch;
};
previousRev: string;
resultRev: string;
} | {
type: 'rebased.local';
id: string;
document: SanityDocumentBase;
} | {
type: 'rebased.remote';
id: string;
document: SanityDocumentBase;
} | {
type: 'pristine';
id: string;
};
declare const documentMutatorMachine: xstate43.StateMachine<{
client: SanityClient;
/** A shared listener can be provided, if not it'll be created using `client.listen()` */
sharedListener?: ReturnType<typeof createSharedListener>;
/** The document id */
id: string;
cache?: Map<string, SanityDocument | null>;
remote: SanityDocument | null | undefined;
local: SanityDocument | null | undefined;
mutationEvents: MutationEvent[];
stagedChanges: MutationGroup[];
stashedChanges: MutationGroup[];
error: unknown;
fetchRemoteSnapshotAttempts: number;
submitTransactionsAttempts: number;
}, _sanity_client5.ReconnectEvent | _sanity_client5.WelcomeEvent | MutationEvent | {
type: "error";
} | {
type: "retry";
} | {
type: "connect";
} | {
type: "reconnect";
} | {
type: "welcome";
} | {
type: "mutate";
mutations: Mutation[];
} | {
type: "submit";
} | {
type: "xstate.done.actor.getDocument";
output: SanityDocument;
} | {
type: "xstate.done.actor.submitTransactions";
output: undefined;
}, {
[x: string]: xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void | SanityDocument<Record<string, any>> | undefined, {
client: SanityClient;
id: string;
}, xstate43.EventObject>> | xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void, {
client: SanityClient;
transactions: Transaction[];
}, xstate43.EventObject>> | xstate43.ActorRefFromLogic<xstate43.ObservableActorLogic<_sanity_client5.ReconnectEvent | _sanity_client5.WelcomeEvent | MutationEvent, {
listener: ReturnType<typeof createSharedListener>;
id: string;
}, xstate43.EventObject>> | undefined;
getDocument?: xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void | SanityDocument<Record<string, any>> | undefined, {
client: SanityClient;
id: string;
}, xstate43.EventObject>> | undefined;
submitTransactions?: xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void, {
client: SanityClient;
transactions: Transaction[];
}, xstate43.EventObject>> | undefined;
}, {
src: "fetch remote snapshot";
logic: xstate43.PromiseActorLogic<void | SanityDocument<Record<string, any>> | undefined, {
client: SanityClient;
id: string;
}, xstate43.EventObject>;
id: "getDocument";
} | {
src: "submit mutations as transactions";
logic: xstate43.PromiseActorLogic<void, {
client: SanityClient;
transactions: Transaction[];
}, xstate43.EventObject>;
id: "submitTransactions";
} | {
src: "server-sent events";
logic: xstate43.ObservableActorLogic<_sanity_client5.ReconnectEvent | _sanity_client5.WelcomeEvent | MutationEvent, {
listener: ReturnType<typeof createSharedListener>;
id: string;
}, xstate43.EventObject>;
id: string | undefined;
}, {
type: "assign error to context";
params: xstate43.NonReducibleUnknown;
} | {
type: "clear error from context";
params: xstate43.NonReducibleUnknown;
} | {
type: "connect to server-sent events";
params: xstate43.NonReducibleUnknown;
} | {
type: "listen to server-sent events";
params: xstate43.NonReducibleUnknown;
} | {
type: "stop listening to server-sent events";
params: xstate43.NonReducibleUnknown;
} | {
type: "buffer remote mutation events";
params: xstate43.NonReducibleUnknown;
} | {
type: "restore stashed changes";
params: xstate43.NonReducibleUnknown;
} | {
type: "rebase fetched remote snapshot";
params: xstate43.NonReducibleUnknown;
} | {
type: "apply mendoza patch";
params: xstate43.NonReducibleUnknown;
} | {
type: "increment fetch attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "reset fetch attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "increment submit attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "reset submit attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "stage mutation";
params: xstate43.NonReducibleUnknown;
} | {
type: "stash mutation";
params: xstate43.NonReducibleUnknown;
} | {
type: "rebase local snapshot";
params: xstate43.NonReducibleUnknown;
} | {
type: "send pristine event to parent";
params: xstate43.NonReducibleUnknown;
} | {
type: "send sync event to parent";
params: xstate43.NonReducibleUnknown;
} | {
type: "send mutation event to parent";
params: xstate43.NonReducibleUnknown;
}, never, "fetchRemoteSnapshotTimeout" | "submitTransactionsTimeout", "disconnected" | "connecting" | "reconnecting" | "connectFailure" | {
connected: "loading" | "loadFailure" | {
loaded: "pristine" | "dirty" | "submitting" | "submitFailure";
};
}, "busy" | "error" | "ready", DocumentMutatorMachineInput, xstate43.NonReducibleUnknown, xstate43.EventObject, xstate43.MetaObject, {
id: "document-mutator";
states: {
readonly disconnected: {};
readonly connecting: {};
readonly connectFailure: {};
readonly reconnecting: {};
readonly connected: {
states: {
readonly loading: {};
readonly loaded: {
states: {
readonly pristine: {};
readonly dirty: {};
readonly submitting: {};
readonly submitFailure: {};
};
};
readonly loadFailure: {};
};
};
};
}>;
export { AnyArray, AnyEmptyArray, AnyOp, ArrayOp, AssignOp, ByIndex, Concat, ConcatInner, Conflict, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DataStore, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, DocumentMap, DocumentMutatorMachineInput, DocumentMutatorMachineParentEvent, ElementType, Err, FindBy, FindInArray, Get, GetAtPath, IncOp, Index, InsertIfMissingOp, InsertOp, KeyedPathElement, Merge, MergeInner, Mutation, MutationGroup, MutationResult, NodePatch, NodePatchList, NonTransactionalMutationGroup, NumberOp, ObjectOp, Ok, OnlyDigits, Operation, OptimisticDocumentEvent, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, RelativePosition, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, RemoveOp, ReplaceOp, Result, SafePath, SanityDocumentBase, SetIfMissingOp, SetOp, Split, SplitAll, StringOp, StringToPath, StripError, SubmitResult, ToArray, ToNumber, Transaction, TransactionalMutationGroup, Trim, TrimLeft, TrimRight, TruncateOp, Try, UnassignOp, UnsetOp, Unwrap, UpdateResult, UpsertOp, createSharedListener, documentMutatorMachine, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify };
//# sourceMappingURL=_unstable_machine.d.cts.map
{"version":3,"file":"_unstable_machine.d.cts","names":[],"sources":["../src/store/documentMap/applyMutations.ts","../src/store/optimistic/optimizations/squashDMPStrings.ts","../src/machine/listener.ts","../src/machine/documentMutatorMachine.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;UAKiB,uBAAuB;;;WAG7B;UACD;aACG;;;;;UCDI,SAAA;uBACM;;;;;iBCCP,oBAAA,SAA6B,eAAY,KAAA,CAAA,WAAA,iBAAA,eAAA;UCyBxC,2BAAA;;UAEP;;mBAES,kBAAkB;UAE3B,YAAY;AHrCtB;AAA6B,KGwCjB,iCAAA,GHxCiB;MAAW,EAAA,MAAA;MAG7B,MAAA;UACD,EGqC+B,kBHrC/B;;EACW,IAAA,EAAA,UAAA;;ECDJ,OAAA,EAAA;WEyCM;EDvCP,CAAA;EAAoB,WAAA,EAAA,MAAA;WAAS,EAAA,MAAA;;MAAY,EAAA,eAAA;MAAA,MAAA;UAAA,EC2CP,kBD3CO;CAAA,GAAA;;ECyBxC,EAAA,EAAA,MAAA;EAA2B,QAAA,EAmBO,kBAnBP;;MAIP,EAAA,UAAA;MAAlB,MAAA;;AAET,cAgBG,sBAhBH,WAgByB,YAhBzB,CAAA;EAAG,MAAA,EAwBC,YAxBD;EAGD;EAAiC,cAAA,CAAA,EAuBtB,U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AA;MAzCnB,oBAAA;;KAAR,EAAA,oBAAA;;cAAV,kBAAkB;;KAAR,QAAA,CAAA,WAAA;;;;;;;;;;;;;;;;;;;;;iCA5QD;EAAA,MAAA,8BAAA"}
import "./_chunks-dts/index.js";
import { AnyArray, AnyEmptyArray, ByIndex, Concat, ConcatInner, Digit, ElementType, Err, FindBy, FindInArray, Index, KeyedPathElement, Merge, MergeInner, Ok, OnlyDigits, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, Path, PathElement, PropertyName, Result, SafePath, Split, SplitAll, StringToPath, StripError, ToArray, ToNumber, Trim, TrimLeft, TrimRight, Try, Unwrap } from "./_chunks-dts/types.js";
import { Get, GetAtPath, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify } from "./_chunks-dts/predicates.js";
import { AnyOp, ArrayOp, AssignOp, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, IncOp, InsertIfMissingOp, InsertOp, Mutation, NodePatch, NodePatchList, NumberOp, ObjectOp, Operation, PatchMutation, PatchOptions, PrimitiveOp, RelativePosition, RemoveOp, ReplaceOp, SanityDocumentBase, SetIfMissingOp, SetOp, StringOp, Transaction, TruncateOp, UnassignOp, UnsetOp, UpsertOp } from "./_chunks-dts/types2.js";
import "./_chunks-dts/types3.js";
import { Conflict, DocumentMap, MutationGroup, MutationResult, NonTransactionalMutationGroup, OptimisticDocumentEvent, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, SubmitResult, TransactionalMutationGroup } from "./_chunks-dts/types4.js";
import { RawPatch } from "mendoza";
import * as rxjs0 from "rxjs";
import * as _sanity_client5 from "@sanity/client";
import { MutationEvent, ReconnectEvent, SanityClient, SanityDocument, WelcomeEvent } from "@sanity/client";
import * as xstate43 from "xstate";
interface UpdateResult<T extends SanityDocumentBase> {
id: string;
status: 'created' | 'updated' | 'deleted';
before?: T;
after?: T;
mutations: Mutation[];
}
/**
* Takes a list of mutations and applies them to documents in a documentMap
*/
interface DataStore {
get: (id: string) => SanityDocumentBase | undefined;
}
/**
* Creates a single, shared, listener EventSource that strems remote mutations, and notifies when it's online (welcome), offline (reconnect).
*/
declare function createSharedListener(client: SanityClient): rxjs0.Observable<ReconnectEvent | WelcomeEvent | MutationEvent>;
interface DocumentMutatorMachineInput {
id: string;
client: SanityClient;
/** A shared listener can be provided, if not it'll be created using `client.listen()` */
sharedListener?: ReturnType<typeof createSharedListener>;
cache?: Map<string, SanityDocument | null>;
}
type DocumentMutatorMachineParentEvent = {
type: 'sync';
id: string;
document: SanityDocumentBase;
} | {
type: 'mutation';
id: string;
effects: {
apply: RawPatch;
};
previousRev: string;
resultRev: string;
} | {
type: 'rebased.local';
id: string;
document: SanityDocumentBase;
} | {
type: 'rebased.remote';
id: string;
document: SanityDocumentBase;
} | {
type: 'pristine';
id: string;
};
declare const documentMutatorMachine: xstate43.StateMachine<{
client: SanityClient;
/** A shared listener can be provided, if not it'll be created using `client.listen()` */
sharedListener?: ReturnType<typeof createSharedListener>;
/** The document id */
id: string;
cache?: Map<string, SanityDocument | null>;
remote: SanityDocument | null | undefined;
local: SanityDocument | null | undefined;
mutationEvents: MutationEvent[];
stagedChanges: MutationGroup[];
stashedChanges: MutationGroup[];
error: unknown;
fetchRemoteSnapshotAttempts: number;
submitTransactionsAttempts: number;
}, _sanity_client5.ReconnectEvent | _sanity_client5.WelcomeEvent | MutationEvent | {
type: "error";
} | {
type: "retry";
} | {
type: "connect";
} | {
type: "reconnect";
} | {
type: "welcome";
} | {
type: "mutate";
mutations: Mutation[];
} | {
type: "submit";
} | {
type: "xstate.done.actor.getDocument";
output: SanityDocument;
} | {
type: "xstate.done.actor.submitTransactions";
output: undefined;
}, {
[x: string]: xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void | SanityDocument<Record<string, any>> | undefined, {
client: SanityClient;
id: string;
}, xstate43.EventObject>> | xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void, {
client: SanityClient;
transactions: Transaction[];
}, xstate43.EventObject>> | xstate43.ActorRefFromLogic<xstate43.ObservableActorLogic<_sanity_client5.ReconnectEvent | _sanity_client5.WelcomeEvent | MutationEvent, {
listener: ReturnType<typeof createSharedListener>;
id: string;
}, xstate43.EventObject>> | undefined;
getDocument?: xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void | SanityDocument<Record<string, any>> | undefined, {
client: SanityClient;
id: string;
}, xstate43.EventObject>> | undefined;
submitTransactions?: xstate43.ActorRefFromLogic<xstate43.PromiseActorLogic<void, {
client: SanityClient;
transactions: Transaction[];
}, xstate43.EventObject>> | undefined;
}, {
src: "fetch remote snapshot";
logic: xstate43.PromiseActorLogic<void | SanityDocument<Record<string, any>> | undefined, {
client: SanityClient;
id: string;
}, xstate43.EventObject>;
id: "getDocument";
} | {
src: "submit mutations as transactions";
logic: xstate43.PromiseActorLogic<void, {
client: SanityClient;
transactions: Transaction[];
}, xstate43.EventObject>;
id: "submitTransactions";
} | {
src: "server-sent events";
logic: xstate43.ObservableActorLogic<_sanity_client5.ReconnectEvent | _sanity_client5.WelcomeEvent | MutationEvent, {
listener: ReturnType<typeof createSharedListener>;
id: string;
}, xstate43.EventObject>;
id: string | undefined;
}, {
type: "assign error to context";
params: xstate43.NonReducibleUnknown;
} | {
type: "clear error from context";
params: xstate43.NonReducibleUnknown;
} | {
type: "connect to server-sent events";
params: xstate43.NonReducibleUnknown;
} | {
type: "listen to server-sent events";
params: xstate43.NonReducibleUnknown;
} | {
type: "stop listening to server-sent events";
params: xstate43.NonReducibleUnknown;
} | {
type: "buffer remote mutation events";
params: xstate43.NonReducibleUnknown;
} | {
type: "restore stashed changes";
params: xstate43.NonReducibleUnknown;
} | {
type: "rebase fetched remote snapshot";
params: xstate43.NonReducibleUnknown;
} | {
type: "apply mendoza patch";
params: xstate43.NonReducibleUnknown;
} | {
type: "increment fetch attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "reset fetch attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "increment submit attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "reset submit attempts";
params: xstate43.NonReducibleUnknown;
} | {
type: "stage mutation";
params: xstate43.NonReducibleUnknown;
} | {
type: "stash mutation";
params: xstate43.NonReducibleUnknown;
} | {
type: "rebase local snapshot";
params: xstate43.NonReducibleUnknown;
} | {
type: "send pristine event to parent";
params: xstate43.NonReducibleUnknown;
} | {
type: "send sync event to parent";
params: xstate43.NonReducibleUnknown;
} | {
type: "send mutation event to parent";
params: xstate43.NonReducibleUnknown;
}, never, "fetchRemoteSnapshotTimeout" | "submitTransactionsTimeout", "disconnected" | "connecting" | "reconnecting" | "connectFailure" | {
connected: "loading" | "loadFailure" | {
loaded: "pristine" | "dirty" | "submitting" | "submitFailure";
};
}, "busy" | "error" | "ready", DocumentMutatorMachineInput, xstate43.NonReducibleUnknown, xstate43.EventObject, xstate43.MetaObject, {
id: "document-mutator";
states: {
readonly disconnected: {};
readonly connecting: {};
readonly connectFailure: {};
readonly reconnecting: {};
readonly connected: {
states: {
readonly loading: {};
readonly loaded: {
states: {
readonly pristine: {};
readonly dirty: {};
readonly submitting: {};
readonly submitFailure: {};
};
};
readonly loadFailure: {};
};
};
};
}>;
export { AnyArray, AnyEmptyArray, AnyOp, ArrayOp, AssignOp, ByIndex, Concat, ConcatInner, Conflict, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DataStore, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, DocumentMap, DocumentMutatorMachineInput, DocumentMutatorMachineParentEvent, ElementType, Err, FindBy, FindInArray, Get, GetAtPath, IncOp, Index, InsertIfMissingOp, InsertOp, KeyedPathElement, Merge, MergeInner, Mutation, MutationGroup, MutationResult, NodePatch, NodePatchList, NonTransactionalMutationGroup, NumberOp, ObjectOp, Ok, OnlyDigits, Operation, OptimisticDocumentEvent, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, RelativePosition, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, RemoveOp, ReplaceOp, Result, SafePath, SanityDocumentBase, SetIfMissingOp, SetOp, Split, SplitAll, StringOp, StringToPath, StripError, SubmitResult, ToArray, ToNumber, Transaction, TransactionalMutationGroup, Trim, TrimLeft, TrimRight, TruncateOp, Try, UnassignOp, UnsetOp, Unwrap, UpdateResult, UpsertOp, createSharedListener, documentMutatorMachine, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify };
//# sourceMappingURL=_unstable_machine.d.ts.map
{"version":3,"file":"_unstable_machine.d.ts","names":[],"sources":["../src/store/documentMap/applyMutations.ts","../src/store/optimistic/optimizations/squashDMPStrings.ts","../src/machine/listener.ts","../src/machine/documentMutatorMachine.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;UAKiB,uBAAuB;;;WAG7B;UACD;aACG;;;;;UCDI,SAAA;uBACM;;;;;iBCCP,oBAAA,SAA6B,eAAY,KAAA,CAAA,WAAA,iBAAA,eAAA;UCyBxC,2BAAA;;UAEP;;mBAES,kBAAkB;UAE3B,YAAY;AHrCtB;AAA6B,KGwCjB,iCAAA,GHxCiB;MAAW,EAAA,MAAA;MAG7B,MAAA;UACD,EGqC+B,kBHrC/B;;EACW,IAAA,EAAA,UAAA;;ECDJ,OAAA,EAAA;WEyCM;EDvCP,CAAA;EAAoB,WAAA,EAAA,MAAA;WAAS,EAAA,MAAA;;MAAY,EAAA,eAAA;MAAA,MAAA;UAAA,EC2CP,kBD3CO;CAAA,GAAA;;ECyBxC,EAAA,EAAA,MAAA;EAA2B,QAAA,EAmBO,kBAnBP;;MAIP,EAAA,UAAA;MAAlB,MAAA;;AAET,cAgBG,sBAhBH,WAgByB,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A;MAqBZ,aAAA;;KAAuC,EAAA,kCAAA;;YAAvC;kBAA4B;KAAW,QAAA,CAAA,WAAA;MAzCnB,oBAAA;;KAAR,EAAA,oBAAA;;cAAV,kBAAkB;;KAAR,QAAA,CAAA,WAAA;;;;;;;;;;;;;;;;;;;;;iCA5QD;EAAA,MAAA,8BAAA"}
import { applyPatch } from "mendoza";
import { share, filter, merge, shareReplay, defer, observeOn, asapScheduler } from "rxjs";
import { setup, fromPromise, fromEventObservable, sendParent, enqueueActions, assign, stopChild, spawnChild, raise, assertEvent } from "xstate";
import { encodeTransaction } from "./_chunks-es/encode.js";
import { applyMutations, commit, rebase, toTransactions, squashDMPStrings, squashMutationGroups } from "./_chunks-es/createOptimisticStore.js";
function createSharedListener(client) {
const allEvents$ = client.listen(
'*[!(_id in path("_.**"))]',
{},
{
events: ["welcome", "mutation", "reconnect"],
includeResult: !1,
includePreviousRevision: !1,
visibility: "transaction",
effectFormat: "mendoza",
includeMutations: !1
}
).pipe(share({ resetOnRefCountZero: !0 })), reconnect = allEvents$.pipe(
filter((event) => event.type === "reconnect")
), welcome = allEvents$.pipe(
filter((event) => event.type === "welcome")
), mutations = allEvents$.pipe(
filter((event) => event.type === "mutation")
), replayWelcome = merge(welcome, reconnect).pipe(
shareReplay({ bufferSize: 1, refCount: !0 })
).pipe(
filter((latestConnectionEvent) => latestConnectionEvent.type === "welcome")
);
return merge(replayWelcome, mutations, reconnect);
}
const documentMutatorMachine = setup({
types: {},
actions: {
"assign error to context": assign({ error: ({ event }) => event }),
"clear error from context": assign({ error: void 0 }),
"connect to server-sent events": raise({ type: "connect" }),
"listen to server-sent events": spawnChild("server-sent events", {
id: "listener",
input: ({ context }) => ({
listener: context.sharedListener || createSharedListener(context.client),
id: context.id
})
}),
"stop listening to server-sent events": stopChild("listener"),
"buffer remote mutation events": assign({
mutationEvents: ({ event, context }) => (assertEvent(event, "mutation"), [...context.mutationEvents, event])
}),
"restore stashed changes": assign({
stagedChanges: ({ event, context }) => (assertEvent(event, "xstate.done.actor.submitTransactions"), context.stashedChanges),
stashedChanges: []
}),
"rebase fetched remote snapshot": enqueueActions(({ enqueue }) => {
enqueue.assign(({ event, context }) => {
assertEvent(event, "xstate.done.actor.getDocument");
const previousRemote = context.remote;
let nextRemote = event.output, seenCurrentRev = !1;
for (const patch of context.mutationEvents)
!patch.effects?.apply || !patch.previousRev && patch.transition !== "appear" || (!seenCurrentRev && patch.previousRev === nextRemote?._rev && (seenCurrentRev = !0), seenCurrentRev && (nextRemote = applyMendozaPatch(
nextRemote,
patch.effects.apply,
patch.resultRev
)));
context.cache && // If the shared cache don't have the document already we can just set it
(!context.cache.has(context.id) || // But when it's in the cache, make sure it's necessary to update it
context.cache.get(context.id)._rev !== nextRemote?._rev) && context.cache.set(context.id, nextRemote);
const [stagedChanges, local] = rebase(
context.id,
// It's annoying to convert between null and undefined, reach consensus
previousRemote === null ? void 0 : previousRemote,
nextRemote === null ? void 0 : nextRemote,
context.stagedChanges
);
return {
remote: nextRemote,
local,
stagedChanges,
// Since the snapshot handler applies all the patches they are no longer needed, allow GC
mutationEvents: []
};
}), enqueue.sendParent(
({ context }) => ({
type: "rebased.remote",
id: context.id,
document: context.remote
})
);
}),
"apply mendoza patch": assign(({ event, context }) => {
assertEvent(event, "mutation");
const previousRemote = context.remote;
if (event.transactionId === previousRemote?._rev)
return {};
const nextRemote = applyMendozaPatch(
previousRemote,
event.effects.apply,
event.resultRev
);
context.cache && // If the shared cache don't have the document already we can just set it
(!context.cache.has(context.id) || // But when it's in the cache, make sure it's necessary to update it
context.cache.get(context.id)._rev !== nextRemote?._rev) && context.cache.set(context.id, nextRemote);
const [stagedChanges, local] = rebase(
context.id,
// It's annoying to convert between null and undefined, reach consensus
previousRemote === null ? void 0 : previousRemote,
nextRemote === null ? void 0 : nextRemote,
context.stagedChanges
);
return {
remote: nextRemote,
local,
stagedChanges
};
}),
"increment fetch attempts": assign({
fetchRemoteSnapshotAttempts: ({ context }) => context.fetchRemoteSnapshotAttempts + 1
}),
"reset fetch attempts": assign({
fetchRemoteSnapshotAttempts: 0
}),
"increment submit attempts": assign({
submitTransactionsAttempts: ({ context }) => context.submitTransactionsAttempts + 1
}),
"reset submit attempts": assign({
submitTransactionsAttempts: 0
}),
"stage mutation": assign({
stagedChanges: ({ event, context }) => (assertEvent(event, "mutate"), [
...context.stagedChanges,
{ transaction: !1, mutations: event.mutations }
])
}),
"stash mutation": assign({
stashedChanges: ({ event, context }) => (assertEvent(event, "mutate"), [
...context.stashedChanges,
{ transaction: !1, mutations: event.mutations }
])
}),
"rebase local snapshot": enqueueActions(({ enqueue }) => {
enqueue.assign({
local: ({ event, context }) => {
assertEvent(event, "mutate");
const localDataset = /* @__PURE__ */ new Map();
context.local && localDataset.set(context.id, context.local);
const results = applyMutations(event.mutations, localDataset);
return commit(results, localDataset), localDataset.get(context.id);
}
}), enqueue.sendParent(
({ context }) => ({
type: "rebased.local",
id: context.id,
document: context.local
})
);
}),
"send pristine event to parent": sendParent(
({ context }) => ({
type: "pristine",
id: context.id
})
),
"send sync event to parent": sendParent(
({ context }) => ({
type: "sync",
id: context.id,
document: context.remote
})
),
"send mutation event to parent": sendParent(({ context, event }) => (assertEvent(event, "mutation"), {
type: "mutation",
id: context.id,
previousRev: event.previousRev,
resultRev: event.resultRev,
effects: event.effects
}))
},
actors: {
"server-sent events": fromEventObservable(
({
input
}) => {
const { listener, id } = input;
return defer(() => listener).pipe(
filter(
(event) => event.type === "welcome" || event.type === "reconnect" || event.type === "mutation" && event.documentId === id
),
// This is necessary to avoid sync emitted events from `shareReplay` from happening before the actor is ready to receive them
observeOn(asapScheduler)
);
}
),
"fetch remote snapshot": fromPromise(
async ({
input,
signal
}) => {
const { client, id } = input;
return await client.getDocument(id, {
signal
}).catch((e) => {
if (!(e instanceof Error && e.name === "AbortError"))
throw e;
});
}
),
"submit mutations as transactions": fromPromise(
async ({
input,
signal
}) => {
const { client, transactions } = input;
for (const transaction of transactions) {
if (signal.aborted) return;
await client.dataRequest("mutate", encodeTransaction(transaction), {
visibility: "async",
returnDocuments: !1,
signal
}).catch((e) => {
if (!(e instanceof Error && e.name === "AbortError"))
throw e;
});
}
}
)
},
delays: {
// Exponential backoff delay function
fetchRemoteSnapshotTimeout: ({ context }) => Math.pow(2, context.fetchRemoteSnapshotAttempts) * 1e3,
submitTransactionsTimeout: ({ context }) => Math.pow(2, context.submitTransactionsAttempts) * 1e3
}
}).createMachine({
/** @xstate-layout N4IgpgJg5mDOIC5QQPYGMCuBbMA7ALgLRYb4CG+KATgMQnn5gDaADALqKgAOKsAlvj4pcnEAA9EADhYAWAHQA2GSwUBmAKwBOaQEZJkhQBoQAT0Q6ATAF8rx1JhwFipCtTkQ+sNMNxg0jCBpvXF9-Vg4kEB5+QWFRCQQLFhY5PQB2dRU1SQsdGSVjMwRlHTkWNM00nR1VKryKmzt0bDwielcqOWDQwVwoGgB3MAAbbxxw0WiBIRFIhPUKuQ1NVU0tTU0WFdVCxAt1dTlNhX2WdRltGUk061sQexandspO7r9e-qo-H3eJyKnYrNQPNJJollpVutNttdghVCo5MoTgoMpo8jIkqpGvdmo42i4Xl0fv4+H0aGAqFRqH9uLxpnE5ogFrCLFd5CtNBYFJkdOpuaosXcHnjnAw3G9-AAxMh8YYYL5BYn4GlROmA+KIFEs1R6ORpZYWHIXGR6bHC1qijpyL4Sj6DEZjZjsSZqmYaxK1ORcvlc-ZqSoyNKwnRpGTyK4WDK5BQ6BQ5BRm3EW55uG1K0n9ClUqgqgFuxketJe7nIv2rUNB0x7LmSL2qGMsSySevcmSJhzJgnipWQOgEma510M4HmcqHZYyWqaOMqTQyWGh0osVSGiwC5uGyftx74sWvHuBNMhX7O-5DoHiPae72lvnlwPBydFlRVS7qPIl7cilP74-+SByMMKBkB4ZKoL4cikgAbigADWYByDA+AACJJgQg4xPmI7FHkZQrKGsjqKcCiaMG9YpJOxySBiCiyPoX6dnuRJ-gEgHAaBmaUm4XDDBQABm1BYIhYAoWhyqnrSmHDpeCAKCicjUbU6g6n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xMHXWOTWJV2avFRKpIwARILJRGJBF4mZBIkDE0KtIxLSSDkDYGhWl70Ru1Tq6zsLURBkoLyWRmz8PmlUZmcY1zXDKdMghcy2mIyFh8W5ZN4RFmOFyKaZwiLeT2GVJcy5pBrguCiMK2tvyDwBYbIWejOkSMQBkeQORJq0RNCUDIDNondxuGpPQmRqIXPhiPECuKMpdMkbILZ-SEnLxyjqOJMZsj1jRTYIAA */
id: "document-mutator",
context: ({ input }) => ({
client: input.client.withConfig({ allowReconfigure: !1 }),
sharedListener: input.sharedListener,
id: input.id,
remote: void 0,
local: void 0,
mutationEvents: [],
stagedChanges: [],
stashedChanges: [],
error: void 0,
fetchRemoteSnapshotAttempts: 0,
submitTransactionsAttempts: 0,
cache: input.cache
}),
// Auto start the connection by default
entry: ["connect to server-sent events"],
on: {
mutate: {
actions: ["rebase local snapshot", "stage mutation"]
}
},
initial: "disconnected",
states: {
disconnected: {
on: {
connect: {
target: "connecting",
actions: ["listen to server-sent events"]
}
}
},
connecting: {
on: {
welcome: "connected",
reconnect: "reconnecting",
error: "connectFailure"
},
tags: ["busy"]
},
connectFailure: {
on: {
connect: {
target: "connecting",
actions: ["listen to server-sent events"]
}
},
entry: [
"stop listening to server-sent events",
"assign error to context"
],
exit: ["clear error from context"],
tags: ["error"]
},
reconnecting: {
on: {
welcome: {
target: "connected"
},
error: {
target: "connectFailure"
}
},
tags: ["busy", "error"]
},
connected: {
on: {
mutation: {
actions: ["buffer remote mutation events"]
},
reconnect: "reconnecting"
},
entry: ["clear error from context"],
initial: "loading",
states: {
loading: {
invoke: {
src: "fetch remote snapshot",
id: "getDocument",
input: ({ context }) => ({
client: context.client,
id: context.id
}),
onError: {
target: "loadFailure"
},
onDone: {
target: "loaded",
actions: [
"rebase fetched remote snapshot",
"reset fetch attempts"
]
}
},
tags: ["busy"]
},
loaded: {
entry: ["send sync event to parent"],
on: {
mutation: {
actions: ["apply mendoza patch", "send mutation event to parent"]
}
},
initial: "pristine",
states: {
pristine: {
on: {
mutate: {
actions: ["rebase local snapshot", "stage mutation"],
target: "dirty"
}
},
tags: ["ready"]
},
dirty: {
on: {
submit: "submitting"
},
tags: ["ready"]
},
submitting: {
on: {
mutate: {
actions: ["rebase local snapshot", "stash mutation"]
}
},
invoke: {
src: "submit mutations as transactions",
id: "submitTransactions",
input: ({ context }) => {
const remoteDataset = /* @__PURE__ */ new Map();
return remoteDataset.set(context.id, context.remote), {
client: context.client,
transactions: toTransactions(
// Squashing DMP strings is the last thing we do before submitting
squashDMPStrings(
remoteDataset,
squashMutationGroups(context.stagedChanges)
)
)
};
},
onError: {
target: "submitFailure"
},
onDone: {
target: "pristine",
actions: [
"restore stashed changes",
"reset submit attempts",
"send pristine event to parent"
]
}
},
/**
* 'busy' means we should show a spinner, 'ready' means we can still accept mutations, they'll be applied optimistically right away, and queued for submissions after the current submission settles
*/
tags: ["busy", "ready"]
},
submitFailure: {
exit: ["clear error from context"],
after: {
submitTransactionsTimeout: {
actions: ["increment submit attempts"],
target: "submitting"
}
},
on: {
retry: "submitting"
},
/**
* How can it be both `ready` and `error`? `ready` means it can receive mutations, optimistically apply them, and queue them for submission. `error` means it failed to submit previously applied mutations.
* It's completely fine to keep queueing up more mutations and applying them optimistically, while showing UI that notifies that mutations didn't submit, and show a count down until the next automatic retry.
*/
tags: ["error", "ready"]
}
}
},
loadFailure: {
exit: ["clear error from context"],
after: {
fetchRemoteSnapshotTimeout: {
actions: ["increment fetch attempts"],
target: "loading"
}
},
on: {
retry: "loading"
},
tags: ["error"]
}
}
}
}
});
function applyMendozaPatch(document, patch, nextRevision) {
const next = applyPatch(omitRev(document), patch);
return next ? Object.assign(next, { _rev: nextRevision }) : null;
}
function omitRev(document) {
if (!document)
return null;
const { _rev, ...doc } = document;
return doc;
}
export {
createSharedListener,
documentMutatorMachine
};
//# sourceMappingURL=_unstable_machine.js.map
{"version":3,"file":"_unstable_machine.js","sources":["../src/machine/listener.ts","../src/machine/documentMutatorMachine.ts"],"sourcesContent":["import {\n type MutationEvent,\n type ReconnectEvent,\n type SanityClient,\n type WelcomeEvent,\n} from '@sanity/client'\nimport {filter, merge, type ObservedValueOf, share, shareReplay} from 'rxjs'\n\n/**\n * Creates a single, shared, listener EventSource that strems remote mutations, and notifies when it's online (welcome), offline (reconnect).\n */\nexport function createSharedListener(client: SanityClient) {\n const allEvents$ = client\n .listen(\n '*[!(_id in path(\"_.**\"))]',\n {},\n {\n events: ['welcome', 'mutation', 'reconnect'],\n includeResult: false,\n includePreviousRevision: false,\n visibility: 'transaction',\n effectFormat: 'mendoza',\n includeMutations: false,\n },\n )\n .pipe(share({resetOnRefCountZero: true}))\n\n // Reconnect events emitted in case the connection is lost\n const reconnect = allEvents$.pipe(\n filter((event): event is ReconnectEvent => event.type === 'reconnect'),\n )\n\n // Welcome events are emitted when the listener is (re)connected\n const welcome = allEvents$.pipe(\n filter((event): event is WelcomeEvent => event.type === 'welcome'),\n )\n\n // Mutation events coming from the listener\n const mutations = allEvents$.pipe(\n filter((event): event is MutationEvent => event.type === 'mutation'),\n )\n\n // Replay the latest connection event that was emitted either when the connection was disconnected ('reconnect'), established or re-established ('welcome')\n const connectionEvent = merge(welcome, reconnect).pipe(\n shareReplay({bufferSize: 1, refCount: true}),\n )\n\n // Emit the welcome event if the latest connection event was the 'welcome' event.\n // Downstream subscribers will typically map the welcome event to an initial fetch\n const replayWelcome = connectionEvent.pipe(\n filter(latestConnectionEvent => latestConnectionEvent.type === 'welcome'),\n )\n\n // Combine into a single stream\n return merge(replayWelcome, mutations, reconnect)\n}\n\nexport type SharedListenerEvents = ObservedValueOf<\n ReturnType<typeof createSharedListener>\n>\n","import {\n type MutationEvent,\n type SanityClient,\n type SanityDocument,\n} from '@sanity/client'\nimport {applyPatch, type RawPatch} from 'mendoza'\nimport {asapScheduler, defer, filter, observeOn} from 'rxjs'\nimport {\n assertEvent,\n assign,\n enqueueActions,\n fromEventObservable,\n fromPromise,\n raise,\n sendParent,\n setup,\n spawnChild,\n stopChild,\n} from 'xstate'\n\nimport {encodeTransaction, type Mutation} from '../encoders/sanity'\nimport {\n type MutationGroup,\n type SanityDocumentBase,\n type Transaction,\n} from '../store'\nimport {applyMutations} from '../store/documentMap/applyMutations'\nimport {commit} from '../store/documentMap/commit'\nimport {createSharedListener, type SharedListenerEvents} from './listener'\nimport { squashDMPStrings } from '../store/optimistic/optimizations/squashDMPStrings'\nimport { rebase } from '../store/optimistic/rebase'\nimport { squashMutationGroups } from '../store/optimistic/optimizations/squashMutations'\nimport { toTransactions } from '../store/optimistic/createOptimisticStore'\n\nexport {createSharedListener}\n\nexport interface DocumentMutatorMachineInput {\n id: string\n client: SanityClient\n /** A shared listener can be provided, if not it'll be created using `client.listen()` */\n sharedListener?: ReturnType<typeof createSharedListener>\n /* Preferrably a LRU cache map that is compatible with an ES6 Map, and have documents that allow unique ids to a particular dataset */\n cache?: Map<string, SanityDocument | null>\n}\n\nexport type DocumentMutatorMachineParentEvent =\n | {type: 'sync'; id: string; document: SanityDocumentBase}\n | {\n type: 'mutation'\n id: string\n effects: {apply: RawPatch}\n previousRev: string\n resultRev: string\n }\n | {type: 'rebased.local'; id: string; document: SanityDocumentBase}\n | {type: 'rebased.remote'; id: string; document: SanityDocumentBase}\n | {type: 'pristine'; id: string}\n\nexport const documentMutatorMachine = setup({\n types: {} as {\n children: {\n getDocument: 'fetch remote snapshot'\n submitTransactions: 'submit mutations as transactions'\n }\n tags: 'busy' | 'error' | 'ready'\n context: {\n client: SanityClient\n /** A shared listener can be provided, if not it'll be created using `client.listen()` */\n sharedListener?: ReturnType<typeof createSharedListener>\n /** The document id */\n id: string\n /* Preferrably a LRU cache map that is compatible with an ES6 Map, and have documents that allow unique ids to a particular dataset */\n cache?: Map<string, SanityDocument | null>\n /* The remote snapshot of what the document looks like in Content Lake, kept in sync by applying Mendoza patches in real time. undefined means it's unknown if it exists yet, null means its known that it doesn't exist. */\n remote: SanityDocument | null | undefined\n /* Local snapshot, that is rebased to the remote snapshot whenever that snapshot changes, and allows optimistic local mutations. undefined means it's unknown if the document exists in content lake yet, if both `remote` and `local` is `null` it means it's known that it doesn't exist. If `remote` is defined, and `local` is `null` it means it's optimistically deleted. If `remote` is `null` and `local` defined then it's optimistically created. */\n local: SanityDocument | null | undefined\n /* Remote mendoza mutation events, needs a better name to differentiate from optimistic mutations */\n mutationEvents: MutationEvent[]\n /* Track staged mutations that can be submitted */\n stagedChanges: MutationGroup[]\n /* Queue mutations mutations that should be staged after an ongoing submission settles */\n stashedChanges: MutationGroup[]\n /* Any kind of error object that the UI can parse and decide how to display/report */\n error: unknown\n /* Used for automatic retrying of loading the remote snapshot */\n fetchRemoteSnapshotAttempts: number\n /* Used for automatic retrying of submitting mutations to Content Lake as a transaction */\n submitTransactionsAttempts: number\n }\n events:\n | SharedListenerEvents\n | {type: 'error'}\n | {type: 'retry'}\n | {type: 'connect'}\n | {type: 'reconnect'}\n | {type: 'welcome'}\n | {type: 'mutate'; mutations: Mutation[]}\n | {type: 'submit'}\n | {\n type: 'xstate.done.actor.getDocument'\n output: SanityDocument\n }\n | {\n type: 'xstate.done.actor.submitTransactions'\n output: undefined\n }\n input: DocumentMutatorMachineInput\n },\n actions: {\n 'assign error to context': assign({error: ({event}) => event}),\n 'clear error from context': assign({error: undefined}),\n 'connect to server-sent events': raise({type: 'connect'}),\n 'listen to server-sent events': spawnChild('server-sent events', {\n id: 'listener',\n input: ({context}) => ({\n listener:\n context.sharedListener || createSharedListener(context.client),\n id: context.id,\n }),\n }),\n 'stop listening to server-sent events': stopChild('listener'),\n 'buffer remote mutation events': assign({\n mutationEvents: ({event, context}) => {\n assertEvent(event, 'mutation')\n return [...context.mutationEvents, event]\n },\n }),\n 'restore stashed changes': assign({\n stagedChanges: ({event, context}) => {\n assertEvent(event, 'xstate.done.actor.submitTransactions')\n return context.stashedChanges\n },\n stashedChanges: [],\n }),\n 'rebase fetched remote snapshot': enqueueActions(({enqueue}) => {\n enqueue.assign(({event, context}) => {\n assertEvent(event, 'xstate.done.actor.getDocument')\n const previousRemote = context.remote\n let nextRemote = event.output\n\n /**\n * We assume all patches that happen while we're waiting for the document to resolve are already applied.\n * But if we do see a patch that has the same revision as the document we just fetched, we should apply any patches following it\n */\n let seenCurrentRev = false\n for (const patch of context.mutationEvents) {\n if (\n !patch.effects?.apply ||\n (!patch.previousRev && patch.transition !== 'appear')\n )\n continue\n if (!seenCurrentRev && patch.previousRev === nextRemote?._rev) {\n seenCurrentRev = true\n }\n if (seenCurrentRev) {\n nextRemote = applyMendozaPatch(\n nextRemote,\n patch.effects.apply,\n patch.resultRev,\n )\n }\n }\n\n if (\n context.cache &&\n // If the shared cache don't have the document already we can just set it\n (!context.cache.has(context.id) ||\n // But when it's in the cache, make sure it's necessary to update it\n context.cache.get(context.id)!._rev !== nextRemote?._rev)\n ) {\n context.cache.set(context.id, nextRemote as unknown as any)\n }\n\n const [stagedChanges, local] = rebase(\n context.id,\n // It's annoying to convert between null and undefined, reach consensus\n previousRemote === null ? undefined : previousRemote,\n nextRemote === null ? undefined : (nextRemote as unknown as any),\n context.stagedChanges,\n )\n\n return {\n remote: nextRemote as unknown as any,\n local: local as unknown as any,\n stagedChanges,\n // Since the snapshot handler applies all the patches they are no longer needed, allow GC\n mutationEvents: [],\n }\n })\n enqueue.sendParent(\n ({context}) =>\n ({\n type: 'rebased.remote',\n id: context.id,\n document: context.remote!,\n }) satisfies DocumentMutatorMachineParentEvent,\n )\n }),\n 'apply mendoza patch': assign(({event, context}) => {\n assertEvent(event, 'mutation')\n const previousRemote = context.remote\n // We have already seen this mutation\n if (event.transactionId === previousRemote?._rev) {\n return {}\n }\n\n const nextRemote = applyMendozaPatch(\n previousRemote!,\n event.effects!.apply,\n event.resultRev,\n )\n\n if (\n context.cache &&\n // If the shared cache don't have the document already we can just set it\n (!context.cache.has(context.id) ||\n // But when it's in the cache, make sure it's necessary to update it\n context.cache.get(context.id)!._rev !== nextRemote?._rev)\n ) {\n context.cache.set(context.id, nextRemote as unknown as any)\n }\n\n const [stagedChanges, local] = rebase(\n context.id,\n // It's annoying to convert between null and undefined, reach consensus\n previousRemote === null ? undefined : previousRemote,\n nextRemote === null ? undefined : (nextRemote as unknown as any),\n context.stagedChanges,\n )\n\n return {\n remote: nextRemote as unknown as any,\n local: local as unknown as any,\n stagedChanges,\n }\n }),\n 'increment fetch attempts': assign({\n fetchRemoteSnapshotAttempts: ({context}) =>\n context.fetchRemoteSnapshotAttempts + 1,\n }),\n 'reset fetch attempts': assign({\n fetchRemoteSnapshotAttempts: 0,\n }),\n 'increment submit attempts': assign({\n submitTransactionsAttempts: ({context}) =>\n context.submitTransactionsAttempts + 1,\n }),\n 'reset submit attempts': assign({\n submitTransactionsAttempts: 0,\n }),\n 'stage mutation': assign({\n stagedChanges: ({event, context}) => {\n assertEvent(event, 'mutate')\n return [\n ...context.stagedChanges,\n {transaction: false, mutations: event.mutations},\n ]\n },\n }),\n 'stash mutation': assign({\n stashedChanges: ({event, context}) => {\n assertEvent(event, 'mutate')\n return [\n ...context.stashedChanges,\n {transaction: false, mutations: event.mutations},\n ]\n },\n }),\n 'rebase local snapshot': enqueueActions(({enqueue}) => {\n enqueue.assign({\n local: ({event, context}) => {\n assertEvent(event, 'mutate')\n // @TODO would be helpful to not have to convert back and forth between maps\n const localDataset = new Map()\n if (context.local) {\n localDataset.set(context.id, context.local)\n }\n // Apply mutations to local dataset (note: this is immutable, and doesn't change the dataset)\n const results = applyMutations(event.mutations, localDataset)\n // Write the updated results back to the \"local\" dataset\n commit(results, localDataset)\n // Read the result from the local dataset again\n return localDataset.get(context.id)\n },\n })\n enqueue.sendParent(\n ({context}) =>\n ({\n type: 'rebased.local',\n id: context.id,\n document: context.local!,\n }) satisfies DocumentMutatorMachineParentEvent,\n )\n }),\n 'send pristine event to parent': sendParent(\n ({context}) =>\n ({\n type: 'pristine',\n id: context.id,\n }) satisfies DocumentMutatorMachineParentEvent,\n ),\n 'send sync event to parent': sendParent(\n ({context}) =>\n ({\n type: 'sync',\n id: context.id,\n document: context.remote!,\n }) satisfies DocumentMutatorMachineParentEvent,\n ),\n 'send mutation event to parent': sendParent(({context, event}) => {\n assertEvent(event, 'mutation')\n return {\n type: 'mutation',\n id: context.id,\n previousRev: event.previousRev!,\n resultRev: event.resultRev!,\n effects: event.effects!,\n } satisfies DocumentMutatorMachineParentEvent\n }),\n },\n actors: {\n 'server-sent events': fromEventObservable(\n ({\n input,\n }: {\n input: {listener: ReturnType<typeof createSharedListener>; id: string}\n }) => {\n const {listener, id} = input\n return defer(() => listener).pipe(\n filter(\n event =>\n event.type === 'welcome' ||\n event.type === 'reconnect' ||\n (event.type === 'mutation' && event.documentId === id),\n ),\n // This is necessary to avoid sync emitted events from `shareReplay` from happening before the actor is ready to receive them\n observeOn(asapScheduler),\n )\n },\n ),\n 'fetch remote snapshot': fromPromise(\n async ({\n input,\n signal,\n }: {\n input: {client: SanityClient; id: string}\n signal: AbortSignal\n }) => {\n const {client, id} = input\n const document = await client\n .getDocument(id, {\n signal,\n })\n .catch(e => {\n if (e instanceof Error && e.name === 'AbortError') return\n throw e\n })\n\n return document\n },\n ),\n 'submit mutations as transactions': fromPromise(\n async ({\n input,\n signal,\n }: {\n input: {client: SanityClient; transactions: Transaction[]}\n signal: AbortSignal\n }) => {\n const {client, transactions} = input\n for (const transaction of transactions) {\n if (signal.aborted) return\n await client\n .dataRequest('mutate', encodeTransaction(transaction), {\n visibility: 'async',\n returnDocuments: false,\n signal,\n })\n .catch(e => {\n if (e instanceof Error && e.name === 'AbortError') return\n throw e\n })\n }\n },\n ),\n },\n delays: {\n // Exponential backoff delay function\n fetchRemoteSnapshotTimeout: ({context}) =>\n Math.pow(2, context.fetchRemoteSnapshotAttempts) * 1000,\n submitTransactionsTimeout: ({context}) =>\n Math.pow(2, context.submitTransactionsAttempts) * 1000,\n },\n}).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QQPYGMCuBbMA7ALgLRYb4CG+KATgMQnn5gDaADALqKgAOKsAlvj4pcnEAA9EADhYAWAHQA2GSwUBmAKwBOaQEZJk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D1PS9j3vVhMnrWCFRxtNaRLdcfIsiwuS5fkgZaOUlhpDDP7MdFzWWftzXI-gdrPGlLoOSNyiHFstRySisjcgzahyFoUYBbRsac5tO6w1F7wIwLONHfg0qyvKyVfPgVAmCT0kJGt41pJD02xgcpElUkcZ6rI+q5JcckbU0W0NWZB57QduMCKbcoKmIsCpXIZB8YwVAABRC-jj3PYCsA3XwOAoKQACUNDmttjVh-zEfG9H5u21lpVjSrTtTTNbsstUYJJAFWgA37XORTz+t8+xtcKpb1v1+6KJFopGQqRi6nBlstYcqNK5riusYDztlejzKMfJXHCdJynqd8SJaAABYAEpgFgKCMAAyrgZBcLAV+P3nBfF6XJnc7tfmY8xZnglgWGe-klILzUhYDSJVRpnCONNOcWxWRKBRDYO4uAUD7XgJEMuIdqDi2GgWQgOhgxMyRKyFc8IuQkXUDvK0HgvAHmIR9bCD4SoeSWCoLkoZpxrmXIw0OLEMxsNJgkSc418KhnrHyG4oZYTcPhMifhJx4SCiDjrABSpgHiLtogAUhwW77DRIGXkk55wexKCrJQsg1jBTnPsYRqZviiL6PohuORgyhhBhGKMsZYzxhcXrf8EBPHulUJOPCtRlABWIu7IoORVBIIhMpNYGJyghKHmEvaYjQEkOwhkxQrJtBES0JDOBPlkgKD1JYZSjZORyTXNkwBsVwkFPYTJVYS58JxPKbOYM0gUj7FjGcEMOpciaJxMHXWOTWJV2avFRKpIwARILJRGJBF4mZBIkDE0KtIxLSSDkDYGhWl70Ru1Tq6zsLURBkoLyWRmz8PmlUZmcY1zXDKdMghcy2mIyFh8W5ZN4RFmOFyKaZwiLeT2GVJcy5pBrguCiMK2tvyDwBYbIWejOkSMQBkeQORJq0RNCUDIDNondxuGpPQmRqIXPhiPECuKMpdMkbILZ-SEnLxyjqOJMZsj1jRTYIAA */\n\n id: 'document-mutator',\n\n context: ({input}) => ({\n client: input.client.withConfig({allowReconfigure: false}),\n sharedListener: input.sharedListener,\n id: input.id,\n remote: undefined,\n local: undefined,\n mutationEvents: [],\n stagedChanges: [],\n stashedChanges: [],\n error: undefined,\n fetchRemoteSnapshotAttempts: 0,\n submitTransactionsAttempts: 0,\n cache: input.cache,\n }),\n\n // Auto start the connection by default\n entry: ['connect to server-sent events'],\n\n on: {\n mutate: {\n actions: ['rebase local snapshot', 'stage mutation'],\n },\n },\n initial: 'disconnected',\n states: {\n disconnected: {\n on: {\n connect: {\n target: 'connecting',\n actions: ['listen to server-sent events'],\n },\n },\n },\n connecting: {\n on: {\n welcome: 'connected',\n reconnect: 'reconnecting',\n error: 'connectFailure',\n },\n tags: ['busy'],\n },\n connectFailure: {\n on: {\n connect: {\n target: 'connecting',\n actions: ['listen to server-sent events'],\n },\n },\n entry: [\n 'stop listening to server-sent events',\n 'assign error to context',\n ],\n exit: ['clear error from context'],\n tags: ['error'],\n },\n reconnecting: {\n on: {\n welcome: {\n target: 'connected',\n },\n error: {\n target: 'connectFailure',\n },\n },\n tags: ['busy', 'error'],\n },\n connected: {\n on: {\n mutation: {\n actions: ['buffer remote mutation events'],\n },\n reconnect: 'reconnecting',\n },\n entry: ['clear error from context'],\n initial: 'loading',\n states: {\n loading: {\n invoke: {\n src: 'fetch remote snapshot',\n id: 'getDocument',\n input: ({context}) => ({\n client: context.client,\n id: context.id,\n }),\n onError: {\n target: 'loadFailure',\n },\n onDone: {\n target: 'loaded',\n actions: [\n 'rebase fetched remote snapshot',\n 'reset fetch attempts',\n ],\n },\n },\n\n tags: ['busy'],\n },\n\n loaded: {\n entry: ['send sync event to parent'],\n on: {\n mutation: {\n actions: ['apply mendoza patch', 'send mutation event to parent'],\n },\n },\n initial: 'pristine',\n\n states: {\n pristine: {\n on: {\n mutate: {\n actions: ['rebase local snapshot', 'stage mutation'],\n target: 'dirty',\n },\n },\n tags: ['ready'],\n },\n dirty: {\n on: {\n submit: 'submitting',\n },\n tags: ['ready'],\n },\n submitting: {\n on: {\n mutate: {\n actions: ['rebase local snapshot', 'stash mutation'],\n },\n },\n invoke: {\n src: 'submit mutations as transactions',\n id: 'submitTransactions',\n input: ({context}) => {\n // @TODO perhaps separate utils to be lower level and operate on single documents at a time instead of expecting a local dataset\n const remoteDataset = new Map()\n remoteDataset.set(context.id, context.remote)\n return {\n client: context.client,\n transactions: toTransactions(\n // Squashing DMP strings is the last thing we do before submitting\n squashDMPStrings(\n remoteDataset,\n squashMutationGroups(context.stagedChanges),\n ),\n ),\n }\n },\n onError: {\n target: 'submitFailure',\n },\n\n onDone: {\n target: 'pristine',\n actions: [\n 'restore stashed changes',\n 'reset submit attempts',\n 'send pristine event to parent',\n ],\n },\n },\n /**\n * 'busy' means we should show a spinner, 'ready' means we can still accept mutations, they'll be applied optimistically right away, and queued for submissions after the current submission settles\n */\n tags: ['busy', 'ready'],\n },\n submitFailure: {\n exit: ['clear error from context'],\n after: {\n submitTransactionsTimeout: {\n actions: ['increment submit attempts'],\n target: 'submitting',\n },\n },\n on: {\n retry: 'submitting',\n },\n /**\n * How can it be both `ready` and `error`? `ready` means it can receive mutations, optimistically apply them, and queue them for submission. `error` means it failed to submit previously applied mutations.\n * It's completely fine to keep queueing up more mutations and applying them optimistically, while showing UI that notifies that mutations didn't submit, and show a count down until the next automatic retry.\n */\n tags: ['error', 'ready'],\n },\n },\n },\n\n loadFailure: {\n exit: ['clear error from context'],\n after: {\n fetchRemoteSnapshotTimeout: {\n actions: ['increment fetch attempts'],\n target: 'loading',\n },\n },\n on: {\n retry: 'loading',\n },\n tags: ['error'],\n },\n },\n },\n },\n})\n\nfunction applyMendozaPatch<const DocumentType extends SanityDocumentBase>(\n document: DocumentType | undefined,\n patch: RawPatch,\n nextRevision: string | undefined,\n) {\n const next = applyPatch(omitRev(document), patch)\n if (!next) {\n return null\n }\n return Object.assign(next, {_rev: nextRevision})\n}\n\nfunction omitRev<const DocumentType extends SanityDocumentBase>(\n document: DocumentType | undefined,\n) {\n if (!document) {\n return null\n }\n // eslint-disable-next-line unused-imports/no-unused-vars\n const {_rev, ...doc} = document\n return doc\n}\n"],"names":[],"mappings":";;;;;AAWO,SA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QAAQ,QAAQ,GAAG,KAAK;AAChD,SAAK,OAGE,OAAO,OAAO,MAAM,EAAC,MAAM,aAAA,CAAa,IAFtC;AAGX;AAEA,SAAS,QACP,UACA;AACA,MAAI,CAAC;AACH,WAAO;AAGT,QAAM,EAAC,MAAM,GAAG,IAAA,IAAO;AACvB,SAAO;AACT;"}
+16
-552
"use strict";
Object.defineProperty(exports, "__esModule", { value: !0 });
var rxjs = require("rxjs"), lodashPartition = require("lodash/partition.js"), operators = require("rxjs/operators"), keyBy = require("lodash/keyBy.js"), encode = require("./_chunks-cjs/encode.cjs"), nanoid = require("nanoid"), utils = require("./_chunks-cjs/utils.cjs"), mendoza = require("mendoza"), sortedIndex = require("lodash/sortedIndex.js"), uuid = require("@sanity/uuid"), diffMatchPatch = require("@sanity/diff-match-patch"), getAtPath = require("./_chunks-cjs/getAtPath.cjs"), stringify = require("./_chunks-cjs/stringify.cjs"), groupBy = require("lodash/groupBy.js");
var rxjs = require("rxjs"), lodashPartition = require("lodash/partition.js"), operators = require("rxjs/operators"), keyBy = require("lodash/keyBy.js"), encode = require("./_chunks-cjs/encode.cjs"), createOptimisticStore = require("./_chunks-cjs/createOptimisticStore.cjs"), sortedIndex = require("lodash/sortedIndex.js");
function _interopDefaultCompat(e) {
return e && typeof e == "object" && "default" in e ? e : { default: e };
}
var lodashPartition__default = /* @__PURE__ */ _interopDefaultCompat(lodashPartition), keyBy__default = /* @__PURE__ */ _interopDefaultCompat(keyBy), sortedIndex__default = /* @__PURE__ */ _interopDefaultCompat(sortedIndex), groupBy__default = /* @__PURE__ */ _interopDefaultCompat(groupBy);
var lodashPartition__default = /* @__PURE__ */ _interopDefaultCompat(lodashPartition), keyBy__default = /* @__PURE__ */ _interopDefaultCompat(keyBy), sortedIndex__default = /* @__PURE__ */ _interopDefaultCompat(sortedIndex);
function createReadOnlyStore(listenDocumentUpdates, options = {}) {

@@ -100,3 +100,3 @@ const cache = /* @__PURE__ */ new Map(), { shutdownDelay } = options;

}
const DEFAULT_MAX_BUFFER_SIZE = 20, DEFAULT_DEADLINE_MS = 3e4, EMPTY_ARRAY$1 = [];
const DEFAULT_MAX_BUFFER_SIZE = 20, DEFAULT_DEADLINE_MS = 3e4, EMPTY_ARRAY = [];
function sequentializeListenerEvents(options) {

@@ -119,3 +119,3 @@ const {

base: { revision: event.document?._rev },
buffer: EMPTY_ARRAY$1,
buffer: EMPTY_ARRAY,
emitEvents: [event]

@@ -162,3 +162,3 @@ };

buffer: nextBuffer,
emitEvents: EMPTY_ARRAY$1
emitEvents: EMPTY_ARRAY
};

@@ -169,5 +169,5 @@ }

{
emitEvents: EMPTY_ARRAY$1,
emitEvents: EMPTY_ARRAY,
base: void 0,
buffer: EMPTY_ARRAY$1
buffer: EMPTY_ARRAY
}

@@ -318,93 +318,2 @@ ),

}
function applyAll(current, mutation) {
return mutation.reduce((doc, m) => {
const res = applyDocumentMutation(doc, m);
if (res.status === "error")
throw new Error(res.message);
return res.status === "noop" ? doc : res.after;
}, current);
}
function applyDocumentMutation(document, mutation) {
if (mutation.type === "create")
return create(document, mutation);
if (mutation.type === "createIfNotExists")
return createIfNotExists(document, mutation);
if (mutation.type === "delete")
return del(document, mutation);
if (mutation.type === "createOrReplace")
return createOrReplace(document, mutation);
if (mutation.type === "patch")
return patch(document, mutation);
throw new Error(`Invalid mutation type: ${mutation.type}`);
}
function create(document, mutation) {
if (document)
return { status: "error", message: "Document already exist" };
const result = utils.assignId(mutation.document, nanoid.nanoid);
return { status: "created", id: result._id, after: result };
}
function createIfNotExists(document, mutation) {
return utils.hasId(mutation.document) ? document ? { status: "noop" } : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function createOrReplace(document, mutation) {
return utils.hasId(mutation.document) ? document ? {
status: "updated",
id: mutation.document._id,
before: document,
after: mutation.document
} : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function del(document, mutation) {
return document ? mutation.id !== document._id ? { status: "error", message: "Delete mutation targeted wrong document" } : {
status: "deleted",
id: mutation.id,
before: document,
after: void 0
} : { status: "noop" };
}
function patch(document, mutation) {
if (!document)
return {
status: "error",
message: "Cannot apply patch on nonexistent document"
};
const next = utils.applyPatchMutation(mutation, document);
return document === next ? { status: "noop" } : { status: "updated", id: mutation.id, before: document, after: next };
}
function omitRev(document) {
if (document === void 0)
return;
const { _rev, ...doc } = document;
return doc;
}
function applyMendozaPatch(document, patch2, patchBaseRev) {
if (patchBaseRev !== document?._rev)
throw new Error(
"Invalid document revision. The provided patch is calculated from a different revision than the current document"
);
const next = mendoza.applyPatch(omitRev(document), patch2);
return next === null ? void 0 : next;
}
function applyMutationEventEffects(document, event) {
if (!event.effects)
throw new Error(
"Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?"
);
const next = applyMendozaPatch(
document,
event.effects.apply,
event.previousRev
);
return next ? { ...next, _rev: event.resultRev } : void 0;
}
function hasProperty(value, property) {
const val = value[property];
return typeof val < "u" && val !== null;
}
function createDocumentUpdateListener(options) {

@@ -427,7 +336,7 @@ const { listenDocumentEvents } = options;

);
if (hasProperty(event, "effects"))
if (createOptimisticStore.hasProperty(event, "effects"))
return {
event,
documentId,
snapshot: applyMutationEventEffects(
snapshot: createOptimisticStore.applyMutationEventEffects(
prev.snapshot,

@@ -437,7 +346,7 @@ event

};
if (hasProperty(event, "mutations"))
if (createOptimisticStore.hasProperty(event, "mutations"))
return {
event,
documentId,
snapshot: applyAll(
snapshot: createOptimisticStore.applyAll(
prev.snapshot,

@@ -618,48 +527,2 @@ encode.decodeAll(event.mutations)

}
function getMutationDocumentId(mutation) {
if (mutation.type === "patch")
return mutation.id;
if (mutation.type === "create")
return mutation.document._id;
if (mutation.type === "delete")
return mutation.id;
if (mutation.type === "createIfNotExists" || mutation.type === "createOrReplace")
return mutation.document._id;
throw new Error("Invalid mutation type");
}
function applyMutations(mutations, documentMap, transactionId) {
const updatedDocs = /* @__PURE__ */ Object.create(null);
for (const mutation of mutations) {
const documentId = getMutationDocumentId(mutation);
if (!documentId)
throw new Error("Unable to get document id from mutation");
const before = updatedDocs[documentId]?.after || documentMap.get(documentId), res = applyDocumentMutation(before, mutation);
if (res.status === "error")
throw new Error(res.message);
let entry = updatedDocs[documentId];
entry || (entry = { before, after: before, mutations: [] }, updatedDocs[documentId] = entry);
const after = transactionId ? { ...res.status === "noop" ? before : res.after, _rev: transactionId } : res.status === "noop" ? before : res.after;
documentMap.set(documentId, after), entry.after = after, entry.mutations.push(mutation);
}
return Object.entries(updatedDocs).map(
([id, { before, after, mutations: muts }]) => ({
id,
status: after ? before ? "updated" : "created" : "deleted",
mutations: muts,
before,
after
})
);
}
function createDocumentMap() {
const documents = /* @__PURE__ */ new Map();
return {
set: (id, doc) => void documents.set(id, doc),
get: (id) => documents.get(id),
delete: (id) => documents.delete(id)
};
}
function createTransactionId() {
return uuid.uuid();
}
function createWelcomeEvent() {

@@ -672,3 +535,3 @@ return {

function createMockBackendAPI() {
const documentMap = createDocumentMap(), listenerEvents = new rxjs.Subject();
const documentMap = createOptimisticStore.createDocumentMap(), listenerEvents = new rxjs.Subject();
return {

@@ -693,3 +556,3 @@ listen: (query) => rxjs.concat(

const transaction = structuredClone(_transaction);
return applyMutations(
return createOptimisticStore.applyMutations(
transaction.mutations,

@@ -703,3 +566,3 @@ documentMap,

mutations: encode.encodeAll(res.mutations),
transactionId: transaction.id || createTransactionId(),
transactionId: transaction.id || createOptimisticStore.createTransactionId(),
previousRev: res.before?._rev,

@@ -736,402 +599,4 @@ resultRev: res.after?._rev,

}
function commit(results, documentMap) {
results.forEach((result) => {
(result.status === "created" || result.status === "updated") && documentMap.set(result.id, result.after), result.status === "deleted" && documentMap.delete(result.id);
});
}
function createReplayMemoizer(expiry) {
const memo = /* @__PURE__ */ Object.create(null);
return function(key, observable) {
return key in memo || (memo[key] = observable.pipe(
rxjs.finalize(() => {
delete memo[key];
}),
rxjs.share({
connector: () => new rxjs.ReplaySubject(1),
resetOnRefCountZero: () => rxjs.timer(expiry)
})
)), memo[key];
};
}
function filterMutationGroupsById(mutationGroups, id) {
return mutationGroups.flatMap(
(mutationGroup) => mutationGroup.mutations.flatMap(
(mut) => getMutationDocumentId(mut) === id ? [mut] : []
)
);
}
function takeUntilRight(arr, predicate, opts) {
const result = [];
for (const item of arr.slice().reverse()) {
if (predicate(item))
return result;
result.push(item);
}
return result.reverse();
}
function isEqualPath(p1, p2) {
return stringify.stringify(p1) === stringify.stringify(p2);
}
function supersedes(later, earlier) {
return (earlier.type === "set" || earlier.type === "unset") && (later.type === "set" || later.type === "unset");
}
function squashNodePatches(patches) {
return compactSetIfMissingPatches(
compactSetPatches(compactUnsetPatches(patches))
);
}
function compactUnsetPatches(patches) {
return patches.reduce(
(earlierPatches, laterPatch) => {
if (laterPatch.op.type !== "unset")
return earlierPatches.push(laterPatch), earlierPatches;
const unaffected = earlierPatches.filter(
(earlierPatch) => !stringify.startsWith(laterPatch.path, earlierPatch.path)
);
return unaffected.push(laterPatch), unaffected;
},
[]
);
}
function compactSetPatches(patches) {
return patches.reduceRight(
(laterPatches, earlierPatch) => (laterPatches.find(
(later) => supersedes(later.op, earlierPatch.op) && isEqualPath(later.path, earlierPatch.path)
) || laterPatches.unshift(earlierPatch), laterPatches),
[]
);
}
function compactSetIfMissingPatches(patches) {
return patches.reduce(
(previousPatches, laterPatch) => laterPatch.op.type !== "setIfMissing" ? (previousPatches.push(laterPatch), previousPatches) : (takeUntilRight(
previousPatches,
(patch2) => patch2.op.type === "unset"
).find(
(precedingPatch) => precedingPatch.op.type === "setIfMissing" && isEqualPath(precedingPatch.path, laterPatch.path)
) || previousPatches.push(laterPatch), previousPatches),
[]
);
}
function compactDMPSetPatches(base, patches) {
let edge = base;
return patches.reduce(
(earlierPatches, laterPatch) => {
const before = edge;
if (edge = utils.applyNodePatch(laterPatch, edge), laterPatch.op.type === "set" && typeof laterPatch.op.value == "string") {
const current = getAtPath.getAtPath(laterPatch.path, before);
if (typeof current == "string") {
const replaced = {
...laterPatch,
op: {
type: "diffMatchPatch",
value: diffMatchPatch.stringifyPatches(
diffMatchPatch.makePatches(current, laterPatch.op.value)
)
}
};
return earlierPatches.flatMap((ep) => isEqualPath(ep.path, laterPatch.path) && ep.op.type === "diffMatchPatch" ? [] : ep).concat(replaced);
}
}
return earlierPatches.push(laterPatch), earlierPatches;
},
[]
);
}
function squashDMPStrings(base, mutationGroups) {
return mutationGroups.map((mutationGroup) => ({
...mutationGroup,
mutations: dmpIfyMutations(base, mutationGroup.mutations)
}));
}
function dmpIfyMutations(store, mutations) {
return mutations.map((mutation, i) => {
if (mutation.type !== "patch")
return mutation;
const base = store.get(mutation.id);
return base ? dmpifyPatchMutation(base, mutation) : mutation;
});
}
function dmpifyPatchMutation(base, mutation) {
return {
...mutation,
patches: compactDMPSetPatches(base, mutation.patches)
};
}
function mergeMutationGroups(mutationGroups) {
return chunkWhile(mutationGroups, (group) => !group.transaction).flatMap(
(chunk) => ({
...chunk[0],
mutations: chunk.flatMap((c) => c.mutations)
})
);
}
function chunkWhile(arr, predicate) {
const res = [];
let currentChunk = [];
return arr.forEach((item) => {
predicate(item) ? currentChunk.push(item) : (currentChunk.length > 0 && res.push(currentChunk), currentChunk = [], res.push([item]));
}), currentChunk.length > 0 && res.push(currentChunk), res;
}
function squashMutationGroups(staged) {
return mergeMutationGroups(staged).map((transaction) => ({
...transaction,
mutations: squashMutations(transaction.mutations)
})).map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mutation) => mutation.type !== "patch" ? mutation : {
...mutation,
patches: squashNodePatches(mutation.patches)
})
}));
}
function squashMutations(mutations) {
const byDocument = groupBy__default.default(mutations, getMutationDocumentId);
return Object.values(byDocument).flatMap((documentMutations) => squashCreateIfNotExists(squashDelete(documentMutations)).flat().reduce((acc, docMutation) => {
const prev = acc[acc.length - 1];
return (!prev || prev.type === "patch") && docMutation.type === "patch" ? acc.slice(0, -1).concat({
...docMutation,
patches: (prev?.patches || []).concat(docMutation.patches)
}) : acc.concat(docMutation);
}, []));
}
function squashCreateIfNotExists(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type !== "createIfNotExists" ? (previousMuts.push(laterMut), previousMuts) : (takeUntilRight(previousMuts, (m) => m.type === "delete").find(
(precedingPatch) => precedingPatch.type === "createIfNotExists"
) || previousMuts.push(laterMut), previousMuts), []);
}
function squashDelete(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type === "delete" ? [laterMut] : (previousMuts.push(laterMut), previousMuts), []);
}
function rebase(documentId, oldBase, newBase, localMutations) {
let edge = oldBase;
const dmpified = localMutations.map((transaction) => {
const mutations = transaction.mutations.flatMap((mut) => {
if (getMutationDocumentId(mut) !== documentId)
return [];
const before = edge;
return edge = applyAll(edge, [mut]), !before || mut.type !== "patch" ? mut : {
type: "dmpified",
mutation: {
...mut,
// Todo: make compactDMPSetPatches return pairs of patches that was dmpified with their
// original as dmpPatches and original is not 1:1 (e..g some of the original may not be dmpified)
dmpPatches: compactDMPSetPatches(before, mut.patches),
original: mut.patches
}
};
});
return { ...transaction, mutations };
});
let newBaseWithDMPForOldBaseApplied = newBase;
return dmpified.map((transaction) => {
const applied = [];
return transaction.mutations.forEach((mut) => {
if (mut.type === "dmpified")
try {
newBaseWithDMPForOldBaseApplied = utils.applyPatches(
mut.mutation.dmpPatches,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch {
console.warn("Failed to apply dmp patch, falling back to original");
try {
newBaseWithDMPForOldBaseApplied = utils.applyPatches(
mut.mutation.original,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch (second) {
throw new Error(
`Failed to apply patch for document "${documentId}": ${second.message}`
);
}
}
else
newBaseWithDMPForOldBaseApplied = applyAll(
newBaseWithDMPForOldBaseApplied,
[mut]
);
});
}), [localMutations.map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mut) => mut.type !== "patch" || getMutationDocumentId(mut) !== documentId ? mut : {
...mut,
patches: mut.patches.map((patch2) => patch2.op.type !== "set" ? patch2 : {
...patch2,
op: {
...patch2.op,
value: getAtPath.getAtPath(patch2.path, newBaseWithDMPForOldBaseApplied)
}
})
})
})), newBaseWithDMPForOldBaseApplied];
}
let didEmitMutationsAccessWarning = !1;
function warnNoMutationsReceived() {
didEmitMutationsAccessWarning || (console.warn(
new Error(
"No mutation received from backend. The listener is likely set up with `excludeMutations: true`. If your app need to know about mutations, make sure the listener is set up to include mutations"
)
), didEmitMutationsAccessWarning = !0);
}
const EMPTY_ARRAY = [];
function createOptimisticStore(backend) {
const local = createDocumentMap(), remote = createDocumentMap(), memoize = createReplayMemoizer(1e3);
let stagedChanges = [];
const remoteEvents$ = new rxjs.Subject(), localMutations$ = new rxjs.Subject(), stage$ = new rxjs.Subject();
function setStaged(nextPending) {
stagedChanges = nextPending, stage$.next();
}
function getLocalEvents(id) {
return localMutations$.pipe(rxjs.filter((event) => event.id === id));
}
function getRemoteEvents(id) {
return backend.listen(id).pipe(
rxjs.filter(
(event) => event.type !== "reconnect"
),
rxjs.mergeMap((event) => {
const oldLocal = local.get(id), oldRemote = remote.get(id);
if (event.type === "sync") {
const newRemote = event.document, [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
return rxjs.of({
type: "sync",
id,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
rebasedStage
});
} else if (event.type === "mutation") {
if (event.transactionId === oldRemote?._rev)
return rxjs.EMPTY;
let newRemote;
if (hasProperty(event, "effects"))
newRemote = applyMutationEventEffects(oldRemote, event);
else if (hasProperty(event, "mutations"))
newRemote = applyAll(oldRemote, encode.decodeAll(event.mutations));
else
throw new Error(
"Neither effects or mutations found on listener event"
);
const [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
newLocal && (newLocal._rev = event.transactionId);
const emittedEvent = {
type: "mutation",
id,
rebasedStage,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
effects: event.effects,
previousRev: event.previousRev,
resultRev: event.resultRev,
// overwritten below
mutations: EMPTY_ARRAY
};
return event.mutations ? emittedEvent.mutations = encode.decodeAll(
event.mutations
) : Object.defineProperty(
emittedEvent,
"mutations",
warnNoMutationsReceived
), rxjs.of(emittedEvent);
} else
throw new Error(`Unknown event type: ${event.type}`);
}),
rxjs.tap((event) => {
local.set(event.id, event.after.local), remote.set(event.id, event.after.remote), setStaged(event.rebasedStage);
}),
rxjs.tap({
next: (event) => remoteEvents$.next(event),
error: (err) => {
}
})
);
}
function listenEvents(id) {
return rxjs.defer(
() => memoize(id, rxjs.merge(getLocalEvents(id), getRemoteEvents(id)))
);
}
return {
meta: {
events: rxjs.merge(localMutations$, remoteEvents$),
stage: stage$.pipe(
rxjs.map(
() => (
// note: this should not be tampered with by consumers. We might want to do a deep-freeze during dev to avoid accidental mutations
stagedChanges
)
)
),
conflicts: rxjs.EMPTY
// does nothing for now
},
mutate: (mutations) => {
stagedChanges.push({ transaction: !1, mutations });
const results = applyMutations(mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
before: result.before,
after: result.after,
mutations: result.mutations,
id: result.id,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
transaction: (mutationsOrTransaction) => {
const transaction = Array.isArray(
mutationsOrTransaction
) ? { mutations: mutationsOrTransaction, transaction: !0 } : { ...mutationsOrTransaction, transaction: !0 };
stagedChanges.push(transaction);
const results = applyMutations(transaction.mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
mutations: result.mutations,
id: result.id,
before: result.before,
after: result.after,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
listenEvents,
listen: (id) => listenEvents(id).pipe(
rxjs.map(
(event) => event.type === "optimistic" ? event.after : event.after.local
)
),
optimize: () => {
setStaged(squashMutationGroups(stagedChanges));
},
submit: () => {
const pending = stagedChanges;
return setStaged([]), rxjs.lastValueFrom(
rxjs.from(
toTransactions(
// Squashing DMP strings is the last thing we do before submitting
squashDMPStrings(remote, squashMutationGroups(pending))
)
).pipe(
rxjs.concatMap((mut) => backend.submit(mut)),
rxjs.toArray()
)
);
}
};
}
function toTransactions(groups) {
return groups.map((group) => group.transaction && group.id !== void 0 ? { id: group.id, mutations: group.mutations } : { id: createTransactionId(), mutations: group.mutations });
}
exports.createOptimisticStore = createOptimisticStore.createOptimisticStore;
exports.toTransactions = createOptimisticStore.toTransactions;
exports.createDocumentEventListener = createDocumentEventListener;

@@ -1144,3 +609,2 @@ exports.createDocumentLoader = createDocumentLoader;

exports.createMockBackendAPI = createMockBackendAPI;
exports.createOptimisticStore = createOptimisticStore;
exports.createOptimisticStoreClientBackend = createOptimisticStoreClientBackend;

@@ -1147,0 +611,0 @@ exports.createOptimisticStoreMockBackend = createOptimisticStoreMockBackend;

@@ -5,153 +5,5 @@ import { AnyArray, AnyEmptyArray, ByIndex, Concat, ConcatInner, Digit, ElementType, Err, FindBy, FindInArray, Index, KeyedPathElement, Merge, MergeInner, Ok, OnlyDigits, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, Path, PathElement, PropertyName, Result, SafePath, Split, SplitAll, StringToPath, StripError, ToArray, ToNumber, Trim, TrimLeft, TrimRight, Try, Unwrap } from "./_chunks-dts/types.cjs";

import { Insert, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityIncPatch, SanityInsertPatch, SanityMutation, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch } from "./_chunks-dts/types3.cjs";
import { Conflict, DocumentMap, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MutationGroup, MutationResult, NonTransactionalMutationGroup, OptimisticDocumentEvent, OptimisticStore, QueryParams, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, SubmitResult, TransactionalMutationGroup } from "./_chunks-dts/types4.cjs";
import { Observable } from "rxjs";
import { RawPatch } from "mendoza";
import { ReconnectEvent, SanityClient, WelcomeEvent } from "@sanity/client";
interface ListenerSyncEvent<Doc extends SanityDocumentBase = SanityDocumentBase> {
type: 'sync';
document: Doc | undefined;
}
interface ListenerMutationEvent {
type: 'mutation';
documentId: string;
transactionId: string;
resultRev?: string;
previousRev?: string;
effects?: {
apply: RawPatch;
};
mutations: SanityMutation[];
transition: 'update' | 'appear' | 'disappear';
}
interface ListenerReconnectEvent {
type: 'reconnect';
}
type ListenerChannelErrorEvent = {
type: 'channelError';
message: string;
};
type ListenerWelcomeEvent = {
type: 'welcome';
listenerName: string;
};
type ListenerDisconnectEvent = {
type: 'disconnect';
reason: string;
};
type ListenerEndpointEvent = ListenerWelcomeEvent | ListenerMutationEvent | ListenerReconnectEvent | ListenerChannelErrorEvent | ListenerDisconnectEvent;
type ListenerEvent<Doc extends SanityDocumentBase = SanityDocumentBase> = ListenerSyncEvent<Doc> | ListenerMutationEvent | ListenerReconnectEvent;
interface OptimisticDocumentEvent {
type: 'optimistic';
id: string;
before: SanityDocumentBase | undefined;
after: SanityDocumentBase | undefined;
mutations: Mutation[];
stagedChanges: Mutation[];
}
type QueryParams = Record<string, string | number | boolean | (string | number | boolean)[]>;
interface RemoteSyncEvent {
type: 'sync';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
rebasedStage: MutationGroup[];
}
interface RemoteMutationEvent {
type: 'mutation';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
effects?: {
apply: RawPatch;
};
previousRev?: string;
resultRev?: string;
mutations: Mutation[];
rebasedStage: MutationGroup[];
}
type RemoteDocumentEvent = RemoteSyncEvent | RemoteMutationEvent;
type DocumentMap<Doc extends SanityDocumentBase> = {
get(id: string): Doc | undefined;
set(id: string, doc: Doc | undefined): void;
delete(id: string): void;
};
interface MutationResult {}
interface SubmitResult {}
interface NonTransactionalMutationGroup {
transaction: false;
mutations: Mutation[];
}
interface TransactionalMutationGroup {
transaction: true;
id?: string;
mutations: Mutation[];
}
/**
* A mutation group represents an incoming, locally added group of mutations
* They can either be transactional or non-transactional
* - Transactional means that they must be submitted as a separate transaction (with an optional id) and no other mutations can be mixed with it
* – Non-transactional means that they can be combined with other mutations
*/
type MutationGroup = NonTransactionalMutationGroup | TransactionalMutationGroup;
type Conflict = {
path: Path;
error: Error;
base: SanityDocumentBase | undefined;
local: SanityDocumentBase | undefined;
};
interface OptimisticStore {
meta: {
/**
* A stream of events for anything that happens in the store
*/
events: Observable<OptimisticDocumentEvent | RemoteDocumentEvent>;
/**
* A stream of current staged changes
*/
stage: Observable<MutationGroup[]>;
/**
* A stream of current conflicts. TODO: Needs more work
*/
conflicts: Observable<Conflict[]>;
};
/**
* Applies the given mutations. Mutations are not guaranteed to be submitted in the same transaction
* Can this mutate both local and remote documents at the same time
*/
mutate(mutation: Mutation[]): MutationResult;
/**
* Makes sure the given mutations are posted in a single transaction
*/
transaction(transaction: {
id?: string;
mutations: Mutation[];
} | Mutation[]): MutationResult;
/**
* Checkout a document for editing. This is required to be able to see optimistic changes
*/
listen(id: string): Observable<SanityDocumentBase | undefined>;
/**
* Listen for events for a given document id
*/
listenEvents(id: string): Observable<RemoteDocumentEvent | OptimisticDocumentEvent>;
/**
* Optimize list of pending mutations
*/
optimize(): void;
/**
* Submit pending mutations
*/
submit(): Promise<SubmitResult[]>;
}
interface DocumentSyncUpdate<Doc extends SanityDocumentBase> {

@@ -349,5 +201,6 @@ documentId: string;

declare function createOptimisticStore(backend: OptimisticStoreBackend): OptimisticStore;
declare function toTransactions(groups: MutationGroup[]): Transaction[];
declare function createOptimisticStoreClientBackend(client: SanityClient): OptimisticStoreBackend;
declare function createOptimisticStoreMockBackend(backendAPI: MockBackendAPI): OptimisticStoreBackend;
export { AccessibleDocumentResult, AnyArray, AnyEmptyArray, AnyOp, ArrayOp, AssignOp, ByIndex, Concat, ConcatInner, Conflict, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, DocEndpointResponse, DocumentIdSetEvent, DocumentIdSetState, DocumentLoader, DocumentMap, DocumentMutationUpdate, DocumentReconnectUpdate, DocumentResult, DocumentSyncUpdate, DocumentUpdate, DocumentUpdateListener, ElementType, Err, FetchDocumentIdsFn, FetchDocuments, FindBy, FindInArray, Get, GetAtPath, IdSetListenFn, InaccessibleDocumentResult, InaccessibleReason, IncOp, Index, InitialEvent, Insert, InsertIfMissingOp, InsertMethod, InsertOp, KeyedPathElement, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerOptions, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MapTuple, Merge, MergeInner, MockBackendAPI, Mutation, MutationGroup, MutationResult, NodePatch, NodePatchList, NonTransactionalMutationGroup, NumberOp, ObjectOp, Ok, OmittedDocument, OnlyDigits, Operation, OptimisticDocumentEvent, OptimisticStore, OptimisticStoreBackend, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, QueryParams, ReadOnlyDocumentStore, RelativePosition, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, RemoveOp, ReplaceOp, RequestOptions, Result, SafePath, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, SetIfMissingOp, SetOp, SharedListenerListenFn, Split, SplitAll, StringOp, StringToPath, StripError, SubmitResult, ToArray, ToNumber, Transaction, TransactionalMutationGroup, Trim, TrimLeft, TrimRight, TruncateOp, Try, UnassignOp, UnsetOp, Unwrap, UpsertOp, createDocumentEventListener, createDocumentLoader, createDocumentLoaderFromClient, createDocumentUpdateListener, createIdSetListener, createIdSetListenerFromClient, createMockBackendAPI, createOptimisticStore, createOptimisticStoreClientBackend, createOptimisticStoreMockBackend, createReadOnlyStore, createSharedListener, createSharedListenerFromClient, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify, toState };
export { AccessibleDocumentResult, AnyArray, AnyEmptyArray, AnyOp, ArrayOp, AssignOp, ByIndex, Concat, ConcatInner, Conflict, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, DocEndpointResponse, DocumentIdSetEvent, DocumentIdSetState, DocumentLoader, DocumentMap, DocumentMutationUpdate, DocumentReconnectUpdate, DocumentResult, DocumentSyncUpdate, DocumentUpdate, DocumentUpdateListener, ElementType, Err, FetchDocumentIdsFn, FetchDocuments, FindBy, FindInArray, Get, GetAtPath, IdSetListenFn, InaccessibleDocumentResult, InaccessibleReason, IncOp, Index, InitialEvent, Insert, InsertIfMissingOp, InsertMethod, InsertOp, KeyedPathElement, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerOptions, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MapTuple, Merge, MergeInner, MockBackendAPI, Mutation, MutationGroup, MutationResult, NodePatch, NodePatchList, NonTransactionalMutationGroup, NumberOp, ObjectOp, Ok, OmittedDocument, OnlyDigits, Operation, OptimisticDocumentEvent, OptimisticStore, OptimisticStoreBackend, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, QueryParams, ReadOnlyDocumentStore, RelativePosition, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, RemoveOp, ReplaceOp, RequestOptions, Result, SafePath, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, SetIfMissingOp, SetOp, SharedListenerListenFn, Split, SplitAll, StringOp, StringToPath, StripError, SubmitResult, ToArray, ToNumber, Transaction, TransactionalMutationGroup, Trim, TrimLeft, TrimRight, TruncateOp, Try, UnassignOp, UnsetOp, Unwrap, UpsertOp, createDocumentEventListener, createDocumentLoader, createDocumentLoaderFromClient, createDocumentUpdateListener, createIdSetListener, createIdSetListenerFromClient, createMockBackendAPI, createOptimisticStore, createOptimisticStoreClientBackend, createOptimisticStoreMockBackend, createReadOnlyStore, createSharedListener, createSharedListenerFromClient, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify, toState, toTransactions };
//# sourceMappingURL=_unstable_store.d.cts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"_unstable_store.d.cts","names":[],"sources":["../src/store/types.ts","../src/store/listeners/createDocumentUpdateListener.ts","../src/store/createReadOnlyStore.ts","../src/store/listeners/types.ts","../src/store/listeners/createDocumentEventListener.ts","../src/store/listeners/createDocumentLoader.ts","../src/store/listeners/createIdSetListener.ts","../src/store/listeners/createSharedListener.ts","../src/store/mock/createMockBackendAPI.ts","../src/store/optimistic/createOptimisticStore.ts","../src/store/optimistic/backend/createOptimisticStoreClientBackend.ts","../src/store/optimistic/backend/createOptimisticStoreMockBackend.ts"],"sourcesContent":[],"mappings":";;;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dateListener.ts","../src/store/createReadOnlyStore.ts","../src/store/listeners/types.ts","../src/store/listeners/createDocumentEventListener.ts","../src/store/listeners/createDocumentLoader.ts","../src/store/listeners/createIdSetListener.ts","../src/store/listeners/createSharedListener.ts","../src/store/mock/createMockBackendAPI.ts","../src/store/optimistic/createOptimisticStore.ts","../src/store/optimistic/backend/createOptimisticStoreClientBackend.ts","../src/store/optimistic/backend/createOptimisticStoreMockBackend.ts"],"sourcesContent":[],"mappings":";;;;;;;UAeiB,+BAA+B;;YAEpC;SACH,kBAAkB;;AAHV,UAKA,sBALkB,CAAA,YAKiB,kBALjB,CAAA,CAAA;EAAA,UAAA,EAAA,MAAA;UAAa,EAOpC,GAPoC,GAAA,SAAA;OAEpC,EAMH,qBANG;;AACH,UAQQ,uBARR,CAAA,YAQ4C,kBAR5C,CAAA,CAAA;EAAiB,UAAA,EAAA,MAAA;EAET,QAAA,EAQL,GARK,GAAA,SAAsB;EAAA,KAAA,EAS9B,sBAT8B;;AAE3B,KAUA,cAVA,CAAA,YAU2B,kBAV3B,CAAA,GAWR,kBAXQ,CAWW,GAXX,CAAA,GAYR,sBAZQ,CAYe,GAZf,CAAA,GAaR,uBAbQ,CAAA,GAAA,CAAA;AACH,KAcG,sBAdH,CAAA,YAcsC,kBAdtC,CAAA,GAAA,CAAA,EAAA,EAAA,MAAA,EAAA,GAgBJ,UAhBI,CAgBO,cAhBP,CAgBsB,GAhBtB,CAAA,CAAA;;AAGT;;;;AAGS,iBAiBO,4BAAA,CAjBP,OAAA,EAAA;EAAsB,oBAAA,EAAA,CAAA,UAAA,EAAA,MAAA,EAAA,GAkBiB,UAlBjB,CAkB4B,aAlB5B,CAAA;AAG/B,CAAA,CAAA,EAAY,CAAA,YAmByB,kBAnBX,CAAA,CAAA,UAAA,EAAA,MAAA,EAAA,GAmBiD,UAnBjD,CAmBiD,cAnBjD,CAmBiD,GAnBjD,CAAA,CAAA;KCjBd,+BAA8B,IAAI;UAE7B,qBAAA;+BACc,mCAExB,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AAkB,EOYV,UPZU,COYC,qBPZD,CAAA;EAAA,YAAA,CAAA,GAAA,EAAA,MAAA,EAAA,CAAA,EOaJ,UPbI,COaO,mBPbP,CAAA;QAAa,CAAA,WAAA,EOc1B,WPd0B,CAAA,EOcZ,UPdY,COcD,YPdC,CAAA;;AAGrB,iBOaX,oBAAA,CAAA,CPbW,EOaa,cPbb;UQyBV,sBAAA;;;;;AR5BjB;;QAAgD,EAAA,CAAA,EAAA,EAAA,MAAA,EAAA,GQmCtB,URnCsB,CQmCX,aRnCW,CAAA;QAEpC,EAAA,CAAA,cAAA,EQkCe,WRlCf,EAAA,GQkC+B,URlC/B,CQkC0C,YRlC1C,CAAA;;;;AAGZ;;AAAoD,iBQyDpC,qBAAA,CRzDoC,OAAA,EQ0DzC,sBR1DyC,CAAA,EQ2DjD,eR3DiD;AAExC,iBQmQI,cAAA,CRnQJ,MAAA,EQmQ2B,aRnQ3B,EAAA,CAAA,EQmQ6C,WRnQ7C,EAAA;iBSZI,kCAAA,SACN,eACP;iBCNa,gCAAA,aACF,iBACX"}

@@ -5,153 +5,5 @@ import { AnyArray, AnyEmptyArray, ByIndex, Concat, ConcatInner, Digit, ElementType, Err, FindBy, FindInArray, Index, KeyedPathElement, Merge, MergeInner, Ok, OnlyDigits, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, Path, PathElement, PropertyName, Result, SafePath, Split, SplitAll, StringToPath, StripError, ToArray, ToNumber, Trim, TrimLeft, TrimRight, Try, Unwrap } from "./_chunks-dts/types.js";

import { Insert, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityIncPatch, SanityInsertPatch, SanityMutation, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch } from "./_chunks-dts/types3.js";
import { Conflict, DocumentMap, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MutationGroup, MutationResult, NonTransactionalMutationGroup, OptimisticDocumentEvent, OptimisticStore, QueryParams, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, SubmitResult, TransactionalMutationGroup } from "./_chunks-dts/types4.js";
import { Observable } from "rxjs";
import { RawPatch } from "mendoza";
import { ReconnectEvent, SanityClient, WelcomeEvent } from "@sanity/client";
interface ListenerSyncEvent<Doc extends SanityDocumentBase = SanityDocumentBase> {
type: 'sync';
document: Doc | undefined;
}
interface ListenerMutationEvent {
type: 'mutation';
documentId: string;
transactionId: string;
resultRev?: string;
previousRev?: string;
effects?: {
apply: RawPatch;
};
mutations: SanityMutation[];
transition: 'update' | 'appear' | 'disappear';
}
interface ListenerReconnectEvent {
type: 'reconnect';
}
type ListenerChannelErrorEvent = {
type: 'channelError';
message: string;
};
type ListenerWelcomeEvent = {
type: 'welcome';
listenerName: string;
};
type ListenerDisconnectEvent = {
type: 'disconnect';
reason: string;
};
type ListenerEndpointEvent = ListenerWelcomeEvent | ListenerMutationEvent | ListenerReconnectEvent | ListenerChannelErrorEvent | ListenerDisconnectEvent;
type ListenerEvent<Doc extends SanityDocumentBase = SanityDocumentBase> = ListenerSyncEvent<Doc> | ListenerMutationEvent | ListenerReconnectEvent;
interface OptimisticDocumentEvent {
type: 'optimistic';
id: string;
before: SanityDocumentBase | undefined;
after: SanityDocumentBase | undefined;
mutations: Mutation[];
stagedChanges: Mutation[];
}
type QueryParams = Record<string, string | number | boolean | (string | number | boolean)[]>;
interface RemoteSyncEvent {
type: 'sync';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
rebasedStage: MutationGroup[];
}
interface RemoteMutationEvent {
type: 'mutation';
id: string;
before: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
after: {
local: SanityDocumentBase | undefined;
remote: SanityDocumentBase | undefined;
};
effects?: {
apply: RawPatch;
};
previousRev?: string;
resultRev?: string;
mutations: Mutation[];
rebasedStage: MutationGroup[];
}
type RemoteDocumentEvent = RemoteSyncEvent | RemoteMutationEvent;
type DocumentMap<Doc extends SanityDocumentBase> = {
get(id: string): Doc | undefined;
set(id: string, doc: Doc | undefined): void;
delete(id: string): void;
};
interface MutationResult {}
interface SubmitResult {}
interface NonTransactionalMutationGroup {
transaction: false;
mutations: Mutation[];
}
interface TransactionalMutationGroup {
transaction: true;
id?: string;
mutations: Mutation[];
}
/**
* A mutation group represents an incoming, locally added group of mutations
* They can either be transactional or non-transactional
* - Transactional means that they must be submitted as a separate transaction (with an optional id) and no other mutations can be mixed with it
* – Non-transactional means that they can be combined with other mutations
*/
type MutationGroup = NonTransactionalMutationGroup | TransactionalMutationGroup;
type Conflict = {
path: Path;
error: Error;
base: SanityDocumentBase | undefined;
local: SanityDocumentBase | undefined;
};
interface OptimisticStore {
meta: {
/**
* A stream of events for anything that happens in the store
*/
events: Observable<OptimisticDocumentEvent | RemoteDocumentEvent>;
/**
* A stream of current staged changes
*/
stage: Observable<MutationGroup[]>;
/**
* A stream of current conflicts. TODO: Needs more work
*/
conflicts: Observable<Conflict[]>;
};
/**
* Applies the given mutations. Mutations are not guaranteed to be submitted in the same transaction
* Can this mutate both local and remote documents at the same time
*/
mutate(mutation: Mutation[]): MutationResult;
/**
* Makes sure the given mutations are posted in a single transaction
*/
transaction(transaction: {
id?: string;
mutations: Mutation[];
} | Mutation[]): MutationResult;
/**
* Checkout a document for editing. This is required to be able to see optimistic changes
*/
listen(id: string): Observable<SanityDocumentBase | undefined>;
/**
* Listen for events for a given document id
*/
listenEvents(id: string): Observable<RemoteDocumentEvent | OptimisticDocumentEvent>;
/**
* Optimize list of pending mutations
*/
optimize(): void;
/**
* Submit pending mutations
*/
submit(): Promise<SubmitResult[]>;
}
interface DocumentSyncUpdate<Doc extends SanityDocumentBase> {

@@ -349,5 +201,6 @@ documentId: string;

declare function createOptimisticStore(backend: OptimisticStoreBackend): OptimisticStore;
declare function toTransactions(groups: MutationGroup[]): Transaction[];
declare function createOptimisticStoreClientBackend(client: SanityClient): OptimisticStoreBackend;
declare function createOptimisticStoreMockBackend(backendAPI: MockBackendAPI): OptimisticStoreBackend;
export { AccessibleDocumentResult, AnyArray, AnyEmptyArray, AnyOp, ArrayOp, AssignOp, ByIndex, Concat, ConcatInner, Conflict, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, DocEndpointResponse, DocumentIdSetEvent, DocumentIdSetState, DocumentLoader, DocumentMap, DocumentMutationUpdate, DocumentReconnectUpdate, DocumentResult, DocumentSyncUpdate, DocumentUpdate, DocumentUpdateListener, ElementType, Err, FetchDocumentIdsFn, FetchDocuments, FindBy, FindInArray, Get, GetAtPath, IdSetListenFn, InaccessibleDocumentResult, InaccessibleReason, IncOp, Index, InitialEvent, Insert, InsertIfMissingOp, InsertMethod, InsertOp, KeyedPathElement, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerOptions, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MapTuple, Merge, MergeInner, MockBackendAPI, Mutation, MutationGroup, MutationResult, NodePatch, NodePatchList, NonTransactionalMutationGroup, NumberOp, ObjectOp, Ok, OmittedDocument, OnlyDigits, Operation, OptimisticDocumentEvent, OptimisticStore, OptimisticStoreBackend, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, QueryParams, ReadOnlyDocumentStore, RelativePosition, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, RemoveOp, ReplaceOp, RequestOptions, Result, SafePath, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, SetIfMissingOp, SetOp, SharedListenerListenFn, Split, SplitAll, StringOp, StringToPath, StripError, SubmitResult, ToArray, ToNumber, Transaction, TransactionalMutationGroup, Trim, TrimLeft, TrimRight, TruncateOp, Try, UnassignOp, UnsetOp, Unwrap, UpsertOp, createDocumentEventListener, createDocumentLoader, createDocumentLoaderFromClient, createDocumentUpdateListener, createIdSetListener, createIdSetListenerFromClient, createMockBackendAPI, createOptimisticStore, createOptimisticStoreClientBackend, createOptimisticStoreMockBackend, createReadOnlyStore, createSharedListener, createSharedListenerFromClient, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify, toState };
export { AccessibleDocumentResult, AnyArray, AnyEmptyArray, AnyOp, ArrayOp, AssignOp, ByIndex, Concat, ConcatInner, Conflict, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, DocEndpointResponse, DocumentIdSetEvent, DocumentIdSetState, DocumentLoader, DocumentMap, DocumentMutationUpdate, DocumentReconnectUpdate, DocumentResult, DocumentSyncUpdate, DocumentUpdate, DocumentUpdateListener, ElementType, Err, FetchDocumentIdsFn, FetchDocuments, FindBy, FindInArray, Get, GetAtPath, IdSetListenFn, InaccessibleDocumentResult, InaccessibleReason, IncOp, Index, InitialEvent, Insert, InsertIfMissingOp, InsertMethod, InsertOp, KeyedPathElement, ListenerChannelErrorEvent, ListenerDisconnectEvent, ListenerEndpointEvent, ListenerEvent, ListenerMutationEvent, ListenerOptions, ListenerReconnectEvent, ListenerSyncEvent, ListenerWelcomeEvent, MapTuple, Merge, MergeInner, MockBackendAPI, Mutation, MutationGroup, MutationResult, NodePatch, NodePatchList, NonTransactionalMutationGroup, NumberOp, ObjectOp, Ok, OmittedDocument, OnlyDigits, Operation, OptimisticDocumentEvent, OptimisticStore, OptimisticStoreBackend, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, QueryParams, ReadOnlyDocumentStore, RelativePosition, RemoteDocumentEvent, RemoteMutationEvent, RemoteSyncEvent, RemoveOp, ReplaceOp, RequestOptions, Result, SafePath, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, SetIfMissingOp, SetOp, SharedListenerListenFn, Split, SplitAll, StringOp, StringToPath, StripError, SubmitResult, ToArray, ToNumber, Transaction, TransactionalMutationGroup, Trim, TrimLeft, TrimRight, TruncateOp, Try, UnassignOp, UnsetOp, Unwrap, UpsertOp, createDocumentEventListener, createDocumentLoader, createDocumentLoaderFromClient, createDocumentUpdateListener, createIdSetListener, createIdSetListenerFromClient, createMockBackendAPI, createOptimisticStore, createOptimisticStoreClientBackend, createOptimisticStoreMockBackend, createReadOnlyStore, createSharedListener, createSharedListenerFromClient, getAtPath, isArrayElement, isElementEqual, isEqual, isIndexElement, isKeyElement, isKeyedElement, isPropertyElement, normalize, parse, startsWith, stringify, toState, toTransactions };
//# sourceMappingURL=_unstable_store.d.ts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"_unstable_store.d.ts","names":[],"sources":["../src/store/types.ts","../src/store/listeners/createDocumentUpdateListener.ts","../src/store/createReadOnlyStore.ts","../src/store/listeners/types.ts","../src/store/listeners/createDocumentEventListener.ts","../src/store/listeners/createDocumentLoader.ts","../src/store/listeners/createIdSetListener.ts","../src/store/listeners/createSharedListener.ts","../src/store/mock/createMockBackendAPI.ts","../src/store/optimistic/createOptimisticStore.ts","../src/store/optimistic/backend/createOptimisticStoreClientBackend.ts","../src/store/optimistic/backend/createOptimisticStoreMockBackend.ts"],"sourcesContent":[],"mappings":";;;;;;;UAOiB,8BACH,qBAAqB;;YAGvB;AAJZ;AAAkC,UAOjB,qBAAA,CAPiB;MACpB,EAAA,UAAA;YAAqB,EAAA,MAAA;eAGvB,EAAA,MAAA;EAAG,SAAA,CAAA,EAAA,MAAA;EAGE,WAAA,CAAA,EAAA,MAAA;EAAqB,OAAA,CAAA,EAAA;IAMlB,KAAA,EAAA,QAAA;;EACO,SAAA,EAAd,cAAc,EAAA;EAIV,UAAA,EAAA,QAAA,GAAA,QAAsB,GAAA,WAAA;AAIvC;AAKY,UATK,sBAAA,CASe;EAKpB,IAAA,EAAA,WAAA;AAIZ;AAAiC,KAdrB,yBAAA,GAcqB;MAC7B,EAAA,cAAA;SACA,EAAA,MAAA;;AAEA,KAbQ,oBAAA,GAaR;MACA,EAAA,SAAA;EAAuB,YAAA,EAAA,MAAA;AAE3B,CAAA;AAAyB,KAXb,uBAAA,GAWa;MAAa,EAAA,YAAA;QAAqB,EAAA,MAAA;;AACzD,KARU,qBAAA,GACR,oBAOF,GANE,qBAMF,GALE,sBAKF,GAJE,yBAIF,GAHE,uBAGF;AAAyB,KADf,aACe,CAAA,YADW,kBACX,GADgC,kBAChC,CAAA,GAAzB,iBAAyB,CAAP,GAAO,CAAA,GAAA,qBAAA,GAAwB,sBAAxB;AAAwB,UAElC,uBAAA,CAFkC;EAAsB,IAAA,EAAA,YAAA;EAExD,EAAA,EAAA,MAAA;EAAuB,MAAA,EAG9B,kBAH8B,GAAA,SAAA;OAG9B,EACD,kBADC,GAAA,SAAA;WACD,EACI,QADJ,EAAA;eACI,EACI,QADJ,EAAA;;AACY,KAGb,WAAA,GAAc,MAHD,CAAA,MAAA,EAAA,MAAA,GAAA,MAAA,GAAA,OAAA,GAAA,CAAA,MAAA,GAAA,MAAA,GAAA,OAAA,CAAA,EAAA,C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V,eT1DU;iBUXG,kCAAA,SACN,eACP;iBCNa,gCAAA,aACF,iBACX"}
{"version":3,"file":"_unstable_store.d.ts","names":[],"sources":["../src/store/listeners/createDocumentUpdateListener.ts","../src/store/createReadOnlyStore.ts","../src/store/listeners/types.ts","../src/store/listeners/createDocumentEventListener.ts","../src/store/listeners/createDocumentLoader.ts","../src/store/listeners/createIdSetListener.ts","../src/store/listeners/createSharedListener.ts","../src/store/mock/createMockBackendAPI.ts","../src/store/optimistic/createOptimisticStore.ts","../src/store/optimistic/backend/createOptimisticStoreClientBackend.ts","../src/store/optimistic/backend/createOptimisticStoreMockBackend.ts"],"sourcesContent":[],"mappings":";;;;;;;UAeiB,+BAA+B;;YAEpC;SACH,kBAAkB;;AAHV,UAKA,sBALkB,CAAA,YAKiB,kBALjB,CAAA,CAAA;EAAA,UAAA,EAAA,MAAA;UAAa,EAOpC,GAPoC,GAAA,SAAA;OAEpC,EAMH,qBANG;;AACH,UAQQ,uBARR,CAAA,YAQ4C,kBAR5C,CAAA,CAAA;EAAiB,UAAA,EAAA,MAAA;EAET,QAAA,EAQL,GARK,GAAA,SAAsB;EAAA,KAAA,EAS9B,sBAT8B;;AAE3B,KAUA,cAVA,CAAA,YAU2B,kBAV3B,CAAA,GAWR,kBAXQ,CAWW,GAXX,CAAA,GAYR,sBAZQ,CAYe,GAZf,CAAA,GAaR,uBAbQ,CAAA,GAAA,CAAA;AACH,KAcG,sBAdH,CAAA,YAcsC,kBAdtC,CAAA,GAAA,CAAA,EAAA,EAAA,MAAA,EAAA,GAgBJ,UAhBI,CAgBO,cAhBP,CAgBsB,GAhBtB,CAAA,CAAA;;AAGT;;;;AAGS,iBAiBO,4BAAA,CAjBP,OAAA,EAAA;EAAsB,oBAAA,EAAA,CAAA,UAAA,EAAA,MAAA,EAAA,GAkBiB,UAlBjB,CAkB4B,aAlB5B,CAAA;AAG/B,CAAA,CAAA,EAAY,CAAA,YAmByB,kBAnBX,CAAA,CAAA,UAAA,EAAA,MAAA,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CwE,CMuC7D,YNvC6D,GMuC9C,qBNvC8C,GMuCtB,cNvCsB,CAAA;;;;UOzB1D,cAAA;EPXA,MAAA,CAAA,KAAA,EAAA,MAAA,CAAkB,EOYV,UPZU,COYC,qBPZD,CAAA;EAAA,YAAA,CAAA,GAAA,EAAA,MAAA,EAAA,CAAA,EOaJ,UPbI,COaO,mBPbP,CAAA;QAAa,CAAA,WAAA,EOc1B,WPd0B,CAAA,EOcZ,UPdY,COcD,YPdC,CAAA;;AAGrB,iBOaX,oBAAA,CAAA,CPbW,EOaa,cPbb;UQyBV,sBAAA;;;;;AR5BjB;;QAAgD,EAAA,CAAA,EAAA,EAAA,MAAA,EAAA,GQmCtB,URnCsB,CQmCX,aRnCW,CAAA;QAEpC,EAAA,CAAA,cAAA,EQkCe,WRlCf,EAAA,GQkC+B,URlC/B,CQkC0C,YRlC1C,CAAA;;;;AAGZ;;AAAoD,iBQyDpC,qBAAA,CRzDoC,OAAA,EQ0DzC,sBR1DyC,CAAA,EQ2DjD,eR3DiD;AAExC,iBQmQI,cAAA,CRnQJ,MAAA,EQmQ2B,aRnQ3B,EAAA,CAAA,EQmQ6C,WRnQ7C,EAAA;iBSZI,kCAAA,SACN,eACP;iBCNa,gCAAA,aACF,iBACX"}

@@ -1,2 +0,2 @@

import { combineLatest, finalize, share, ReplaySubject, timer, switchMap, concat, of, throwError, concatMap, EMPTY, catchError, map, BehaviorSubject, Subject, filter, bufferWhen, scheduled, mergeMap as mergeMap$1, takeUntil, Observable, defer, merge, takeWhile, asyncScheduler, tap, NEVER, from, lastValueFrom, toArray } from "rxjs";
import { combineLatest, finalize, share, ReplaySubject, timer, switchMap, concat, of, throwError, concatMap, EMPTY, catchError, map, BehaviorSubject, Subject, filter, bufferWhen, scheduled, mergeMap as mergeMap$1, takeUntil, Observable, defer, merge, takeWhile, asyncScheduler, tap, NEVER, from } from "rxjs";
import lodashPartition from "lodash/partition.js";

@@ -6,11 +6,5 @@ import { scan, mergeMap, map as map$1, filter as filter$1 } from "rxjs/operators";

import { decodeAll, encodeAll, encodeTransaction } from "./_chunks-es/encode.js";
import { nanoid } from "nanoid";
import { assignId, hasId, applyPatchMutation, applyNodePatch, applyPatches } from "./_chunks-es/utils.js";
import { applyPatch } from "mendoza";
import { hasProperty, applyMutationEventEffects, applyAll, applyMutations, createDocumentMap, createTransactionId } from "./_chunks-es/createOptimisticStore.js";
import { createOptimisticStore, toTransactions } from "./_chunks-es/createOptimisticStore.js";
import sortedIndex from "lodash/sortedIndex.js";
import { uuid } from "@sanity/uuid";
import { stringifyPatches, makePatches } from "@sanity/diff-match-patch";
import { getAtPath } from "./_chunks-es/getAtPath.js";
import { startsWith, stringify } from "./_chunks-es/stringify.js";
import groupBy from "lodash/groupBy.js";
function createReadOnlyStore(listenDocumentUpdates, options = {}) {

@@ -108,3 +102,3 @@ const cache = /* @__PURE__ */ new Map(), { shutdownDelay } = options;

}
const DEFAULT_MAX_BUFFER_SIZE = 20, DEFAULT_DEADLINE_MS = 3e4, EMPTY_ARRAY$1 = [];
const DEFAULT_MAX_BUFFER_SIZE = 20, DEFAULT_DEADLINE_MS = 3e4, EMPTY_ARRAY = [];
function sequentializeListenerEvents(options) {

@@ -127,3 +121,3 @@ const {

base: { revision: event.document?._rev },
buffer: EMPTY_ARRAY$1,
buffer: EMPTY_ARRAY,
emitEvents: [event]

@@ -170,3 +164,3 @@ };

buffer: nextBuffer,
emitEvents: EMPTY_ARRAY$1
emitEvents: EMPTY_ARRAY
};

@@ -177,5 +171,5 @@ }

{
emitEvents: EMPTY_ARRAY$1,
emitEvents: EMPTY_ARRAY,
base: void 0,
buffer: EMPTY_ARRAY$1
buffer: EMPTY_ARRAY
}

@@ -326,93 +320,2 @@ ),

}
function applyAll(current, mutation) {
return mutation.reduce((doc, m) => {
const res = applyDocumentMutation(doc, m);
if (res.status === "error")
throw new Error(res.message);
return res.status === "noop" ? doc : res.after;
}, current);
}
function applyDocumentMutation(document, mutation) {
if (mutation.type === "create")
return create(document, mutation);
if (mutation.type === "createIfNotExists")
return createIfNotExists(document, mutation);
if (mutation.type === "delete")
return del(document, mutation);
if (mutation.type === "createOrReplace")
return createOrReplace(document, mutation);
if (mutation.type === "patch")
return patch(document, mutation);
throw new Error(`Invalid mutation type: ${mutation.type}`);
}
function create(document, mutation) {
if (document)
return { status: "error", message: "Document already exist" };
const result = assignId(mutation.document, nanoid);
return { status: "created", id: result._id, after: result };
}
function createIfNotExists(document, mutation) {
return hasId(mutation.document) ? document ? { status: "noop" } : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function createOrReplace(document, mutation) {
return hasId(mutation.document) ? document ? {
status: "updated",
id: mutation.document._id,
before: document,
after: mutation.document
} : { status: "created", id: mutation.document._id, after: mutation.document } : {
status: "error",
message: "Cannot createIfNotExists on document without _id"
};
}
function del(document, mutation) {
return document ? mutation.id !== document._id ? { status: "error", message: "Delete mutation targeted wrong document" } : {
status: "deleted",
id: mutation.id,
before: document,
after: void 0
} : { status: "noop" };
}
function patch(document, mutation) {
if (!document)
return {
status: "error",
message: "Cannot apply patch on nonexistent document"
};
const next = applyPatchMutation(mutation, document);
return document === next ? { status: "noop" } : { status: "updated", id: mutation.id, before: document, after: next };
}
function omitRev(document) {
if (document === void 0)
return;
const { _rev, ...doc } = document;
return doc;
}
function applyMendozaPatch(document, patch2, patchBaseRev) {
if (patchBaseRev !== document?._rev)
throw new Error(
"Invalid document revision. The provided patch is calculated from a different revision than the current document"
);
const next = applyPatch(omitRev(document), patch2);
return next === null ? void 0 : next;
}
function applyMutationEventEffects(document, event) {
if (!event.effects)
throw new Error(
"Mutation event is missing effects. Is the listener set up with effectFormat=mendoza?"
);
const next = applyMendozaPatch(
document,
event.effects.apply,
event.previousRev
);
return next ? { ...next, _rev: event.resultRev } : void 0;
}
function hasProperty(value, property) {
const val = value[property];
return typeof val < "u" && val !== null;
}
function createDocumentUpdateListener(options) {

@@ -624,48 +527,2 @@ const { listenDocumentEvents } = options;

}
function getMutationDocumentId(mutation) {
if (mutation.type === "patch")
return mutation.id;
if (mutation.type === "create")
return mutation.document._id;
if (mutation.type === "delete")
return mutation.id;
if (mutation.type === "createIfNotExists" || mutation.type === "createOrReplace")
return mutation.document._id;
throw new Error("Invalid mutation type");
}
function applyMutations(mutations, documentMap, transactionId) {
const updatedDocs = /* @__PURE__ */ Object.create(null);
for (const mutation of mutations) {
const documentId = getMutationDocumentId(mutation);
if (!documentId)
throw new Error("Unable to get document id from mutation");
const before = updatedDocs[documentId]?.after || documentMap.get(documentId), res = applyDocumentMutation(before, mutation);
if (res.status === "error")
throw new Error(res.message);
let entry = updatedDocs[documentId];
entry || (entry = { before, after: before, mutations: [] }, updatedDocs[documentId] = entry);
const after = transactionId ? { ...res.status === "noop" ? before : res.after, _rev: transactionId } : res.status === "noop" ? before : res.after;
documentMap.set(documentId, after), entry.after = after, entry.mutations.push(mutation);
}
return Object.entries(updatedDocs).map(
([id, { before, after, mutations: muts }]) => ({
id,
status: after ? before ? "updated" : "created" : "deleted",
mutations: muts,
before,
after
})
);
}
function createDocumentMap() {
const documents = /* @__PURE__ */ new Map();
return {
set: (id, doc) => void documents.set(id, doc),
get: (id) => documents.get(id),
delete: (id) => documents.delete(id)
};
}
function createTransactionId() {
return uuid();
}
function createWelcomeEvent() {

@@ -739,402 +596,2 @@ return {

}
function commit(results, documentMap) {
results.forEach((result) => {
(result.status === "created" || result.status === "updated") && documentMap.set(result.id, result.after), result.status === "deleted" && documentMap.delete(result.id);
});
}
function createReplayMemoizer(expiry) {
const memo = /* @__PURE__ */ Object.create(null);
return function(key, observable) {
return key in memo || (memo[key] = observable.pipe(
finalize(() => {
delete memo[key];
}),
share({
connector: () => new ReplaySubject(1),
resetOnRefCountZero: () => timer(expiry)
})
)), memo[key];
};
}
function filterMutationGroupsById(mutationGroups, id) {
return mutationGroups.flatMap(
(mutationGroup) => mutationGroup.mutations.flatMap(
(mut) => getMutationDocumentId(mut) === id ? [mut] : []
)
);
}
function takeUntilRight(arr, predicate, opts) {
const result = [];
for (const item of arr.slice().reverse()) {
if (predicate(item))
return result;
result.push(item);
}
return result.reverse();
}
function isEqualPath(p1, p2) {
return stringify(p1) === stringify(p2);
}
function supersedes(later, earlier) {
return (earlier.type === "set" || earlier.type === "unset") && (later.type === "set" || later.type === "unset");
}
function squashNodePatches(patches) {
return compactSetIfMissingPatches(
compactSetPatches(compactUnsetPatches(patches))
);
}
function compactUnsetPatches(patches) {
return patches.reduce(
(earlierPatches, laterPatch) => {
if (laterPatch.op.type !== "unset")
return earlierPatches.push(laterPatch), earlierPatches;
const unaffected = earlierPatches.filter(
(earlierPatch) => !startsWith(laterPatch.path, earlierPatch.path)
);
return unaffected.push(laterPatch), unaffected;
},
[]
);
}
function compactSetPatches(patches) {
return patches.reduceRight(
(laterPatches, earlierPatch) => (laterPatches.find(
(later) => supersedes(later.op, earlierPatch.op) && isEqualPath(later.path, earlierPatch.path)
) || laterPatches.unshift(earlierPatch), laterPatches),
[]
);
}
function compactSetIfMissingPatches(patches) {
return patches.reduce(
(previousPatches, laterPatch) => laterPatch.op.type !== "setIfMissing" ? (previousPatches.push(laterPatch), previousPatches) : (takeUntilRight(
previousPatches,
(patch2) => patch2.op.type === "unset"
).find(
(precedingPatch) => precedingPatch.op.type === "setIfMissing" && isEqualPath(precedingPatch.path, laterPatch.path)
) || previousPatches.push(laterPatch), previousPatches),
[]
);
}
function compactDMPSetPatches(base, patches) {
let edge = base;
return patches.reduce(
(earlierPatches, laterPatch) => {
const before = edge;
if (edge = applyNodePatch(laterPatch, edge), laterPatch.op.type === "set" && typeof laterPatch.op.value == "string") {
const current = getAtPath(laterPatch.path, before);
if (typeof current == "string") {
const replaced = {
...laterPatch,
op: {
type: "diffMatchPatch",
value: stringifyPatches(
makePatches(current, laterPatch.op.value)
)
}
};
return earlierPatches.flatMap((ep) => isEqualPath(ep.path, laterPatch.path) && ep.op.type === "diffMatchPatch" ? [] : ep).concat(replaced);
}
}
return earlierPatches.push(laterPatch), earlierPatches;
},
[]
);
}
function squashDMPStrings(base, mutationGroups) {
return mutationGroups.map((mutationGroup) => ({
...mutationGroup,
mutations: dmpIfyMutations(base, mutationGroup.mutations)
}));
}
function dmpIfyMutations(store, mutations) {
return mutations.map((mutation, i) => {
if (mutation.type !== "patch")
return mutation;
const base = store.get(mutation.id);
return base ? dmpifyPatchMutation(base, mutation) : mutation;
});
}
function dmpifyPatchMutation(base, mutation) {
return {
...mutation,
patches: compactDMPSetPatches(base, mutation.patches)
};
}
function mergeMutationGroups(mutationGroups) {
return chunkWhile(mutationGroups, (group) => !group.transaction).flatMap(
(chunk) => ({
...chunk[0],
mutations: chunk.flatMap((c) => c.mutations)
})
);
}
function chunkWhile(arr, predicate) {
const res = [];
let currentChunk = [];
return arr.forEach((item) => {
predicate(item) ? currentChunk.push(item) : (currentChunk.length > 0 && res.push(currentChunk), currentChunk = [], res.push([item]));
}), currentChunk.length > 0 && res.push(currentChunk), res;
}
function squashMutationGroups(staged) {
return mergeMutationGroups(staged).map((transaction) => ({
...transaction,
mutations: squashMutations(transaction.mutations)
})).map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mutation) => mutation.type !== "patch" ? mutation : {
...mutation,
patches: squashNodePatches(mutation.patches)
})
}));
}
function squashMutations(mutations) {
const byDocument = groupBy(mutations, getMutationDocumentId);
return Object.values(byDocument).flatMap((documentMutations) => squashCreateIfNotExists(squashDelete(documentMutations)).flat().reduce((acc, docMutation) => {
const prev = acc[acc.length - 1];
return (!prev || prev.type === "patch") && docMutation.type === "patch" ? acc.slice(0, -1).concat({
...docMutation,
patches: (prev?.patches || []).concat(docMutation.patches)
}) : acc.concat(docMutation);
}, []));
}
function squashCreateIfNotExists(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type !== "createIfNotExists" ? (previousMuts.push(laterMut), previousMuts) : (takeUntilRight(previousMuts, (m) => m.type === "delete").find(
(precedingPatch) => precedingPatch.type === "createIfNotExists"
) || previousMuts.push(laterMut), previousMuts), []);
}
function squashDelete(mutations) {
return mutations.length === 0 ? mutations : mutations.reduce((previousMuts, laterMut) => laterMut.type === "delete" ? [laterMut] : (previousMuts.push(laterMut), previousMuts), []);
}
function rebase(documentId, oldBase, newBase, localMutations) {
let edge = oldBase;
const dmpified = localMutations.map((transaction) => {
const mutations = transaction.mutations.flatMap((mut) => {
if (getMutationDocumentId(mut) !== documentId)
return [];
const before = edge;
return edge = applyAll(edge, [mut]), !before || mut.type !== "patch" ? mut : {
type: "dmpified",
mutation: {
...mut,
// Todo: make compactDMPSetPatches return pairs of patches that was dmpified with their
// original as dmpPatches and original is not 1:1 (e..g some of the original may not be dmpified)
dmpPatches: compactDMPSetPatches(before, mut.patches),
original: mut.patches
}
};
});
return { ...transaction, mutations };
});
let newBaseWithDMPForOldBaseApplied = newBase;
return dmpified.map((transaction) => {
const applied = [];
return transaction.mutations.forEach((mut) => {
if (mut.type === "dmpified")
try {
newBaseWithDMPForOldBaseApplied = applyPatches(
mut.mutation.dmpPatches,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch {
console.warn("Failed to apply dmp patch, falling back to original");
try {
newBaseWithDMPForOldBaseApplied = applyPatches(
mut.mutation.original,
newBaseWithDMPForOldBaseApplied
), applied.push(mut);
} catch (second) {
throw new Error(
`Failed to apply patch for document "${documentId}": ${second.message}`
);
}
}
else
newBaseWithDMPForOldBaseApplied = applyAll(
newBaseWithDMPForOldBaseApplied,
[mut]
);
});
}), [localMutations.map((transaction) => ({
...transaction,
mutations: transaction.mutations.map((mut) => mut.type !== "patch" || getMutationDocumentId(mut) !== documentId ? mut : {
...mut,
patches: mut.patches.map((patch2) => patch2.op.type !== "set" ? patch2 : {
...patch2,
op: {
...patch2.op,
value: getAtPath(patch2.path, newBaseWithDMPForOldBaseApplied)
}
})
})
})), newBaseWithDMPForOldBaseApplied];
}
let didEmitMutationsAccessWarning = !1;
function warnNoMutationsReceived() {
didEmitMutationsAccessWarning || (console.warn(
new Error(
"No mutation received from backend. The listener is likely set up with `excludeMutations: true`. If your app need to know about mutations, make sure the listener is set up to include mutations"
)
), didEmitMutationsAccessWarning = !0);
}
const EMPTY_ARRAY = [];
function createOptimisticStore(backend) {
const local = createDocumentMap(), remote = createDocumentMap(), memoize = createReplayMemoizer(1e3);
let stagedChanges = [];
const remoteEvents$ = new Subject(), localMutations$ = new Subject(), stage$ = new Subject();
function setStaged(nextPending) {
stagedChanges = nextPending, stage$.next();
}
function getLocalEvents(id) {
return localMutations$.pipe(filter((event) => event.id === id));
}
function getRemoteEvents(id) {
return backend.listen(id).pipe(
filter(
(event) => event.type !== "reconnect"
),
mergeMap$1((event) => {
const oldLocal = local.get(id), oldRemote = remote.get(id);
if (event.type === "sync") {
const newRemote = event.document, [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
return of({
type: "sync",
id,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
rebasedStage
});
} else if (event.type === "mutation") {
if (event.transactionId === oldRemote?._rev)
return EMPTY;
let newRemote;
if (hasProperty(event, "effects"))
newRemote = applyMutationEventEffects(oldRemote, event);
else if (hasProperty(event, "mutations"))
newRemote = applyAll(oldRemote, decodeAll(event.mutations));
else
throw new Error(
"Neither effects or mutations found on listener event"
);
const [rebasedStage, newLocal] = rebase(
id,
oldRemote,
newRemote,
stagedChanges
);
newLocal && (newLocal._rev = event.transactionId);
const emittedEvent = {
type: "mutation",
id,
rebasedStage,
before: { remote: oldRemote, local: oldLocal },
after: { remote: newRemote, local: newLocal },
effects: event.effects,
previousRev: event.previousRev,
resultRev: event.resultRev,
// overwritten below
mutations: EMPTY_ARRAY
};
return event.mutations ? emittedEvent.mutations = decodeAll(
event.mutations
) : Object.defineProperty(
emittedEvent,
"mutations",
warnNoMutationsReceived
), of(emittedEvent);
} else
throw new Error(`Unknown event type: ${event.type}`);
}),
tap((event) => {
local.set(event.id, event.after.local), remote.set(event.id, event.after.remote), setStaged(event.rebasedStage);
}),
tap({
next: (event) => remoteEvents$.next(event),
error: (err) => {
}
})
);
}
function listenEvents(id) {
return defer(
() => memoize(id, merge(getLocalEvents(id), getRemoteEvents(id)))
);
}
return {
meta: {
events: merge(localMutations$, remoteEvents$),
stage: stage$.pipe(
map(
() => (
// note: this should not be tampered with by consumers. We might want to do a deep-freeze during dev to avoid accidental mutations
stagedChanges
)
)
),
conflicts: EMPTY
// does nothing for now
},
mutate: (mutations) => {
stagedChanges.push({ transaction: !1, mutations });
const results = applyMutations(mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
before: result.before,
after: result.after,
mutations: result.mutations,
id: result.id,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
transaction: (mutationsOrTransaction) => {
const transaction = Array.isArray(
mutationsOrTransaction
) ? { mutations: mutationsOrTransaction, transaction: !0 } : { ...mutationsOrTransaction, transaction: !0 };
stagedChanges.push(transaction);
const results = applyMutations(transaction.mutations, local);
return commit(results, local), results.forEach((result) => {
localMutations$.next({
type: "optimistic",
mutations: result.mutations,
id: result.id,
before: result.before,
after: result.after,
stagedChanges: filterMutationGroupsById(stagedChanges, result.id)
});
}), results;
},
listenEvents,
listen: (id) => listenEvents(id).pipe(
map(
(event) => event.type === "optimistic" ? event.after : event.after.local
)
),
optimize: () => {
setStaged(squashMutationGroups(stagedChanges));
},
submit: () => {
const pending = stagedChanges;
return setStaged([]), lastValueFrom(
from(
toTransactions(
// Squashing DMP strings is the last thing we do before submitting
squashDMPStrings(remote, squashMutationGroups(pending))
)
).pipe(
concatMap((mut) => backend.submit(mut)),
toArray()
)
);
}
};
}
function toTransactions(groups) {
return groups.map((group) => group.transaction && group.id !== void 0 ? { id: group.id, mutations: group.mutations } : { id: createTransactionId(), mutations: group.mutations });
}
export {

@@ -1154,4 +611,5 @@ createDocumentEventListener,

createSharedListenerFromClient,
toState
toState,
toTransactions
};
//# sourceMappingURL=_unstable_store.js.map

@@ -0,320 +1,5 @@

import { Arrify, append, assign, at, autoKeys, compact_d_exports, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, index_d_exports as index_d_exports$2, index_d_exports$1, index_d_exports$2 as index_d_exports, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert } from "./_chunks-dts/index.cjs";
import { AnyArray, AnyEmptyArray, ArrayElement, ByIndex, Concat, ConcatInner, Digit, ElementType, Err, FindBy, FindInArray, Index, KeyedPathElement, Merge, MergeInner, NormalizeReadOnlyArray, Ok, OnlyDigits, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, Path, PathElement, PropertyName, Result, SafePath, Split, SplitAll, StringToPath, StripError, ToArray, ToNumber, Trim, TrimLeft, TrimRight, Try, Tuplify, Unwrap } from "./_chunks-dts/types.cjs";
import { AnyOp, ArrayOp, AssignOp, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, IdentifiedSanityDocument, IncOp, InsertIfMissingOp, InsertOp, Mutation, NodePatch, NodePatchList, NumberOp, ObjectOp, Operation, PatchMutation, PatchOptions, PrimitiveOp, RelativePosition, RemoveOp, ReplaceOp, SanityDocumentBase, SetIfMissingOp, SetOp, StringOp, Transaction, TruncateOp, UnassignOp, UnsetOp, UpsertOp } from "./_chunks-dts/types2.cjs";
import { Insert, InsertAfter, InsertBefore, InsertReplace, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch } from "./_chunks-dts/types3.cjs";
declare function decodeAll<Doc extends SanityDocumentBase>(sanityMutations: SanityMutation<Doc>[]): Mutation[];
declare function decode$1<Doc extends SanityDocumentBase>(encodedMutation: SanityMutation<Doc>): Mutation;
type Id = string;
type RevisionLock = string;
type CompactPath = string;
type ItemRef$1 = string | number;
type DeleteMutation$1 = ['delete', Id];
type CreateMutation$1<Doc> = ['create', Doc];
type CreateIfNotExistsMutation$1<Doc> = ['createIfNotExists', Doc];
type CreateOrReplaceMutation$1<Doc> = ['createOrReplace', Doc];
type UnsetMutation = ['patch', 'unset', Id, CompactPath, [], RevisionLock?];
type InsertMutation = ['patch', 'insert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type UpsertMutation = ['patch', 'upsert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type InsertIfMissingMutation = ['patch', 'insertIfMissing', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type TruncateMutation = ['patch', 'truncate', Id, CompactPath, [startIndex: number, endIndex: number | undefined], RevisionLock?];
type IncMutation = ['patch', 'inc', Id, CompactPath, [number], RevisionLock?];
type DecMutation = ['patch', 'dec', Id, CompactPath, [number], RevisionLock?];
type AssignMutation = ['patch', 'assign', Id, CompactPath, [object], RevisionLock?];
type UnassignMutation = ['patch', 'assign', Id, CompactPath, [string[]], RevisionLock?];
type ReplaceMutation = ['patch', 'replace', Id, CompactPath, [ItemRef$1, AnyArray], RevisionLock?];
type RemoveMutation = ['patch', 'remove', Id, CompactPath, [ItemRef$1], RevisionLock?];
type SetMutation = ['patch', 'set', Id, CompactPath, any, RevisionLock?];
type SetIfMissingMutation = ['patch', 'setIfMissing', Id, CompactPath, [unknown], RevisionLock?];
type DiffMatchPatchMutation = ['patch', 'diffMatchPatch', Id, CompactPath, [string], RevisionLock?];
type CompactPatchMutation = UnsetMutation | InsertMutation | UpsertMutation | InsertIfMissingMutation | TruncateMutation | IncMutation | DecMutation | SetMutation | SetIfMissingMutation | DiffMatchPatchMutation | AssignMutation | UnassignMutation | ReplaceMutation | RemoveMutation;
type CompactMutation<Doc> = DeleteMutation$1 | CreateMutation$1<Doc> | CreateIfNotExistsMutation$1<Doc> | CreateOrReplaceMutation$1<Doc> | CompactPatchMutation;
declare function decode<Doc extends SanityDocumentBase>(mutations: CompactMutation<Doc>[]): Mutation[];
declare function encode$1<Doc extends SanityDocumentBase>(mutations: Mutation[]): CompactMutation<Doc>[];
declare namespace index_d_exports {
export { AssignMutation, CompactMutation, CompactPatchMutation, CompactPath, CreateIfNotExistsMutation$1 as CreateIfNotExistsMutation, CreateMutation$1 as CreateMutation, CreateOrReplaceMutation$1 as CreateOrReplaceMutation, DecMutation, DeleteMutation$1 as DeleteMutation, DiffMatchPatchMutation, Id, IncMutation, InsertIfMissingMutation, InsertMutation, ItemRef$1 as ItemRef, RemoveMutation, ReplaceMutation, RevisionLock, SetIfMissingMutation, SetMutation, TruncateMutation, UnassignMutation, UnsetMutation, UpsertMutation, decode, encode$1 as encode };
}
/**
* @deprecated
*/
type FormPatchPathKeyedSegment = {
_key: string;
};
/**
* @deprecated
*/
type FormPatchPathIndexTuple = [number | '', number | ''];
/**
* @deprecated
*/
type FormPatchPathSegment = string | number | FormPatchPathKeyedSegment | FormPatchPathIndexTuple;
/**
* @deprecated
*/
type FormPatchPath = FormPatchPathSegment[];
/**
* A variant of the FormPath type that never contains index tupes
*/
type CompatPath = Exclude<ElementType<FormPatchPath>, FormPatchPathIndexTuple>[];
/**
*
* @internal
* @deprecated
*/
type FormPatchJSONValue = number | string | boolean | {
[key: string]: FormPatchJSONValue;
} | FormPatchJSONValue[];
/**
*
* @internal
* @deprecated
*/
type FormPatchOrigin = 'remote' | 'local' | 'internal';
/**
*
* @internal
* @deprecated
*/
interface FormSetPatch {
path: FormPatchPath;
type: 'set';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormIncPatch {
path: FormPatchPath;
type: 'inc';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormDecPatch {
path: FormPatchPath;
type: 'dec';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormSetIfMissingPatch {
path: FormPatchPath;
type: 'setIfMissing';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormUnsetPatch {
path: FormPatchPath;
type: 'unset';
}
/**
*
* @internal
* @deprecated
*/
type FormInsertPatchPosition = 'before' | 'after';
/**
*
* @internal
* @deprecated
*/
interface FormInsertPatch {
path: FormPatchPath;
type: 'insert';
position: FormInsertPatchPosition;
items: FormPatchJSONValue[];
}
/**
*
* @internal
* @deprecated
*/
interface FormDiffMatchPatch {
path: FormPatchPath;
type: 'diffMatchPatch';
value: string;
}
/**
*
* @internal
* @deprecated
*/
type FormPatchLike = FormSetPatch | FormSetIfMissingPatch | FormUnsetPatch | FormInsertPatch | FormDiffMatchPatch;
/**
* Convert a Sanity form patch (ie emitted from an input component) to a {@link NodePatch}
* Note the lack of encodeMutation here. Sanity forms never emit *mutations*, only patches
* @param patches - Array of {@link FormPatchLike}
* @internal
*/
declare function encodePatches(patches: FormPatchLike[]): NodePatch[];
declare namespace index_d_exports$1 {
export { CompatPath, FormDecPatch, FormDiffMatchPatch, FormIncPatch, FormInsertPatch, FormInsertPatchPosition, FormPatchJSONValue, FormPatchLike, FormPatchOrigin, FormPatchPath, FormPatchPathIndexTuple, FormPatchPathKeyedSegment, FormPatchPathSegment, FormSetIfMissingPatch, FormSetPatch, FormUnsetPatch, encodePatches };
}
declare namespace compact_d_exports {
export { ItemRef, format };
}
type ItemRef = string | number;
declare function format<Doc extends SanityDocumentBase>(mutations: Mutation[]): string;
declare function autoKeys<Item>(generateKey: (item: Item) => string): {
insert: <Pos extends RelativePosition, Ref extends Index | KeyedPathElement>(position: Pos, referenceItem: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], Pos, Ref>;
upsert: <Pos extends RelativePosition, ReferenceItem extends KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => UpsertOp<Arrify<Item & {
_key: string;
}>, Pos, ReferenceItem>;
replace: <Pos extends RelativePosition, ReferenceItem extends Index | KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => ReplaceOp<(Item & {
_key: string;
})[], ReferenceItem>;
insertBefore: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", Ref>;
prepend: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", 0>;
insertAfter: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", Ref>;
append: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", -1>;
};
declare function create<Doc extends Optional<SanityDocumentBase, '_id'>>(document: Doc): CreateMutation<Doc>;
declare function patch<P extends NodePatchList | NodePatch>(id: string, patches: P, options?: PatchOptions): PatchMutation<NormalizeReadOnlyArray<Tuplify<P>>>;
declare function at<const P extends Path, O extends Operation>(path: P, operation: O): NodePatch<NormalizeReadOnlyArray<P>, O>;
declare function at<const P extends string, O extends Operation>(path: P, operation: O): NodePatch<SafePath<P>, O>;
declare function createIfNotExists<Doc extends SanityDocumentBase>(document: Doc): CreateIfNotExistsMutation<Doc>;
declare function createOrReplace<Doc extends SanityDocumentBase>(document: Doc): CreateOrReplaceMutation<Doc>;
declare function delete_(id: string): DeleteMutation;
declare const del: typeof delete_;
declare const destroy: typeof delete_;
type Arrify<T> = (T extends (infer E)[] ? E : T)[];
declare const set: <const T>(value: T) => SetOp<T>;
declare const assign: <const T extends { [K in string]: unknown }>(value: T) => AssignOp<T>;
declare const unassign: <const K extends readonly string[]>(keys: K) => UnassignOp<K>;
declare const setIfMissing: <const T>(value: T) => SetIfMissingOp<T>;
declare const unset: () => UnsetOp;
declare const inc: <const N extends number = 1>(amount?: N) => IncOp<N>;
declare const dec: <const N extends number = 1>(amount?: N) => DecOp<N>;
declare const diffMatchPatch: (value: string) => DiffMatchPatchOp;
declare function insert<const Items extends AnyArray<unknown>, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, position: Pos, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, Pos, ReferenceItem>;
declare function append<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "after", -1>;
declare function prepend<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "before", 0>;
declare function insertBefore<const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, "before", ReferenceItem>;
declare const insertAfter: <const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem) => InsertOp<NormalizeReadOnlyArray<Items>, "after", ReferenceItem>;
declare function truncate(startIndex: number, endIndex?: number): TruncateOp;
declare function replace<Items extends any[], ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, referenceItem: ReferenceItem): ReplaceOp<Items, ReferenceItem>;
declare function remove<ReferenceItem extends Index | KeyedPathElement>(referenceItem: ReferenceItem): RemoveOp<ReferenceItem>;
declare function upsert<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): UpsertOp<Arrify<Item>, Pos, ReferenceItem>;
declare function insertIfMissing<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): InsertIfMissingOp<Arrify<Item>, Pos, ReferenceItem>;
declare function encode(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodeAll(mutations: Mutation[]): SanityMutation[];
declare function encodeTransaction(transaction: Transaction): {
transactionId: string | undefined;
mutations: SanityMutation[];
};
declare function encodeMutation(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodePatch(patch: NodePatch): {
unset: string[];
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
diffMatchPatch: {
[x: string]: string;
};
unset?: undefined;
insert?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
inc: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
dec?: undefined;
set?: undefined;
} | {
dec: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
set?: undefined;
} | {
[x: string]: {
[x: string]: unknown;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
unset: string[];
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
set: {
[k: string]: never;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
} | {
insert: {
replace: string;
items: AnyArray;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
};
declare namespace index_d_exports$2 {
export { Insert, InsertAfter, InsertBefore, InsertReplace, Mutation, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, decode$1 as decode, decodeAll, encode, encodeAll, encodeMutation, encodePatch, encodeTransaction };
}
export { type AnyArray, AnyEmptyArray, AnyOp, type ArrayElement, ArrayOp, type Arrify, AssignOp, ByIndex, index_d_exports as CompactEncoder, compact_d_exports as CompactFormatter, Concat, ConcatInner, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, ElementType, Err, FindBy, FindInArray, index_d_exports$1 as FormCompatEncoder, IdentifiedSanityDocument, IncOp, Index, InsertIfMissingOp, InsertOp, KeyedPathElement, Merge, MergeInner, type Mutation, NodePatch, NodePatchList, type NormalizeReadOnlyArray, NumberOp, ObjectOp, Ok, OnlyDigits, Operation, type Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, RelativePosition, RemoveOp, ReplaceOp, Result, SafePath, type SanityDocumentBase, index_d_exports$2 as SanityEncoder, SetIfMissingOp, SetOp, Split, SplitAll, StringOp, StringToPath, StripError, ToArray, ToNumber, Transaction, Trim, TrimLeft, TrimRight, TruncateOp, Try, type Tuplify, UnassignOp, UnsetOp, Unwrap, UpsertOp, append, assign, at, autoKeys, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert };
//# sourceMappingURL=index.d.cts.map
import "./_chunks-dts/types3.cjs";
export { AnyArray, AnyEmptyArray, AnyOp, ArrayElement, ArrayOp, Arrify, AssignOp, ByIndex, index_d_exports as CompactEncoder, compact_d_exports as CompactFormatter, Concat, ConcatInner, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, ElementType, Err, FindBy, FindInArray, index_d_exports$1 as FormCompatEncoder, IdentifiedSanityDocument, IncOp, Index, InsertIfMissingOp, InsertOp, KeyedPathElement, Merge, MergeInner, Mutation, NodePatch, NodePatchList, NormalizeReadOnlyArray, NumberOp, ObjectOp, Ok, OnlyDigits, Operation, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, RelativePosition, RemoveOp, ReplaceOp, Result, SafePath, SanityDocumentBase, index_d_exports$2 as SanityEncoder, SetIfMissingOp, SetOp, Split, SplitAll, StringOp, StringToPath, StripError, ToArray, ToNumber, Transaction, Trim, TrimLeft, TrimRight, TruncateOp, Try, Tuplify, UnassignOp, UnsetOp, Unwrap, UpsertOp, append, assign, at, autoKeys, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert };

@@ -0,320 +1,5 @@

import { Arrify, append, assign, at, autoKeys, compact_d_exports, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, index_d_exports as index_d_exports$2, index_d_exports$1, index_d_exports$2 as index_d_exports, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert } from "./_chunks-dts/index.js";
import { AnyArray, AnyEmptyArray, ArrayElement, ByIndex, Concat, ConcatInner, Digit, ElementType, Err, FindBy, FindInArray, Index, KeyedPathElement, Merge, MergeInner, NormalizeReadOnlyArray, Ok, OnlyDigits, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, Path, PathElement, PropertyName, Result, SafePath, Split, SplitAll, StringToPath, StripError, ToArray, ToNumber, Trim, TrimLeft, TrimRight, Try, Tuplify, Unwrap } from "./_chunks-dts/types.js";
import { AnyOp, ArrayOp, AssignOp, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, IdentifiedSanityDocument, IncOp, InsertIfMissingOp, InsertOp, Mutation, NodePatch, NodePatchList, NumberOp, ObjectOp, Operation, PatchMutation, PatchOptions, PrimitiveOp, RelativePosition, RemoveOp, ReplaceOp, SanityDocumentBase, SetIfMissingOp, SetOp, StringOp, Transaction, TruncateOp, UnassignOp, UnsetOp, UpsertOp } from "./_chunks-dts/types2.js";
import { Insert, InsertAfter, InsertBefore, InsertReplace, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch } from "./_chunks-dts/types3.js";
declare function decodeAll<Doc extends SanityDocumentBase>(sanityMutations: SanityMutation<Doc>[]): Mutation[];
declare function decode$1<Doc extends SanityDocumentBase>(encodedMutation: SanityMutation<Doc>): Mutation;
type Id = string;
type RevisionLock = string;
type CompactPath = string;
type ItemRef$1 = string | number;
type DeleteMutation$1 = ['delete', Id];
type CreateMutation$1<Doc> = ['create', Doc];
type CreateIfNotExistsMutation$1<Doc> = ['createIfNotExists', Doc];
type CreateOrReplaceMutation$1<Doc> = ['createOrReplace', Doc];
type UnsetMutation = ['patch', 'unset', Id, CompactPath, [], RevisionLock?];
type InsertMutation = ['patch', 'insert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type UpsertMutation = ['patch', 'upsert', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type InsertIfMissingMutation = ['patch', 'insertIfMissing', Id, CompactPath, [RelativePosition, ItemRef$1, AnyArray], RevisionLock?];
type TruncateMutation = ['patch', 'truncate', Id, CompactPath, [startIndex: number, endIndex: number | undefined], RevisionLock?];
type IncMutation = ['patch', 'inc', Id, CompactPath, [number], RevisionLock?];
type DecMutation = ['patch', 'dec', Id, CompactPath, [number], RevisionLock?];
type AssignMutation = ['patch', 'assign', Id, CompactPath, [object], RevisionLock?];
type UnassignMutation = ['patch', 'assign', Id, CompactPath, [string[]], RevisionLock?];
type ReplaceMutation = ['patch', 'replace', Id, CompactPath, [ItemRef$1, AnyArray], RevisionLock?];
type RemoveMutation = ['patch', 'remove', Id, CompactPath, [ItemRef$1], RevisionLock?];
type SetMutation = ['patch', 'set', Id, CompactPath, any, RevisionLock?];
type SetIfMissingMutation = ['patch', 'setIfMissing', Id, CompactPath, [unknown], RevisionLock?];
type DiffMatchPatchMutation = ['patch', 'diffMatchPatch', Id, CompactPath, [string], RevisionLock?];
type CompactPatchMutation = UnsetMutation | InsertMutation | UpsertMutation | InsertIfMissingMutation | TruncateMutation | IncMutation | DecMutation | SetMutation | SetIfMissingMutation | DiffMatchPatchMutation | AssignMutation | UnassignMutation | ReplaceMutation | RemoveMutation;
type CompactMutation<Doc> = DeleteMutation$1 | CreateMutation$1<Doc> | CreateIfNotExistsMutation$1<Doc> | CreateOrReplaceMutation$1<Doc> | CompactPatchMutation;
declare function decode<Doc extends SanityDocumentBase>(mutations: CompactMutation<Doc>[]): Mutation[];
declare function encode$1<Doc extends SanityDocumentBase>(mutations: Mutation[]): CompactMutation<Doc>[];
declare namespace index_d_exports {
export { AssignMutation, CompactMutation, CompactPatchMutation, CompactPath, CreateIfNotExistsMutation$1 as CreateIfNotExistsMutation, CreateMutation$1 as CreateMutation, CreateOrReplaceMutation$1 as CreateOrReplaceMutation, DecMutation, DeleteMutation$1 as DeleteMutation, DiffMatchPatchMutation, Id, IncMutation, InsertIfMissingMutation, InsertMutation, ItemRef$1 as ItemRef, RemoveMutation, ReplaceMutation, RevisionLock, SetIfMissingMutation, SetMutation, TruncateMutation, UnassignMutation, UnsetMutation, UpsertMutation, decode, encode$1 as encode };
}
/**
* @deprecated
*/
type FormPatchPathKeyedSegment = {
_key: string;
};
/**
* @deprecated
*/
type FormPatchPathIndexTuple = [number | '', number | ''];
/**
* @deprecated
*/
type FormPatchPathSegment = string | number | FormPatchPathKeyedSegment | FormPatchPathIndexTuple;
/**
* @deprecated
*/
type FormPatchPath = FormPatchPathSegment[];
/**
* A variant of the FormPath type that never contains index tupes
*/
type CompatPath = Exclude<ElementType<FormPatchPath>, FormPatchPathIndexTuple>[];
/**
*
* @internal
* @deprecated
*/
type FormPatchJSONValue = number | string | boolean | {
[key: string]: FormPatchJSONValue;
} | FormPatchJSONValue[];
/**
*
* @internal
* @deprecated
*/
type FormPatchOrigin = 'remote' | 'local' | 'internal';
/**
*
* @internal
* @deprecated
*/
interface FormSetPatch {
path: FormPatchPath;
type: 'set';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormIncPatch {
path: FormPatchPath;
type: 'inc';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormDecPatch {
path: FormPatchPath;
type: 'dec';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormSetIfMissingPatch {
path: FormPatchPath;
type: 'setIfMissing';
value: FormPatchJSONValue;
}
/**
*
* @internal
* @deprecated
*/
interface FormUnsetPatch {
path: FormPatchPath;
type: 'unset';
}
/**
*
* @internal
* @deprecated
*/
type FormInsertPatchPosition = 'before' | 'after';
/**
*
* @internal
* @deprecated
*/
interface FormInsertPatch {
path: FormPatchPath;
type: 'insert';
position: FormInsertPatchPosition;
items: FormPatchJSONValue[];
}
/**
*
* @internal
* @deprecated
*/
interface FormDiffMatchPatch {
path: FormPatchPath;
type: 'diffMatchPatch';
value: string;
}
/**
*
* @internal
* @deprecated
*/
type FormPatchLike = FormSetPatch | FormSetIfMissingPatch | FormUnsetPatch | FormInsertPatch | FormDiffMatchPatch;
/**
* Convert a Sanity form patch (ie emitted from an input component) to a {@link NodePatch}
* Note the lack of encodeMutation here. Sanity forms never emit *mutations*, only patches
* @param patches - Array of {@link FormPatchLike}
* @internal
*/
declare function encodePatches(patches: FormPatchLike[]): NodePatch[];
declare namespace index_d_exports$1 {
export { CompatPath, FormDecPatch, FormDiffMatchPatch, FormIncPatch, FormInsertPatch, FormInsertPatchPosition, FormPatchJSONValue, FormPatchLike, FormPatchOrigin, FormPatchPath, FormPatchPathIndexTuple, FormPatchPathKeyedSegment, FormPatchPathSegment, FormSetIfMissingPatch, FormSetPatch, FormUnsetPatch, encodePatches };
}
declare namespace compact_d_exports {
export { ItemRef, format };
}
type ItemRef = string | number;
declare function format<Doc extends SanityDocumentBase>(mutations: Mutation[]): string;
declare function autoKeys<Item>(generateKey: (item: Item) => string): {
insert: <Pos extends RelativePosition, Ref extends Index | KeyedPathElement>(position: Pos, referenceItem: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], Pos, Ref>;
upsert: <Pos extends RelativePosition, ReferenceItem extends KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => UpsertOp<Arrify<Item & {
_key: string;
}>, Pos, ReferenceItem>;
replace: <Pos extends RelativePosition, ReferenceItem extends Index | KeyedPathElement>(items: Item[], position: Pos, referenceItem: ReferenceItem) => ReplaceOp<(Item & {
_key: string;
})[], ReferenceItem>;
insertBefore: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", Ref>;
prepend: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "before", 0>;
insertAfter: <Ref extends Index | KeyedPathElement>(ref: Ref, items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", Ref>;
append: (items: Item[]) => InsertOp<(Item & {
_key: string;
})[], "after", -1>;
};
declare function create<Doc extends Optional<SanityDocumentBase, '_id'>>(document: Doc): CreateMutation<Doc>;
declare function patch<P extends NodePatchList | NodePatch>(id: string, patches: P, options?: PatchOptions): PatchMutation<NormalizeReadOnlyArray<Tuplify<P>>>;
declare function at<const P extends Path, O extends Operation>(path: P, operation: O): NodePatch<NormalizeReadOnlyArray<P>, O>;
declare function at<const P extends string, O extends Operation>(path: P, operation: O): NodePatch<SafePath<P>, O>;
declare function createIfNotExists<Doc extends SanityDocumentBase>(document: Doc): CreateIfNotExistsMutation<Doc>;
declare function createOrReplace<Doc extends SanityDocumentBase>(document: Doc): CreateOrReplaceMutation<Doc>;
declare function delete_(id: string): DeleteMutation;
declare const del: typeof delete_;
declare const destroy: typeof delete_;
type Arrify<T> = (T extends (infer E)[] ? E : T)[];
declare const set: <const T>(value: T) => SetOp<T>;
declare const assign: <const T extends { [K in string]: unknown }>(value: T) => AssignOp<T>;
declare const unassign: <const K extends readonly string[]>(keys: K) => UnassignOp<K>;
declare const setIfMissing: <const T>(value: T) => SetIfMissingOp<T>;
declare const unset: () => UnsetOp;
declare const inc: <const N extends number = 1>(amount?: N) => IncOp<N>;
declare const dec: <const N extends number = 1>(amount?: N) => DecOp<N>;
declare const diffMatchPatch: (value: string) => DiffMatchPatchOp;
declare function insert<const Items extends AnyArray<unknown>, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, position: Pos, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, Pos, ReferenceItem>;
declare function append<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "after", -1>;
declare function prepend<const Items extends AnyArray<unknown>>(items: Items | ArrayElement<Items>): InsertOp<NormalizeReadOnlyArray<Items>, "before", 0>;
declare function insertBefore<const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem): InsertOp<NormalizeReadOnlyArray<Items>, "before", ReferenceItem>;
declare const insertAfter: <const Items extends AnyArray<unknown>, const ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, indexOrReferenceItem: ReferenceItem) => InsertOp<NormalizeReadOnlyArray<Items>, "after", ReferenceItem>;
declare function truncate(startIndex: number, endIndex?: number): TruncateOp;
declare function replace<Items extends any[], ReferenceItem extends Index | KeyedPathElement>(items: Items | ArrayElement<Items>, referenceItem: ReferenceItem): ReplaceOp<Items, ReferenceItem>;
declare function remove<ReferenceItem extends Index | KeyedPathElement>(referenceItem: ReferenceItem): RemoveOp<ReferenceItem>;
declare function upsert<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): UpsertOp<Arrify<Item>, Pos, ReferenceItem>;
declare function insertIfMissing<const Item extends {
_key: string;
}, const Pos extends RelativePosition, const ReferenceItem extends Index | KeyedPathElement>(items: Item | Item[], position: Pos, referenceItem: ReferenceItem): InsertIfMissingOp<Arrify<Item>, Pos, ReferenceItem>;
declare function encode(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodeAll(mutations: Mutation[]): SanityMutation[];
declare function encodeTransaction(transaction: Transaction): {
transactionId: string | undefined;
mutations: SanityMutation[];
};
declare function encodeMutation(mutation: Mutation): SanityMutation[] | SanityMutation;
declare function encodePatch(patch: NodePatch): {
unset: string[];
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
diffMatchPatch: {
[x: string]: string;
};
unset?: undefined;
insert?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
inc: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
dec?: undefined;
set?: undefined;
} | {
dec: {
[x: string]: number;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
set?: undefined;
} | {
[x: string]: {
[x: string]: unknown;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
unset: string[];
insert: {
[x: string]: string | readonly any[];
items: AnyArray;
replace?: undefined;
};
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
} | {
set: {
[k: string]: never;
};
unset?: undefined;
insert?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
} | {
insert: {
replace: string;
items: AnyArray;
};
unset?: undefined;
diffMatchPatch?: undefined;
inc?: undefined;
dec?: undefined;
set?: undefined;
};
declare namespace index_d_exports$2 {
export { Insert, InsertAfter, InsertBefore, InsertReplace, Mutation, PatchMutationOperation, SanityCreateIfNotExistsMutation, SanityCreateMutation, SanityCreateOrReplaceMutation, SanityDecPatch, SanityDeleteMutation, SanityDiffMatchPatch, SanityDocumentBase, SanityIncPatch, SanityInsertPatch, SanityMutation, SanityPatch, SanitySetIfMissingPatch, SanitySetPatch, SanityUnsetPatch, decode$1 as decode, decodeAll, encode, encodeAll, encodeMutation, encodePatch, encodeTransaction };
}
export { type AnyArray, AnyEmptyArray, AnyOp, type ArrayElement, ArrayOp, type Arrify, AssignOp, ByIndex, index_d_exports as CompactEncoder, compact_d_exports as CompactFormatter, Concat, ConcatInner, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, ElementType, Err, FindBy, FindInArray, index_d_exports$1 as FormCompatEncoder, IdentifiedSanityDocument, IncOp, Index, InsertIfMissingOp, InsertOp, KeyedPathElement, Merge, MergeInner, type Mutation, NodePatch, NodePatchList, type NormalizeReadOnlyArray, NumberOp, ObjectOp, Ok, OnlyDigits, Operation, type Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, RelativePosition, RemoveOp, ReplaceOp, Result, SafePath, type SanityDocumentBase, index_d_exports$2 as SanityEncoder, SetIfMissingOp, SetOp, Split, SplitAll, StringOp, StringToPath, StripError, ToArray, ToNumber, Transaction, Trim, TrimLeft, TrimRight, TruncateOp, Try, type Tuplify, UnassignOp, UnsetOp, Unwrap, UpsertOp, append, assign, at, autoKeys, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert };
//# sourceMappingURL=index.d.ts.map
import "./_chunks-dts/types3.js";
export { AnyArray, AnyEmptyArray, AnyOp, ArrayElement, ArrayOp, Arrify, AssignOp, ByIndex, index_d_exports as CompactEncoder, compact_d_exports as CompactFormatter, Concat, ConcatInner, CreateIfNotExistsMutation, CreateMutation, CreateOrReplaceMutation, DecOp, DeleteMutation, DiffMatchPatchOp, Digit, ElementType, Err, FindBy, FindInArray, index_d_exports$1 as FormCompatEncoder, IdentifiedSanityDocument, IncOp, Index, InsertIfMissingOp, InsertOp, KeyedPathElement, Merge, MergeInner, Mutation, NodePatch, NodePatchList, NormalizeReadOnlyArray, NumberOp, ObjectOp, Ok, OnlyDigits, Operation, Optional, ParseAllProps, ParseError, ParseExpressions, ParseInnerExpression, ParseKVPair, ParseNumber, ParseObject, ParseProperty, ParseValue, PatchMutation, PatchOptions, Path, PathElement, PrimitiveOp, PropertyName, RelativePosition, RemoveOp, ReplaceOp, Result, SafePath, SanityDocumentBase, index_d_exports$2 as SanityEncoder, SetIfMissingOp, SetOp, Split, SplitAll, StringOp, StringToPath, StripError, ToArray, ToNumber, Transaction, Trim, TrimLeft, TrimRight, TruncateOp, Try, Tuplify, UnassignOp, UnsetOp, Unwrap, UpsertOp, append, assign, at, autoKeys, create, createIfNotExists, createOrReplace, dec, del, delete_, destroy, diffMatchPatch, inc, insert, insertAfter, insertBefore, insertIfMissing, patch, prepend, remove, replace, set, setIfMissing, truncate, unassign, unset, upsert };
{
"name": "@sanity/mutate",
"version": "0.15.0",
"version": "0.15.1-canary.0",
"description": "Experimental toolkit for working with Sanity mutations in JavaScript & TypeScript",

@@ -35,2 +35,14 @@ "keywords": [

},
"./_unstable_apply": {
"source": "./src/_unstable_apply.ts",
"import": "./dist/_unstable_apply.js",
"require": "./dist/_unstable_apply.cjs",
"default": "./dist/_unstable_apply.js"
},
"./_unstable_machine": {
"source": "./src/_unstable_machine.ts",
"import": "./dist/_unstable_machine.js",
"require": "./dist/_unstable_machine.cjs",
"default": "./dist/_unstable_machine.js"
},
"./_unstable_store": {

@@ -42,8 +54,2 @@ "source": "./src/_unstable_store.ts",

},
"./_unstable_apply": {
"source": "./src/_unstable_apply.ts",
"import": "./dist/_unstable_apply.js",
"require": "./dist/_unstable_apply.cjs",
"default": "./dist/_unstable_apply.js"
},
"./package.json": "./package.json"

@@ -62,2 +68,5 @@ },

],
"_unstable_machine": [
"./dist/_unstable_machine.d.ts"
],
"_unstable_store": [

@@ -107,2 +116,10 @@ "./dist/_unstable_store.d.ts"

},
"peerDependencies": {
"xstate": "^5.18.2"
},
"peerDependenciesMeta": {
"xstate": {
"optional": true
}
},
"engines": {

@@ -128,2 +145,3 @@ "node": ">=18"

"coverage": "vitest run --coverage",
"example:visual-editing": "pnpm --filter example-visual-editing run dev",
"example:web": "pnpm --filter example-web run dev",

@@ -130,0 +148,0 @@ "check": "run-s typecheck typecheck:examples pkg:build test",

{"version":3,"file":"index.d.cts","names":[],"sources":["../src/encoders/sanity/decode.ts","../src/encoders/compact/types.ts","../src/encoders/compact/decode.ts","../src/encoders/compact/encode.ts","../src/encoders/compact/index.ts","../src/encoders/form-compat/form-patch-types.ts","../src/encoders/form-compat/encode.ts","../src/encoders/form-compat/index.ts","../src/formatters/compact.ts","../src/mutations/autoKeys.ts","../src/mutations/creators.ts","../src/utils/arrify.ts","../src/mutations/operations/creators.ts","../src/encoders/sanity/encode.ts","../src/encoders/sanity/index.ts"],"sourcesContent":[],"mappings":";;;iBAiGgB,sBAAsB,qCACnB,eAAe,SAAM;iBAKxB,qBAAmB,qCAChB,eAAe,OAAI;KCrG1B,EAAA;KACA,YAAA;KACA,WAAA;KACA,SAAA;KAEA,gBAAA,cAA4B;KAC5B,mCAAiC;KACjC,yDAAuD;KACvD,qDAAmD;KAEnD,aAAA,aDoFI,OAAA,ECjFd,EDiFuB,EChFvB,WDgFoC,MC9EpC,YD+EsC,CAAA,CAAA;AAKxB,KClFJ,cAAA,GDkFU,CAAA,OAAA,UAAa,EC/EjC,IACA,WD+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;KACA,CAAA,EAAA,SAAA;KACC,CAAA,EAAA,SAAA;;OAA2B,EAAA,MAAA,EAAA;QAC5B,EAAA;IAAY,CAAA,CAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA,GAAA,EAAA;IAGF,KAAA,UAAgB;IAAA,OAAA,CAAA,EAAA,SAAA;;gBAI1B,CAAA,EAAA,SAAA;KAEA,CAAA,EAAA,SAAA;EAAY,GAAA,CAAA,EAAA,SAAA;EAGF,GAAA,CAAA,EAAA,SAAW;CAAA,GAAA;KAGrB,EAAA;IACA,CAAA,CAAA,EAAA,MAAA,CAAA,EAAA,KAAA;;EAEY,KAAA,CAAA,EAAA,SAAA;EAEF,MAAA,CAAA,EAAA,SAAW;EAAA,cAAA,CAAA,EAAA,SAAA;KAGrB,CAAA,EAAA,SAAA;KACA,CAAA,EAAA,SAAA;;EAEY,MAAA,EAAA;IAEF,OAAA,EAAA,MAAc;IAAA,KAAA,UAAA;;OAIxB,CAAA,EAAA,SAAA;gBAEA,CAAA,EAAA,SAAA;EAAY,GAAA,CAAA,EAAA,SAAA;EAEF,GAAA,CAAA,EAAA,SAAA;EAAgB,GAAA,CAAA,EAAA,SAAA"}
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/encoders/sanity/decode.ts","../src/encoders/compact/types.ts","../src/encoders/compact/decode.ts","../src/encoders/compact/encode.ts","../src/encoders/compact/index.ts","../src/encoders/form-compat/form-patch-types.ts","../src/encoders/form-compat/encode.ts","../src/encoders/form-compat/index.ts","../src/formatters/compact.ts","../src/mutations/autoKeys.ts","../src/mutations/creators.ts","../src/utils/arrify.ts","../src/mutations/operations/creators.ts","../src/encoders/sanity/encode.ts","../src/encoders/sanity/index.ts"],"sourcesContent":[],"mappings":";;;iBAiGgB,sBAAsB,qCACnB,eAAe,SAAM;iBAKxB,qBAAmB,qCAChB,eAAe,OAAI;KCrG1B,EAAA;KACA,YAAA;KACA,WAAA;KACA,SAAA;KAEA,gBAAA,cAA4B;KAC5B,mC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