@fragmentsx/client-core 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/index.cjs.js +1500 -560
  2. package/dist/index.es.js +1501 -561
  3. package/package.json +8 -5
  4. package/dist/fragmentsClient.d.ts +0 -7
  5. package/dist/fragmentsClient.d.ts.map +0 -1
  6. package/dist/index.d.ts +0 -2
  7. package/dist/index.d.ts.map +0 -1
  8. package/dist/plugins/fetch/beacon.d.ts +0 -4
  9. package/dist/plugins/fetch/beacon.d.ts.map +0 -1
  10. package/dist/plugins/fetch/emptyFragment.d.ts +0 -50
  11. package/dist/plugins/fetch/emptyFragment.d.ts.map +0 -1
  12. package/dist/plugins/fetch/fetcher.d.ts +0 -6
  13. package/dist/plugins/fetch/fetcher.d.ts.map +0 -1
  14. package/dist/plugins/fetch/index.d.ts +0 -3
  15. package/dist/plugins/fetch/index.d.ts.map +0 -1
  16. package/dist/plugins/fetch/queries/FragmentQuery.d.ts +0 -2
  17. package/dist/plugins/fetch/queries/FragmentQuery.d.ts.map +0 -1
  18. package/dist/plugins/fetch/queries/LandingQuery.d.ts +0 -2
  19. package/dist/plugins/fetch/queries/LandingQuery.d.ts.map +0 -1
  20. package/dist/plugins/fragments/index.d.ts +0 -3
  21. package/dist/plugins/fragments/index.d.ts.map +0 -1
  22. package/dist/plugins/metrics/index.d.ts +0 -3
  23. package/dist/plugins/metrics/index.d.ts.map +0 -1
  24. package/dist/plugins/metrics/queries/addClientMetric.d.ts +0 -2
  25. package/dist/plugins/metrics/queries/addClientMetric.d.ts.map +0 -1
  26. package/dist/plugins/styleSheet/buildCssBlock.d.ts +0 -2
  27. package/dist/plugins/styleSheet/buildCssBlock.d.ts.map +0 -1
  28. package/dist/plugins/styleSheet/compareRules.d.ts +0 -4
  29. package/dist/plugins/styleSheet/compareRules.d.ts.map +0 -1
  30. package/dist/plugins/styleSheet/findGroups.d.ts +0 -8
  31. package/dist/plugins/styleSheet/findGroups.d.ts.map +0 -1
  32. package/dist/plugins/styleSheet/getAllChildren.d.ts +0 -3
  33. package/dist/plugins/styleSheet/getAllChildren.d.ts.map +0 -1
  34. package/dist/plugins/styleSheet/index.d.ts +0 -3
  35. package/dist/plugins/styleSheet/index.d.ts.map +0 -1
  36. package/dist/plugins/styleSheet/makeCss.d.ts +0 -6
  37. package/dist/plugins/styleSheet/makeCss.d.ts.map +0 -1
  38. package/dist/plugins/styleSheet/toCSS.d.ts +0 -2
  39. package/dist/plugins/styleSheet/toCSS.d.ts.map +0 -1
package/dist/index.cjs.js CHANGED
@@ -1,421 +1,636 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- var t = (e) => !e && e == null, s = (e) => !t(e), y = (e) => typeof e == "object" && !Array.isArray(e) && s(e), a = (e) => typeof Node == "object" ? e instanceof Node : e && typeof e == "object" && typeof e.nodeType == "number" && typeof e.nodeName == "string", p = (e) => typeof e == "string" || n(e), n = (e) => typeof e == "object" && typeof e._type == "string", r = (e) => typeof e == "string" && e.split(":").length >= 2, i = (e) => typeof e != "object" && typeof e != "function" || e === null, b = (e) => typeof e == "string" ? /<\/?[a-z][\s\S]*>/i.test(e) : false;
4
- var G = (t2) => r(t2), te = (t2) => p(t2), ne = (t2) => n(t2), S = (t2) => y(t2), re = (t2, s2) => {
5
- if (t2 === s2) return true;
6
- if (Array.isArray(t2) && Array.isArray(s2)) return t2.length === s2.length && t2.every((a2, h) => s2[h] === a2);
7
- if (!S(t2) || !S(s2)) return false;
8
- let p2 = Object.keys(t2), c = Object.keys(s2);
9
- if (p2.length !== c.length) return false;
10
- for (let a2 of p2) {
11
- if (!c.includes(a2)) return false;
12
- let h = t2[a2], l = s2[a2];
13
- if (i(h) && i(l) && h !== l) return false;
3
+ var r = (e) => !e && e == null, y = (e) => !r(e), a = (e) => typeof e == "object" && !Array.isArray(e) && y(e), f = (e) => typeof Node == "object" ? e instanceof Node : e && typeof e == "object" && typeof e.nodeType == "number" && typeof e.nodeName == "string", i = (e) => typeof e == "string" || t(e), t = (e) => typeof e == "object" && typeof e._type == "string", s = (e) => typeof e == "string" && e.split(":").length >= 2, l = (e) => typeof e != "object" && typeof e != "function" || e === null, g = (e) => typeof e == "string" ? /<\/?[a-z][\s\S]*>/i.test(e) : false, u = (e) => (n) => {
4
+ var _a;
5
+ if (!n) return false;
6
+ let o = null;
7
+ return s(n) && (o = (_a = n.split(":")) == null ? void 0 : _a[0]), t(n) && (o = n._type), o ? !e.includes(o) : false;
8
+ };
9
+ var isLinkKey = (input) => s(input);
10
+ var isGraphOrKey = (input) => i(input);
11
+ var isGraph = (input) => t(input);
12
+ var isObject$1 = (input) => a(input);
13
+ var shallowEqual = (a2, b) => {
14
+ if (a2 === b)
15
+ return true;
16
+ if (Array.isArray(a2) && Array.isArray(b)) {
17
+ return a2.length === b.length && a2.every((val, index2) => b[index2] === val);
18
+ }
19
+ if (!isObject$1(a2) || !isObject$1(b))
20
+ return false;
21
+ const keysA = Object.keys(a2);
22
+ const keysB = Object.keys(b);
23
+ if (keysA.length !== keysB.length)
24
+ return false;
25
+ for (const key of keysA) {
26
+ if (!keysB.includes(key))
27
+ return false;
28
+ const aValue = a2[key];
29
+ const bValue = b[key];
30
+ if (l(aValue) && l(bValue) && aValue !== bValue)
31
+ return false;
14
32
  }
15
33
  return true;
16
- }, W = (t2, s2) => {
17
- if (t2 === s2) return true;
18
- if (Array.isArray(t2) && Array.isArray(s2)) return t2.length === s2.length && t2.every((a2, h) => W(a2, s2[h]));
19
- if (!S(s2) || !S(t2)) return t2 === s2;
20
- let p2 = Object.keys(t2), c = Object.keys(s2);
21
- if (p2.length !== c.length) return false;
22
- for (let a2 of p2) if (!c.includes(a2) || !W(t2[a2], s2[a2])) return false;
34
+ };
35
+ var deepEqual = (a2, b) => {
36
+ if (a2 === b)
37
+ return true;
38
+ if (Array.isArray(a2) && Array.isArray(b)) {
39
+ return a2.length === b.length && a2.every((val, i2) => deepEqual(val, b[i2]));
40
+ }
41
+ if (!isObject$1(b) || !isObject$1(a2))
42
+ return a2 === b;
43
+ const keysA = Object.keys(a2);
44
+ const keysB = Object.keys(b);
45
+ if (keysA.length !== keysB.length)
46
+ return false;
47
+ for (const key of keysA) {
48
+ if (!keysB.includes(key))
49
+ return false;
50
+ if (!deepEqual(a2[key], b[key]))
51
+ return false;
52
+ }
23
53
  return true;
24
54
  };
25
- var z = (...t2) => Array.from(new Set(t2)), se = (...t2) => t2.filter((s2, p2, c) => r(s2) ? c.indexOf(s2) === p2 : true);
26
- var I = (t2) => t2 && t2.split(".").length > 1, Y = (t2, s2) => {
27
- if (!t2 || !s2) return false;
28
- if (typeof t2 != "string" || typeof s2 != "string") return null;
29
- let [p2, c] = t2.split(":"), [a2, h] = s2.split(":");
30
- return p2 !== a2 ? false : c.startsWith(h);
31
- }, ie = (t2) => G(t2) && I(t2) ? t2.split(".")[0] : t2;
32
- var oe = () => {
33
- let t2 = /* @__PURE__ */ new Map(), s2 = /* @__PURE__ */ new Map(), p2 = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), a2 = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Set([]), O = (n2, g) => {
55
+ var unique = (...values) => Array.from(new Set(values));
56
+ var uniqueLinks = (...values) => values.filter((item, index2, arr) => s(item) ? arr.indexOf(item) === index2 : true);
57
+ var isPartialKey = (key) => key && key.split(".").length > 1;
58
+ var isPartialGraph = (entity) => {
59
+ if (isObject$1(entity) && "_id" in entity && typeof entity._id === "string") {
60
+ return entity._id.includes(".");
61
+ }
62
+ return false;
63
+ };
64
+ var isPartOfGraph = (entityKey, graphKey) => {
65
+ if (!entityKey || !graphKey)
66
+ return false;
67
+ if (typeof entityKey !== "string" || typeof graphKey !== "string")
68
+ return null;
69
+ const [entityType, entityId] = entityKey.split(":");
70
+ const [graphType, graphId] = graphKey.split(":");
71
+ if (entityType !== graphType)
72
+ return false;
73
+ return entityId.startsWith(graphId);
74
+ };
75
+ var getGraphLink = (input) => {
76
+ if (isLinkKey(input)) {
77
+ if (isPartialKey(input)) {
78
+ return input.split(".")[0];
79
+ }
80
+ }
81
+ return input;
82
+ };
83
+ var createCache = () => {
84
+ const listeners = /* @__PURE__ */ new Map();
85
+ const types2 = /* @__PURE__ */ new Map();
86
+ const links = /* @__PURE__ */ new Map();
87
+ const parentRefs = /* @__PURE__ */ new Map();
88
+ const childrenRefs = /* @__PURE__ */ new Map();
89
+ const refCount = /* @__PURE__ */ new Map();
90
+ const gbLinks = /* @__PURE__ */ new Set([]);
91
+ const addRefs = (targetKey, depKey) => {
34
92
  var _a;
35
- c.set(n2, z(...c.get(n2) || [], g)), a2.set(g, z(...a2.get(g) ?? [], n2)), M(n2, ((_a = c.get(n2)) == null ? void 0 : _a.length) || 0);
36
- }, q = (n2, g) => {
93
+ parentRefs.set(targetKey, unique(...parentRefs.get(targetKey) || [], depKey));
94
+ childrenRefs.set(depKey, unique(...childrenRefs.get(depKey) ?? [], targetKey));
95
+ updateRefCountForLink(targetKey, ((_a = parentRefs.get(targetKey)) == null ? void 0 : _a.length) || 0);
96
+ };
97
+ const removeRefs = (targetKey, depKey) => {
37
98
  var _a;
38
- c.set(g, (c.get(g) || []).filter((k) => k !== n2)), a2.set(n2, (a2.get(n2) ?? []).filter((k) => k !== g)), M(g, ((_a = c.get(g)) == null ? void 0 : _a.length) || 0);
39
- }, T = (n2, g = []) => {
40
- let k = c.get(n2) || [];
41
- g.push(...k);
42
- let x = k.map((E) => T(E, g)).flat();
43
- return g.push(...x), Array.from(new Set(g).values());
44
- }, V = (n2) => {
45
- M(n2, 0), B();
46
- }, P = (n2) => n2 ? p2.get(n2) : null, R = (n2, g, k) => {
99
+ parentRefs.set(
100
+ depKey,
101
+ (parentRefs.get(depKey) || []).filter((key) => key !== targetKey)
102
+ );
103
+ childrenRefs.set(
104
+ targetKey,
105
+ (childrenRefs.get(targetKey) ?? []).filter((key) => key !== depKey)
106
+ );
107
+ updateRefCountForLink(depKey, ((_a = parentRefs.get(depKey)) == null ? void 0 : _a.length) || 0);
108
+ };
109
+ const getLinkedRefs = (key, stack = []) => {
110
+ const deps = parentRefs.get(key) || [];
111
+ stack.push(...deps);
112
+ const deepDeps = deps.map((ref) => getLinkedRefs(ref, stack)).flat();
113
+ stack.push(...deepDeps);
114
+ return Array.from(new Set(stack).values());
115
+ };
116
+ const invalidate = (key) => {
117
+ updateRefCountForLink(key, 0);
118
+ runGarbageCollector();
119
+ };
120
+ const readLink = (key) => {
121
+ if (key) {
122
+ return links.get(key);
123
+ }
124
+ return null;
125
+ };
126
+ const writeLink = (key, value, depKey) => {
47
127
  var _a;
48
- if (typeof n2 == "string") {
49
- p2.set(n2, g);
50
- let [x] = n2.split(":");
51
- I(n2) || (s2.has(x) ? (_a = s2.get(x)) == null ? void 0 : _a.add(n2) : s2.set(x, /* @__PURE__ */ new Set([n2])));
52
- }
53
- k && n2 && n2 !== k && O(n2, k);
54
- }, _ = (n2) => n2 ? p2.has(n2) : false, M = (n2, g) => {
55
- if (Array.isArray(n2)) n2.forEach((k, x) => M(k, x));
56
- else {
57
- let k = h.get(n2);
58
- h.set(n2, g), g ? !k && g && l.delete(n2) : l.add(n2);
59
- }
60
- }, $ = () => Array.from(p2.entries()), j = (n2) => h.get(n2) ?? 0, B = () => {
128
+ if (typeof key === "string") {
129
+ links.set(key, value);
130
+ const [type] = key.split(":");
131
+ if (!isPartialKey(key)) {
132
+ if (!types2.has(type)) {
133
+ types2.set(type, /* @__PURE__ */ new Set([key]));
134
+ } else {
135
+ (_a = types2.get(type)) == null ? void 0 : _a.add(key);
136
+ }
137
+ }
138
+ }
139
+ if (depKey && key && key !== depKey) {
140
+ addRefs(key, depKey);
141
+ }
142
+ };
143
+ const hasLink = (key) => {
144
+ if (key) {
145
+ return links.has(key);
146
+ }
147
+ return false;
148
+ };
149
+ const updateRefCountForLink = (link, count) => {
150
+ if (Array.isArray(link)) {
151
+ link.forEach((link2, index2) => updateRefCountForLink(link2, index2));
152
+ } else {
153
+ const prevCount = refCount.get(link);
154
+ refCount.set(link, count);
155
+ if (!count) {
156
+ gbLinks.add(link);
157
+ } else if (!prevCount && count) {
158
+ gbLinks.delete(link);
159
+ }
160
+ }
161
+ };
162
+ const getLinkEntries = () => Array.from(links.entries());
163
+ const getRefCount = (link) => refCount.get(link) ?? 0;
164
+ const runGarbageCollector = () => {
61
165
  var _a, _b;
62
- for (let n2 of l.keys()) {
63
- if (j(n2) > 0) continue;
64
- let k = p2.get(n2);
65
- l.delete(n2), p2.delete(n2), h.delete(n2);
66
- let x = c.get(n2) ?? [], E = a2.get(n2) ?? [];
67
- x.forEach((A) => {
166
+ for (const link of gbLinks.keys()) {
167
+ const count = getRefCount(link);
168
+ if (count > 0)
169
+ continue;
170
+ const currentValue = links.get(link);
171
+ gbLinks.delete(link);
172
+ links.delete(link);
173
+ refCount.delete(link);
174
+ const parents = parentRefs.get(link) ?? [];
175
+ const children = childrenRefs.get(link) ?? [];
176
+ parents.forEach((parentKey) => {
68
177
  var _a2, _b2;
69
- a2.set(A, ((_b2 = (_a2 = a2.get(A)) == null ? void 0 : _a2.filter) == null ? void 0 : _b2.call(_a2, (U) => U !== n2)) ?? []);
70
- }), E.forEach((A) => {
71
- M(A, j(A) - 1);
178
+ childrenRefs.set(parentKey, ((_b2 = (_a2 = childrenRefs.get(parentKey)) == null ? void 0 : _a2.filter) == null ? void 0 : _b2.call(_a2, (childLink) => childLink !== link)) ?? []);
179
+ });
180
+ children.forEach((childKey) => {
181
+ updateRefCountForLink(childKey, getRefCount(childKey) - 1);
72
182
  });
73
- let [C] = n2.split(":");
74
- I(n2) || ((_a = s2.get(C)) == null ? void 0 : _a.delete(n2), ((_b = s2.get(C)) == null ? void 0 : _b.size) || s2.delete(C)), c.delete(n2), (t2.get("onRemoveLink") ?? []).forEach((A) => A(n2, k ?? null));
183
+ const [type] = link.split(":");
184
+ if (!isPartialKey(link)) {
185
+ (_a = types2.get(type)) == null ? void 0 : _a.delete(link);
186
+ if (!((_b = types2.get(type)) == null ? void 0 : _b.size)) {
187
+ types2.delete(type);
188
+ }
189
+ }
190
+ parentRefs.delete(link);
191
+ (listeners.get("onRemoveLink") ?? []).forEach((listener) => listener(link, currentValue ?? null));
75
192
  }
76
193
  };
77
- return { readLink: P, writeLink: R, hasLink: _, getLinkEntries: $, parentRefs: c, childrenRefs: a2, addRefs: O, removeRefs: q, getChildren: (n2) => a2.get(n2), getParents: (n2) => c.get(n2), getLinkedRefs: T, invalidate: V, links: p2, types: s2, refCount: h, runGarbageCollector: B, onRemoveLink: (n2) => t2.set("onRemoveLink", [...(t2 == null ? void 0 : t2.get("onRemoveLink")) ?? [], n2]) };
194
+ return {
195
+ readLink,
196
+ writeLink,
197
+ hasLink,
198
+ getLinkEntries,
199
+ parentRefs,
200
+ childrenRefs,
201
+ addRefs,
202
+ removeRefs,
203
+ getChildren: (key) => childrenRefs.get(key),
204
+ getParents: (key) => parentRefs.get(key),
205
+ getLinkedRefs,
206
+ invalidate,
207
+ links,
208
+ types: types2,
209
+ refCount,
210
+ runGarbageCollector,
211
+ onRemoveLink: (callback) => listeners.set("onRemoveLink", [...(listeners == null ? void 0 : listeners.get("onRemoveLink")) ?? [], callback])
212
+ };
78
213
  };
79
- var J = (...t2) => {
214
+ var joinKeys = (...keys) => {
80
215
  var _a;
81
- return (_a = t2 == null ? void 0 : t2.filter(Boolean)) == null ? void 0 : _a.join(".");
82
- };
83
- var ae = process.env.NODE_ENV !== "production";
84
- var ce = (t2 = []) => {
85
- let s2 = [], p2 = (a2) => {
86
- s2.push(a2);
87
- }, c = (a2) => s2.reduce((h, l) => l(h) ?? h, a2);
88
- return t2.forEach(p2), { use: p2, runPlugins: c };
89
- };
90
- var le = (t2) => t2 && S(t2) ? ["_id", "_type", "key", "mutate", "resolve"].every((p2) => p2 in t2) : false;
91
- var ue = () => {
92
- let t2 = /* @__PURE__ */ new Set();
93
- return { debug: (c) => {
94
- t2.forEach((a2) => {
95
- a2({ ...c, timestamp: Date.now() });
96
- });
97
- }, onDebugEvent: (c) => {
98
- t2.add(c);
99
- } };
216
+ return (_a = keys == null ? void 0 : keys.filter(Boolean)) == null ? void 0 : _a.join(".");
100
217
  };
101
- var pe = () => Math.random().toString(16).slice(2);
102
- var De = 0, Se = 100, Ge = "State", fe = "$EACH:ROOT$", it = (t2) => {
103
- let s$1 = (t2 == null ? void 0 : t2._id) ?? `${De++}`, p2 = (t2 == null ? void 0 : t2._type) ?? Ge, c = (t2 == null ? void 0 : t2.keys) ?? {}, a2 = `${p2}:${s$1}`, h = [le, ...(t2 == null ? void 0 : t2.skip) ?? []], l = oe(), O = ue(), q = ce(t2 == null ? void 0 : t2.plugins), T = /* @__PURE__ */ new Map(), V = 0, P = (e) => h.some((r2) => r2(e)), R = (e, r2) => {
104
- let i2 = (r2 == null ? void 0 : r2.deep) ?? false, o = (r2 == null ? void 0 : r2.safe) ?? false, f = (r2 == null ? void 0 : r2.keepLinks) ?? false, { selector: m, ...d } = r2 || {}, y2 = s(e) ? E(e) : null;
105
- O.debug({ type: "resolve", entity: e, options: r2 });
106
- let u = y2 ? l.readLink(y2) : null;
107
- return P(u) ? u : ((S(u) || Array.isArray(u)) && (u = Object.entries(u).reduce((L, [w, v]) => {
108
- let K = v;
109
- return P(K) || (Array.isArray(v) ? (K = v.map((D) => P(D) ? D : G(D) && !o && !l.hasLink(D) ? null : Y(D, y2) && !f || i2 ? _(D, d) : D), o || (K = K.filter(s))) : G(v) && !o && !l.hasLink(v) ? K = null : (Y(E(v), y2) && !f || i2) && (K = _(v, d))), L[w] = K, L;
110
- }, {})), u ? m ? m({ ...u }) : { ...u } : o ? e : null);
111
- }, _ = (e, r2) => R(e, r2) ?? e, M = (e) => {
112
- let r2 = E(e);
113
- r2 && (l.getChildren(r2) || []).forEach((o) => {
114
- I(o) || l.removeRefs(r2, o);
115
- });
116
- }, $ = (e, r2, i$1) => {
117
- var _a, _b, _c, _d;
118
- if ((!e || i(e)) && !G(e) || P(e)) return e;
119
- let o = te(e) ? E(e) : e;
120
- if (G(o)) {
121
- let y2 = ie(r2) ?? "", u = ((_a = i$1 == null ? void 0 : i$1.internal) == null ? void 0 : _a.visitors.get(y2)) ?? [], L = ((_b = i$1 == null ? void 0 : i$1.internal) == null ? void 0 : _b.visitors.get(o)) ?? [];
122
- if (u.includes(o) || o === y2) return null;
123
- (_d = (_c = i$1 == null ? void 0 : i$1.internal) == null ? void 0 : _c.visitors) == null ? void 0 : _d.set(o, [...L, y2]);
124
- }
125
- if (Array.isArray(e)) return e.map((y2) => {
126
- let u = r2 ? J(r2, `${pe()}`) : void 0;
127
- return $(y2, u, i$1);
128
- });
129
- let m = (G(e) ? e : ne(e) ? E(e) : null) ?? r2;
130
- return ((i$1 == null ? void 0 : i$1.overrideMutateMethod) || j)(m, e, i$1);
131
- }, j = (e, ...r2) => {
132
- let { graphKey: i2, options: o, data: f } = A(e, ...r2);
133
- O.debug({ type: "beforeMutate", entity: i2, data: f, options: o });
134
- let m = G(f) ? C(f) : f, d = i2 ?? a2, y2 = I == null ? void 0 : I(d), u = o == null ? void 0 : o.parent, L = R(d ?? ""), w = (o == null ? void 0 : o.internal) || { hasChange: false, visitors: /* @__PURE__ */ new Map([]) }, v = { ...m, ...C(d) }, K = !(o == null ? void 0 : o.parent), D = (o == null ? void 0 : o.replace) ? typeof (o == null ? void 0 : o.replace) == "function" ? o.replace(v) : (o == null ? void 0 : o.replace) === "deep" ? true : K || y2 : false;
135
- if (P(m)) return l.writeLink(d, m, u), d;
136
- !D && S(L) && S(v) && (v = { ...L, ...v }), D && M(d);
137
- let Q = Object.entries(v).reduce((X, [N, de]) => {
138
- let Z = J(d, N), b2 = de, F = L == null ? void 0 : L[N], he = S(m) && N in m;
139
- P(b2) || (!D && he && Array.isArray(b2) && Array.isArray(F) && (b2 = [...F, ...b2]), (S(b2) || Array.isArray(b2) || G(b2)) && (b2 = $(b2, Z, { ...o, parent: d, internal: w })), Array.isArray(b2) && (o == null ? void 0 : o.dedup) !== false && (b2 = se(...b2)));
140
- let me = re(F, Z === b2 ? _(b2) : b2);
141
- return w.hasChange = w.hasChange || !me, !D && G(F) && F !== b2 && l.removeRefs(d, F), X[N] = b2, X;
142
- }, {});
143
- return l.writeLink(d, Q, u), u || l.runGarbageCollector(), (w.hasChange || D) && n2(d, L), O.debug({ type: "afterMutate", entity: i2, data: f, nextData: Q, options: o, hasChange: w.hasChange }), d;
144
- }, B = (e) => {
145
- let r2 = E(e);
146
- if (O.debug({ type: "invalidate", entity: r2 }), r2) {
147
- let i2 = l.getParents(r2) || [];
148
- l.invalidate(r2), i2.forEach((o) => {
149
- let f = l.readLink(o), m = R(o, { safe: false, keepLinks: true });
150
- l.writeLink(o, m), n2(o, f);
151
- });
152
- }
153
- }, n2 = (e, r2) => {
154
- if (V > Se) throw new Error("Too deep notify.");
155
- let i2 = E(e);
156
- if (O.debug({ type: "notify", entity: i2 }), i2) {
157
- V++;
158
- let o = [...T.get(i2) || [], ...T.get(fe) || []], f = l.getChildren(i2) || [], m = R(i2), d = (y2) => {
159
- let u = m && (y2 == null ? void 0 : y2(m)), L = r2 && (y2 == null ? void 0 : y2(r2));
160
- return { next: u, prev: L, hasChange: !W(u, L) };
161
- };
162
- o.forEach(({ callback: y2, selector: u }) => {
163
- if (u) {
164
- let { next: L, prev: w, hasChange: v } = d(u);
165
- v && y2(L, w);
166
- } else y2(m, r2);
167
- }), f.forEach((y2) => n2(y2, r2));
168
- }
169
- V = 0;
170
- }, g = (...e) => {
171
- let r2 = typeof e[0] == "function" ? fe : e[0], i2 = typeof e[0] == "function" ? e[0] : e[1], o = typeof e[0] == "function" ? e[1] : e[2], f = E(r2), m = o == null ? void 0 : o.selector;
172
- f && (T.has(f) ? T.set(f, [...Array.from(T.get(f) || []), { callback: i2, selector: m }]) : T.set(f, [{ callback: i2, selector: m }]), l.onRemoveLink((y2, u) => {
173
- y2 === f && n2(f, u);
174
- }));
175
- let d = () => {
176
- if (f) {
177
- let y2 = (T.get(f) || []).findIndex((u) => u.callback === i2);
178
- if (y2 !== -1) {
179
- let u = T.get(f) || [];
180
- u.splice(y2, 1), T.set(f, u);
181
- }
182
- }
183
- };
184
- return (o == null ? void 0 : o.signal) && o.signal.addEventListener("abort", d, { once: true }), d;
185
- }, k = (e) => [...l.types.get(e) ?? []], x = (e) => {
186
- let r2 = (typeof e == "string" ? e : E(e)) || "";
187
- return (l.getParents(r2) ?? []).map((o) => R(o));
188
- }, E = (e) => {
189
- var _a;
190
- if (typeof e == "string") return C(e) ? e : null;
191
- if (!(e == null ? void 0 : e._type)) return null;
192
- let r2 = null;
193
- return e._type in c ? r2 = ((_a = c[e._type]) == null ? void 0 : _a.call(c, e)) ?? null : (s(e.id) || s(e._id)) && (r2 = `${e.id ?? e._id}`), r2 && `${e._type}:${r2}`;
194
- }, C = (e) => {
195
- if (S(e) && (e == null ? void 0 : e._type) && E(e)) return e;
196
- if (!e || typeof e != "string") return null;
197
- let [r2, ...i2] = e.split(":");
198
- return !r2 || i2.length < 1 ? null : { _type: r2, _id: i2.join(":") };
199
- }, A = (e, ...r2) => {
200
- let i2 = typeof e == "string" ? r2[0] : e;
201
- return typeof i2 == "function" ? i2 = i2(R(e)) : G(i2) && (i2 = C(i2)), { graphKey: typeof e == "string" ? e : E(e), options: typeof e == "string" ? r2[1] : r2[0], data: i2 };
202
- };
203
- function U(e) {
204
- q.use(e), e(this);
205
- }
206
- let ye = (e) => {
207
- h.push(e);
218
+ var isDev = process.env.NODE_ENV !== "production";
219
+ var createPluginsState = (initialPlugins = []) => {
220
+ const plugins = [];
221
+ const use = (plugin) => {
222
+ plugins.push(plugin);
223
+ };
224
+ const runPlugins = (state) => {
225
+ return plugins.reduce((graphState, plugin) => plugin(graphState) ?? graphState, state);
226
+ };
227
+ initialPlugins.forEach(use);
228
+ return {
229
+ use,
230
+ runPlugins
208
231
  };
209
- (t2 == null ? void 0 : t2.initialState) && j(t2.initialState, { replace: true });
210
- let ge = { _type: p2, _id: s$1, key: a2, mutate: j, subscribe: g, resolve: R, safeResolve: _, resolveParents: x, inspectFields: k, invalidate: B, keyOfEntity: E, entityOfKey: C, getArgumentsForMutate: A, types: l.types, cache: l, use: U, addSkip: ye, subscribers: ae ? T : void 0, onDebugEvent: O.onDebugEvent };
211
- return l.onRemoveLink((e, r2) => O.debug({ type: "garbageRemove", entity: e, prevValue: r2 })), q.runPlugins(ge);
212
232
  };
213
- const BASE_HEADERS = {
214
- "Content-Type": "application/json"
233
+ var isGraphState = (input) => {
234
+ if (!input)
235
+ return false;
236
+ if (isObject$1(input)) {
237
+ const fields = ["_id", "_type", "key", "mutate", "resolve"];
238
+ return fields.every((field) => field in input);
239
+ }
240
+ return false;
215
241
  };
216
- const createFetcher = (baseUrl, defaultHeaders = {}) => {
217
- const cache = /* @__PURE__ */ new Map();
218
- const inflightRequests = /* @__PURE__ */ new Map();
219
- const getCacheKey = (query2, variables, options) => JSON.stringify({ query: query2, variables, options });
220
- const query = async (query2, variables = {}, options = {}) => {
221
- const cacheKey = getCacheKey(query2, variables, options);
222
- if (cache.has(cacheKey)) {
223
- return cache.get(cacheKey);
224
- }
225
- if (inflightRequests.has(cacheKey)) {
226
- return inflightRequests.get(cacheKey);
227
- }
228
- const request = fetch(baseUrl, {
229
- ...options,
230
- method: "POST",
231
- body: JSON.stringify({ query: query2, variables }),
232
- headers: {
233
- ...BASE_HEADERS,
234
- ...defaultHeaders,
235
- ...options.headers
236
- }
237
- }).then(async (res) => {
238
- if (!res.ok) throw new Error(`Fetch error: ${res.status}`);
239
- const data = await res.json();
240
- if (!query2.includes("mutation")) {
241
- cache.set(cacheKey, data);
242
- }
243
- return data;
244
- }).finally(() => {
245
- inflightRequests.delete(cacheKey);
242
+ var createDebugState = () => {
243
+ const listeners = /* @__PURE__ */ new Set();
244
+ const onDebugEvent = (callback) => {
245
+ listeners.add(callback);
246
+ };
247
+ const debug = (event) => {
248
+ listeners.forEach((callback) => {
249
+ callback({ ...event, timestamp: Date.now() });
246
250
  });
247
- inflightRequests.set(cacheKey, request);
248
- return request;
249
251
  };
250
- const invalidate = (endpoint, options) => {
251
- cache.delete(getCacheKey(endpoint, options));
252
+ return {
253
+ debug,
254
+ onDebugEvent
252
255
  };
253
- const clearCache = () => cache.clear();
254
- return { query, invalidate, clearCache };
255
256
  };
256
- const getFragmentQuery = (isSelf) => isSelf ? `
257
- query FragmentDocument($fragmentSlug: Int!) {
258
- fragment(fragmentIds: [$fragmentSlug]) {
259
- id
260
- document
261
- linkedFragments {
262
- id
263
- document
264
- }
265
- }
266
- }
267
- ` : `
268
- query FragmentDocument($fragmentSlug: Int!) {
269
- clientFragment(fragmentId: $fragmentSlug) {
270
- id
271
- document
272
- linkedFragments {
273
- id
274
- document
275
- }
276
- }
257
+ var cache = /* @__PURE__ */ new Set();
258
+ var wrapMessage = (message) => `[GraphState]: ${message}`;
259
+ function warn(message) {
260
+ if (!cache.has(message)) {
261
+ console.warn(wrapMessage(message));
262
+ cache.add(message);
263
+ }
277
264
  }
278
- `;
279
- var isEmptyValue = (value) => !value && (value === null || value === void 0);
280
- var isValue = (value) => !isEmptyValue(value);
281
- var createConstants$1 = (...constants) => {
282
- return constants.reduce((acc, constant) => {
283
- acc[constant] = constant;
284
- return acc;
285
- }, {});
265
+ var keyOfEntity = (entity) => {
266
+ if (typeof entity === "string") {
267
+ return entityOfKey(entity) ? entity : null;
268
+ }
269
+ if (!(entity == null ? void 0 : entity._type)) {
270
+ return null;
271
+ }
272
+ let entityId = null;
273
+ if (y(entity.id) || y(entity._id)) {
274
+ entityId = `${entity.id ?? entity._id}`;
275
+ }
276
+ return !entityId ? entityId : `${entity._type}:${entityId}`;
286
277
  };
287
- var isBrowser_default = typeof window !== "undefined";
288
- var generateId = () => Math.random().toString(16).slice(2);
289
- var setKey = (v) => `$${v}`;
290
- var getKey = (v) => isKey(v) ? v.slice(1) : null;
291
- var isKey = (v) => typeof v === "string" && v.startsWith("$");
292
- function hashGenerator(layerKey) {
293
- let hash = 0;
294
- for (let i2 = 0; i2 < layerKey.length; i2++) {
295
- hash = (hash << 5) - hash + layerKey.charCodeAt(i2);
296
- hash |= 0;
278
+ var entityOfKey = (entity) => {
279
+ if (isObject$1(entity) && (entity == null ? void 0 : entity._type) && keyOfEntity(entity)) {
280
+ return entity;
297
281
  }
298
- const raw = Math.abs(hash).toString(36);
299
- return /^[0-9]/.test(raw) ? `h${raw}` : raw;
300
- }
301
- const getEmptyFragment = (fragmentId) => {
302
- const layerId = generateId();
282
+ if (!entity || typeof entity !== "string")
283
+ return null;
284
+ const [typeName, ...restTypes] = entity.split(":");
285
+ if (!typeName || restTypes.length < 1)
286
+ return null;
303
287
  return {
304
- [`Fragment:${fragmentId}`]: {
305
- _type: "Fragment",
306
- _id: fragmentId,
307
- children: [`Frame:${layerId}`],
308
- layoutSizingHorizontal: "Fixed",
309
- layoutSizingVertical: "Fixed",
310
- horizontalGrow: "auto",
311
- verticalGrow: "auto",
312
- renderMode: "parent",
313
- opacity: 1,
314
- visible: true,
315
- overflow: "hidden",
316
- overrides: [],
317
- properties: ["Variable:62218c840bd111"]
318
- },
319
- [`Frame:${layerId}`]: {
320
- _type: "Frame",
321
- _id: layerId,
322
- opacity: 1,
323
- parent: setKey(`Fragment:${fragmentId}`),
324
- visible: true,
325
- overflow: "visible",
326
- children: [],
327
- width: 320,
328
- height: 200,
329
- layoutSizingHorizontal: "Fixed",
330
- layoutSizingVertical: "Fixed",
331
- fillType: "Solid",
332
- positionType: "absolute",
333
- solidFill: "rgba(255, 255, 255, 1)",
334
- name: "Frame",
335
- isPrimary: true,
336
- threshold: 320
337
- }
288
+ _type: typeName,
289
+ _id: restTypes.join(":")
338
290
  };
339
291
  };
340
- const fetchBeacon = (baseUrl) => {
341
- const sender = isBrowser_default && typeof (navigator == null ? void 0 : navigator.sendBeacon) === "function" ? navigator.sendBeacon : () => null;
342
- const sendBeacon = (data) => {
343
- try {
344
- sender("/graphql", "test");
345
- } catch (e) {
346
- console.error(e);
292
+ function omit(obj, ...props) {
293
+ const result = { ...obj };
294
+ props.forEach((prop) => {
295
+ delete result[prop];
296
+ });
297
+ return result;
298
+ }
299
+ var ID = 0;
300
+ var DEEP_LIMIT = 100;
301
+ var STATE_TYPE = "State";
302
+ var EACH_UPDATED = "$EACH:ROOT$";
303
+ var createState = (options) => {
304
+ const id = (options == null ? void 0 : options._id) ?? `${ID++}`;
305
+ const type = (options == null ? void 0 : options._type) ?? STATE_TYPE;
306
+ const stateKey = `${type}:${id}`;
307
+ const skipPredictors = [isGraphState, ...(options == null ? void 0 : options.skip) ?? []];
308
+ const cache2 = createCache();
309
+ const debugState = createDebugState();
310
+ const pluginsStore = createPluginsState(options == null ? void 0 : options.plugins);
311
+ const subscribers = /* @__PURE__ */ new Map();
312
+ let deepIndex = 0;
313
+ const isSkipped = (entity) => {
314
+ return skipPredictors.some((predictor) => predictor(entity));
315
+ };
316
+ const getReferences = (entity, options2) => {
317
+ const withPartialKeys = (options2 == null ? void 0 : options2.withPartialKeys) ?? false;
318
+ const key = keyOfEntity2(entity);
319
+ if (!key)
320
+ return [];
321
+ const values = cache2.getParents(key) ?? [];
322
+ return values.filter((v) => withPartialKeys ? !isPartialKey(v) : v);
323
+ };
324
+ const resolve = (input, options2) => {
325
+ const isDeep = (options2 == null ? void 0 : options2.deep) ?? false;
326
+ const isSafe = (options2 == null ? void 0 : options2.safe) ?? false;
327
+ const keepLinks = (options2 == null ? void 0 : options2.keepLinks) ?? false;
328
+ const removeLinkFromSubGraph = (options2 == null ? void 0 : options2.removeLinkFromSubGraph) ?? true;
329
+ const { selector, ...coreOptions } = options2 || {};
330
+ const inputKey = y(input) ? keyOfEntity2(input) : null;
331
+ debugState.debug({ type: "resolve", entity: input, options: options2 });
332
+ let value = inputKey ? cache2.readLink(inputKey) : null;
333
+ if (isSkipped(value))
334
+ return value;
335
+ if (isObject$1(value) || Array.isArray(value)) {
336
+ value = Object.entries(value).reduce((acc, [key, value2]) => {
337
+ let resultValue = value2;
338
+ if (!isSkipped(resultValue)) {
339
+ if (Array.isArray(value2)) {
340
+ resultValue = value2.map((v) => {
341
+ if (isSkipped(v))
342
+ return v;
343
+ if (isLinkKey(v) && !isSafe && !cache2.hasLink(v)) {
344
+ return null;
345
+ }
346
+ return isPartOfGraph(v, inputKey) && !keepLinks || isDeep ? safeResolve(v, coreOptions) : v;
347
+ });
348
+ if (!isSafe) {
349
+ resultValue = resultValue.filter(y);
350
+ }
351
+ } else {
352
+ if (isLinkKey(value2) && !isSafe && !cache2.hasLink(value2)) {
353
+ resultValue = null;
354
+ } else if (isPartOfGraph(keyOfEntity2(value2), inputKey) && !keepLinks || isDeep) {
355
+ resultValue = safeResolve(value2, coreOptions);
356
+ }
357
+ }
358
+ }
359
+ acc[key] = isPartialGraph(resultValue) && removeLinkFromSubGraph ? omit(resultValue, "_type", "_id") : resultValue;
360
+ return acc;
361
+ }, {});
347
362
  }
363
+ return value ? selector ? selector({ ...value }) : { ...value } : isSafe ? input : null;
348
364
  };
349
- return {
350
- sendBeacon
365
+ const safeResolve = (input, options2) => resolve(input, options2) ?? input;
366
+ const unlinkGraph = (entity) => {
367
+ const graphKey = keyOfEntity2(entity);
368
+ if (graphKey) {
369
+ const deps = cache2.getChildren(graphKey) || [];
370
+ deps.forEach((depLink) => {
371
+ if (!isPartialKey(depLink)) {
372
+ cache2.removeRefs(graphKey, depLink);
373
+ }
374
+ });
375
+ }
351
376
  };
352
- };
353
- const fetchPlugin = (state) => {
354
- var _a, _b, _c;
355
- const isSelf = ((_a = state == null ? void 0 : state.env) == null ? void 0 : _a.isSelf) ?? false;
356
- const url = ((_b = state == null ? void 0 : state.env) == null ? void 0 : _b.url) ?? "http://localhost/graphql";
357
- const apiToken = (_c = state == null ? void 0 : state.env) == null ? void 0 : _c.apiToken;
358
- const fetcher = createFetcher(url, {
359
- Authorization: `Bearer ${apiToken}`
360
- });
361
- const beaconFetcher = fetchBeacon();
362
- const queryFragment = async (fragmentId) => {
363
- var _a2, _b2, _c2, _d;
364
- if (!apiToken) return null;
365
- if (state.$fetch.cacheLinks.get(fragmentId)) {
366
- return state.$fetch.cacheLinks.get(fragmentId);
377
+ const mutateField = (input, parentFieldKey, options2) => {
378
+ var _a, _b, _c, _d;
379
+ if ((!input || l(input)) && !isLinkKey(input) || isSkipped(input)) {
380
+ return input;
367
381
  }
368
- const response = await fetcher.query(getFragmentQuery(isSelf), {
369
- fragmentSlug: fragmentId
370
- });
371
- const fragment = isSelf ? (_b2 = (_a2 = response == null ? void 0 : response.data) == null ? void 0 : _a2.fragment) == null ? void 0 : _b2[0] : (_c2 = response == null ? void 0 : response.data) == null ? void 0 : _c2.clientFragment;
372
- let fragmentDocument = fragment == null ? void 0 : fragment.document;
373
- if (typeof fragmentDocument === "string") {
374
- try {
375
- if (Object.keys(JSON.parse(fragmentDocument)).length === 0) {
376
- fragmentDocument = getEmptyFragment(fragmentId);
382
+ const inputLinkKey = isGraphOrKey(input) ? keyOfEntity2(input) : input;
383
+ if (isLinkKey(inputLinkKey)) {
384
+ const parentGraph = getGraphLink(parentFieldKey) ?? "";
385
+ const parentPaths = ((_a = options2 == null ? void 0 : options2.internal) == null ? void 0 : _a.visitors.get(parentGraph)) ?? [];
386
+ const visitorsPaths = ((_b = options2 == null ? void 0 : options2.internal) == null ? void 0 : _b.visitors.get(inputLinkKey)) ?? [];
387
+ if (parentPaths.includes(inputLinkKey) || inputLinkKey === parentGraph) {
388
+ return null;
389
+ }
390
+ (_d = (_c = options2 == null ? void 0 : options2.internal) == null ? void 0 : _c.visitors) == null ? void 0 : _d.set(inputLinkKey, [...visitorsPaths, parentGraph]);
391
+ }
392
+ if (Array.isArray(input)) {
393
+ return input.map((item) => {
394
+ const indexKey = parentFieldKey ? joinKeys(parentFieldKey, `${ID++}`) : void 0;
395
+ return mutateField(item, indexKey, options2);
396
+ });
397
+ }
398
+ const entityKey = isLinkKey(input) ? input : isGraph(input) ? keyOfEntity2(input) : null;
399
+ const childKey = entityKey ?? parentFieldKey;
400
+ const mutateMethod = (options2 == null ? void 0 : options2.overrideMutateMethod) || mutate;
401
+ return mutateMethod(childKey, input, options2);
402
+ };
403
+ const mutate = (entity, ...args) => {
404
+ const { graphKey: entityGraphKey, options: options2, data: rawData } = getArgumentsForMutate(entity, ...args);
405
+ debugState.debug({ type: "beforeMutate", entity: entityGraphKey, data: rawData, options: options2 });
406
+ const data = isLinkKey(rawData) ? entityOfKey2(rawData) : rawData;
407
+ const graphKey = entityGraphKey ?? stateKey;
408
+ const partialKey = isPartialKey == null ? void 0 : isPartialKey(graphKey);
409
+ const parentKey = options2 == null ? void 0 : options2.parent;
410
+ const prevGraph = resolve(graphKey ?? "", { removeLinkFromSubGraph: false });
411
+ const internal = (options2 == null ? void 0 : options2.internal) || { hasChange: false, visitors: /* @__PURE__ */ new Map([]) };
412
+ let graphData = {
413
+ ...data,
414
+ ...entityOfKey2(graphKey)
415
+ };
416
+ const isTopLevelGraph = !(options2 == null ? void 0 : options2.parent);
417
+ const isReplace = (options2 == null ? void 0 : options2.replace) ? typeof (options2 == null ? void 0 : options2.replace) === "function" ? options2.replace(graphData) : (options2 == null ? void 0 : options2.replace) === "deep" ? true : isTopLevelGraph || partialKey : false;
418
+ if (isSkipped(data)) {
419
+ cache2.writeLink(graphKey, data, parentKey);
420
+ return graphKey;
421
+ }
422
+ if (!isReplace && isObject$1(prevGraph) && isObject$1(graphData)) {
423
+ graphData = {
424
+ ...prevGraph,
425
+ ...graphData
426
+ };
427
+ }
428
+ if (isReplace) {
429
+ unlinkGraph(graphKey);
430
+ }
431
+ const nextGraph = Object.entries(graphData).reduce((acc, [key, value]) => {
432
+ const fieldKey = joinKeys(graphKey, key);
433
+ let fieldValue = value;
434
+ const prevValue = prevGraph == null ? void 0 : prevGraph[key];
435
+ const isUpdateField = isObject$1(data) && key in data;
436
+ if (!isSkipped(fieldValue)) {
437
+ if (!isReplace && isUpdateField && Array.isArray(fieldValue) && Array.isArray(prevValue)) {
438
+ fieldValue = [...prevValue, ...fieldValue];
439
+ }
440
+ if (isObject$1(fieldValue) || Array.isArray(fieldValue) || isLinkKey(fieldValue)) {
441
+ fieldValue = mutateField(fieldValue, fieldKey, {
442
+ ...options2,
443
+ parent: graphKey,
444
+ internal
445
+ });
377
446
  }
378
- } catch (e) {
379
- console.error(e);
447
+ if (Array.isArray(fieldValue) && (options2 == null ? void 0 : options2.dedup) !== false) {
448
+ fieldValue = uniqueLinks(...fieldValue);
449
+ }
450
+ }
451
+ const isEqual = shallowEqual(prevValue, fieldKey === fieldValue ? safeResolve(fieldValue) : fieldValue);
452
+ internal.hasChange = internal.hasChange || !isEqual;
453
+ if (!isReplace && isLinkKey(prevValue) && prevValue !== fieldValue) {
454
+ cache2.removeRefs(graphKey, prevValue);
380
455
  }
456
+ acc[key] = fieldValue;
457
+ return acc;
458
+ }, {});
459
+ cache2.writeLink(graphKey, nextGraph, parentKey);
460
+ if (!parentKey) {
461
+ cache2.runGarbageCollector();
381
462
  }
382
- if (fragment) {
383
- state.$fetch.cacheDocuments.set(fragmentId, fragmentDocument);
384
- if (Array.isArray(fragment.linkedFragments)) {
385
- fragment.linkedFragments.forEach(
386
- (linkedFragment) => state.$fetch.cacheDocuments.set(
387
- linkedFragment.id,
388
- linkedFragment.document
389
- )
390
- );
463
+ if ((internal.hasChange || isReplace) && !parentKey) {
464
+ notify(graphKey, prevGraph);
465
+ }
466
+ debugState.debug({
467
+ type: "afterMutate",
468
+ entity: entityGraphKey,
469
+ data: rawData,
470
+ nextData: nextGraph,
471
+ options: options2,
472
+ hasChange: internal.hasChange
473
+ });
474
+ return graphKey;
475
+ };
476
+ const invalidate = (entity) => {
477
+ const key = keyOfEntity2(entity);
478
+ debugState.debug({ type: "invalidate", entity: key });
479
+ if (key) {
480
+ const parents = cache2.getParents(key) || [];
481
+ cache2.invalidate(key);
482
+ parents.forEach((parentKey) => {
483
+ const prevParent = cache2.readLink(parentKey);
484
+ const freshParent = resolve(parentKey, { safe: false, keepLinks: true, removeLinkFromSubGraph: false });
485
+ cache2.writeLink(parentKey, freshParent);
486
+ notify(parentKey, prevParent);
487
+ });
488
+ }
489
+ };
490
+ const notify = (entity, prevState, _internal) => {
491
+ if (deepIndex > DEEP_LIMIT) {
492
+ throw new Error("Too deep notify.");
493
+ }
494
+ const depth = (_internal == null ? void 0 : _internal.depth) ?? 0;
495
+ const key = keyOfEntity2(entity);
496
+ debugState.debug({ type: "notify", entity: key });
497
+ if (key) {
498
+ deepIndex++;
499
+ const subs = [...subscribers.get(key) || [], ...subscribers.get(EACH_UPDATED) || []];
500
+ const deps = cache2.getChildren(key) || [];
501
+ const nextResult = resolve(key);
502
+ const getSelectedValues = (selector) => {
503
+ const next = nextResult && (selector == null ? void 0 : selector(nextResult));
504
+ const prev = prevState && (selector == null ? void 0 : selector(prevState));
505
+ return { next, prev, hasChange: !deepEqual(next, prev) };
506
+ };
507
+ subs.forEach(({ callback, options: options2 }) => {
508
+ const selector = options2 == null ? void 0 : options2.selector;
509
+ const directChangesOnly = (options2 == null ? void 0 : options2.directChangesOnly) ?? false;
510
+ if (directChangesOnly && depth > 0) {
511
+ return;
512
+ }
513
+ if (selector) {
514
+ const { next, prev, hasChange } = getSelectedValues(selector);
515
+ if (hasChange)
516
+ callback(next, prev);
517
+ } else {
518
+ callback(nextResult, prevState);
519
+ }
520
+ });
521
+ deps.forEach(
522
+ (dep) => notify(dep, prevState, {
523
+ depth: depth + 1
524
+ })
525
+ );
526
+ }
527
+ deepIndex = 0;
528
+ };
529
+ const subscribe = (...args) => {
530
+ const input = typeof args[0] === "function" ? EACH_UPDATED : args[0];
531
+ const callback = typeof args[0] === "function" ? args[0] : args[1];
532
+ const options2 = typeof args[0] === "function" ? args[1] : args[2];
533
+ const key = keyOfEntity2(input);
534
+ if (key) {
535
+ if (subscribers.has(key)) {
536
+ subscribers.set(key, [...Array.from(subscribers.get(key) || []), { callback, options: options2 }]);
537
+ } else {
538
+ subscribers.set(key, [{ callback, options: options2 }]);
391
539
  }
392
- (_d = state.$fetch.cacheLinks) == null ? void 0 : _d.set(fragmentId, {
393
- document: state.$fetch.cacheDocuments.get(fragmentId),
394
- linkedFragments: fragment.linkedFragments ?? []
540
+ cache2.onRemoveLink((link, prevValue) => {
541
+ if (link === key) {
542
+ notify(key, prevValue);
543
+ }
395
544
  });
396
- return state.$fetch.cacheLinks.get(fragmentId);
397
545
  }
398
- return null;
546
+ const unsubscribe = () => {
547
+ if (key) {
548
+ const subIndex = (subscribers.get(key) || []).findIndex((sub) => sub.callback === callback);
549
+ if (subIndex !== -1) {
550
+ const nextSubscribers = subscribers.get(key) || [];
551
+ nextSubscribers.splice(subIndex, 1);
552
+ subscribers.set(key, nextSubscribers);
553
+ }
554
+ }
555
+ };
556
+ if (options2 == null ? void 0 : options2.signal) {
557
+ options2.signal.addEventListener("abort", unsubscribe, { once: true });
558
+ }
559
+ return unsubscribe;
399
560
  };
400
- state.$fetch = {
401
- cacheDocuments: /* @__PURE__ */ new Map(),
402
- cacheLinks: /* @__PURE__ */ new Map(),
403
- queryFragment,
404
- query: fetcher.query,
405
- sendBeacon: beaconFetcher.sendBeacon,
406
- readFragment: (fragmentId) => state.$fetch.cacheDocuments.get(fragmentId)
561
+ const inspectFields = (graphType) => [...cache2.types.get(graphType) ?? []];
562
+ const resolveParents = (field) => {
563
+ const key = (typeof field === "string" ? field : keyOfEntity2(field)) || "";
564
+ const refs = cache2.getParents(key) ?? [];
565
+ return refs.map((ref) => resolve(ref));
566
+ };
567
+ const keyOfEntity2 = (entity) => {
568
+ warn("Instance keyOfEntity is deprecated. Use static method keyOfEntity.");
569
+ return keyOfEntity(entity);
570
+ };
571
+ const entityOfKey2 = (entity) => {
572
+ warn("Instance entityOfKey is deprecated. Use static method entityOfKey.");
573
+ return entityOfKey(entity);
574
+ };
575
+ const getArgumentsForMutate = (entity, ...args) => {
576
+ let data = typeof entity === "string" ? args[0] : entity;
577
+ if (typeof data === "function") {
578
+ data = data(resolve(entity));
579
+ } else if (isLinkKey(data)) {
580
+ data = entityOfKey2(data);
581
+ }
582
+ return {
583
+ graphKey: typeof entity === "string" ? entity : keyOfEntity2(entity),
584
+ options: typeof entity === "string" ? args[1] : args[0],
585
+ data
586
+ };
587
+ };
588
+ function use(plugin) {
589
+ pluginsStore.use(plugin);
590
+ plugin(this);
591
+ }
592
+ const addSkip = (predictor) => {
593
+ skipPredictors.push(predictor);
594
+ };
595
+ if (options == null ? void 0 : options.initialState) {
596
+ mutate(options.initialState, { replace: "deep" });
597
+ }
598
+ const graphState = {
599
+ _type: type,
600
+ _id: id,
601
+ key: stateKey,
602
+ getReferences,
603
+ mutate,
604
+ subscribe,
605
+ resolve,
606
+ safeResolve,
607
+ resolveParents,
608
+ inspectFields,
609
+ invalidate,
610
+ keyOfEntity: keyOfEntity2,
611
+ entityOfKey: entityOfKey2,
612
+ getArgumentsForMutate,
613
+ types: cache2.types,
614
+ cache: cache2,
615
+ use,
616
+ addSkip,
617
+ subscribers: isDev ? subscribers : void 0,
618
+ onDebugEvent: debugState.onDebugEvent
407
619
  };
620
+ cache2.onRemoveLink((link, prevValue) => debugState.debug({ type: "garbageRemove", entity: link, prevValue }));
621
+ return pluginsStore.runPlugins(graphState);
408
622
  };
409
- const createConstants = (...constants) => {
623
+ const createConstants$1 = (...constants) => {
410
624
  return constants.reduce((acc, constant) => {
411
625
  acc[constant] = constant;
412
626
  return acc;
413
627
  }, {});
414
628
  };
415
- const nodes = createConstants(
629
+ const nodes = createConstants$1(
416
630
  "Fragment",
417
631
  "FragmentInstance",
418
632
  "Instance",
633
+ "Collection",
419
634
  "Breakpoint",
420
635
  "Frame",
421
636
  "Image",
@@ -426,57 +641,53 @@ const nodes = createConstants(
426
641
  "ComputedValue",
427
642
  "TransformValue"
428
643
  );
429
- const fragmentGrowingMode = createConstants("auto", "fill");
430
- const borderType = createConstants("None", "Solid", "Dashed", "Dotted");
431
- const linkTarget = createConstants("_blank");
432
- const paintMode = createConstants("None", "Solid", "Image");
433
- const imagePaintScaleModes = createConstants(
434
- "Fill",
435
- "Fit",
436
- "Crop",
437
- "Tile"
438
- );
439
- const constrain = createConstants(
644
+ const fragmentGrowingMode = createConstants$1("auto", "fill");
645
+ const borderType = createConstants$1("None", "Solid", "Dashed", "Dotted");
646
+ const linkTarget = createConstants$1("_blank", "none");
647
+ const paintMode = createConstants$1("None", "Solid", "Image");
648
+ const imagePaintScaleModes = createConstants$1("Auto", "Contain", "Cover");
649
+ const constrain = createConstants$1(
440
650
  "Min",
441
651
  "Center",
442
652
  "Max",
443
653
  "Stretch",
444
654
  "Scale"
445
655
  );
446
- const positionType = createConstants("absolute", "relative");
447
- const sizing = createConstants("Fixed", "Hug", "Fill", "Relative");
448
- const layerMode = createConstants("none", "flex");
449
- const layerDirection = createConstants("vertical", "horizontal");
450
- const layerAlign = createConstants("start", "center", "end");
451
- const layerDistribute = createConstants(
656
+ const positionType = createConstants$1("absolute", "relative");
657
+ const sizing = createConstants$1("Fixed", "Hug", "Fill", "Relative");
658
+ const layerMode = createConstants$1("none", "flex");
659
+ const layerDirection = createConstants$1("vertical", "horizontal");
660
+ const layerAlign = createConstants$1("start", "center", "end");
661
+ const layerDistribute = createConstants$1(
452
662
  "start",
453
663
  "center",
454
664
  "end",
455
665
  "space-between",
456
666
  "space-around"
457
667
  );
458
- const textTransform = createConstants(
668
+ const textTransform = createConstants$1(
459
669
  "none",
460
670
  "uppercase",
461
671
  "lowercase",
462
672
  "capitalize"
463
673
  );
464
- const textDecorations = createConstants(
674
+ const textDecorations = createConstants$1(
465
675
  "none",
466
676
  "underline",
467
677
  "line-through"
468
678
  );
469
- const effectType = createConstants("loop", "appear", "hover", "tap");
470
- const effectName = createConstants(
679
+ const effectType = createConstants$1("loop", "appear", "hover", "tap");
680
+ const effectName = createConstants$1(
471
681
  "fade",
472
682
  "slide",
473
683
  "bounce",
474
684
  "wiggle",
475
685
  "increase"
476
686
  );
477
- const variableType = createConstants(
687
+ const variableType = createConstants$1(
478
688
  "Event",
479
689
  "String",
690
+ "Link",
480
691
  "Boolean",
481
692
  "Array",
482
693
  "Color",
@@ -484,9 +695,10 @@ const variableType = createConstants(
484
695
  "Date",
485
696
  "Enum",
486
697
  "Number",
698
+ "Image",
487
699
  "Object"
488
700
  );
489
- const whiteSpace = createConstants(
701
+ const whiteSpace = createConstants$1(
490
702
  "normal",
491
703
  "nowrap",
492
704
  "pre",
@@ -494,8 +706,8 @@ const whiteSpace = createConstants(
494
706
  "pre-line",
495
707
  "break-spaces"
496
708
  );
497
- const overflow = createConstants("visible", "hidden", "scroll");
498
- const variableTransforms = createConstants(
709
+ const overflow = createConstants$1("visible", "hidden", "scroll");
710
+ const variableTransforms = createConstants$1(
499
711
  "convert",
500
712
  "exists",
501
713
  "equals",
@@ -518,15 +730,21 @@ const variableTransforms = createConstants(
518
730
  "convertFromBoolean",
519
731
  "negative"
520
732
  );
521
- const renderTarget = createConstants("canvas", "document");
522
- const renderMode = createConstants("viewport", "parent", "fixed");
523
- const interactions = createConstants("click", "mouseover");
524
- const eventMode = createConstants("goal", "callback");
733
+ const renderTarget = createConstants$1("canvas", "document");
734
+ const renderMode = createConstants$1("viewport", "parent", "fixed");
735
+ const interactions = createConstants$1("click", "mouseover", "appear");
736
+ const eventMode = createConstants$1("goal", "callback", "tracker");
737
+ const scopeTypes = createConstants$1(
738
+ "InstanceScope",
739
+ "FragmentScope",
740
+ "CollectionScope",
741
+ "CollectionItemScope"
742
+ );
525
743
  const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
526
744
  __proto__: null,
527
745
  borderType,
528
746
  constrain,
529
- createConstants,
747
+ createConstants: createConstants$1,
530
748
  effectName,
531
749
  effectType,
532
750
  eventMode,
@@ -544,6 +762,7 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
544
762
  positionType,
545
763
  renderMode,
546
764
  renderTarget,
765
+ scopeTypes,
547
766
  sizing,
548
767
  textDecorations,
549
768
  textTransform,
@@ -1297,9 +1516,17 @@ const linkValidator = /* @__PURE__ */ check(
1297
1516
  }
1298
1517
  );
1299
1518
  const layerField = (schema, meta) => {
1300
- const modifiedSchema = (meta == null ? void 0 : meta.variable) ? /* @__PURE__ */ union([schema, /* @__PURE__ */ pipe(/* @__PURE__ */ string(), linkValidator)]) : schema;
1519
+ const overridable = (meta == null ? void 0 : meta.overridable) ?? true;
1520
+ const variable = (meta == null ? void 0 : meta.variable) ?? false;
1521
+ const schemaParts = [schema];
1522
+ if (variable) {
1523
+ schemaParts.push(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), linkValidator));
1524
+ }
1525
+ if (overridable) {
1526
+ schemaParts.push(/* @__PURE__ */ any());
1527
+ }
1301
1528
  return /* @__PURE__ */ pipe(
1302
- /* @__PURE__ */ optional(modifiedSchema),
1529
+ /* @__PURE__ */ optional(/* @__PURE__ */ union(schemaParts)),
1303
1530
  /* @__PURE__ */ transform((meta == null ? void 0 : meta.transform) ?? ((v2) => v2)),
1304
1531
  /* @__PURE__ */ metadata(meta ?? {})
1305
1532
  );
@@ -1322,8 +1549,28 @@ const PositionSchema = /* @__PURE__ */ object({
1322
1549
  position: layerField(/* @__PURE__ */ enum_(Object.keys(positionType)), {
1323
1550
  fallback: positionType.absolute
1324
1551
  }),
1325
- top: layerField(/* @__PURE__ */ number(), { fallback: 0, transform: Math.ceil }),
1326
- left: layerField(/* @__PURE__ */ number(), { fallback: 0, transform: Math.ceil })
1552
+ top: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ number()), {
1553
+ fallback: null,
1554
+ transform: (value) => typeof value === "number" ? Math.ceil(value) : value
1555
+ }),
1556
+ left: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ number()), {
1557
+ fallback: null,
1558
+ transform: (value) => typeof value === "number" ? Math.ceil(value) : value
1559
+ }),
1560
+ right: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ number()), {
1561
+ fallback: null,
1562
+ transform: (value) => typeof value === "number" ? Math.ceil(value) : value
1563
+ }),
1564
+ bottom: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ number()), {
1565
+ fallback: null,
1566
+ transform: (value) => typeof value === "number" ? Math.ceil(value) : value
1567
+ }),
1568
+ centerAnchorX: layerField(/* @__PURE__ */ number(), {
1569
+ fallback: 0.5
1570
+ }),
1571
+ centerAnchorY: layerField(/* @__PURE__ */ number(), {
1572
+ fallback: 0.5
1573
+ })
1327
1574
  });
1328
1575
  const SceneSchema = /* @__PURE__ */ object({
1329
1576
  opacity: layerField(/* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ minValue(0), /* @__PURE__ */ maxValue(1)), {
@@ -1331,6 +1578,7 @@ const SceneSchema = /* @__PURE__ */ object({
1331
1578
  variable: true
1332
1579
  }),
1333
1580
  visible: layerField(/* @__PURE__ */ boolean(), { fallback: true, variable: true }),
1581
+ rotate: layerField(/* @__PURE__ */ number(), { fallback: null }),
1334
1582
  zIndex: layerField(/* @__PURE__ */ number(), { fallback: -1 })
1335
1583
  });
1336
1584
  const FillSchema = /* @__PURE__ */ object({
@@ -1340,14 +1588,22 @@ const FillSchema = /* @__PURE__ */ object({
1340
1588
  solidFill: layerField(/* @__PURE__ */ string(), { fallback: "#fff" }),
1341
1589
  imageFill: layerField(/* @__PURE__ */ string()),
1342
1590
  imageSize: layerField(/* @__PURE__ */ picklist(Object.keys(imagePaintScaleModes)), {
1343
- fallback: imagePaintScaleModes.Fill
1591
+ fallback: imagePaintScaleModes.Auto
1344
1592
  })
1345
1593
  });
1346
1594
  const BorderSchema = /* @__PURE__ */ object({
1347
1595
  borderType: layerField(/* @__PURE__ */ picklist(Object.keys(borderType)), {
1348
1596
  fallback: borderType.None
1349
1597
  }),
1350
- borderWidth: layerField(/* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ minValue(0)), { fallback: 0 }),
1598
+ borderWidth: layerField(/* @__PURE__ */ string(), {
1599
+ fallback: "1px",
1600
+ transform: (value) => {
1601
+ if (typeof value === "number") {
1602
+ return `${value}px`;
1603
+ }
1604
+ return value;
1605
+ }
1606
+ }),
1351
1607
  borderColor: layerField(/* @__PURE__ */ string(), { fallback: "#fff" })
1352
1608
  });
1353
1609
  const SizeSchema = /* @__PURE__ */ object({
@@ -1430,6 +1686,15 @@ const InteractionsSchema = /* @__PURE__ */ object({
1430
1686
  const CssOverrideSchema = /* @__PURE__ */ object({
1431
1687
  cssOverride: layerField(/* @__PURE__ */ string(), { fallback: "" })
1432
1688
  });
1689
+ const LinkSchema = /* @__PURE__ */ object({
1690
+ href: layerField(/* @__PURE__ */ string(), { fallback: null }),
1691
+ hrefNewTab: layerField(/* @__PURE__ */ boolean(), {
1692
+ fallback: true
1693
+ })
1694
+ // hrefTarget: layerField(v.picklist(Object.keys(linkTarget)), {
1695
+ // fallback: linkTarget._blank,
1696
+ // }),
1697
+ });
1433
1698
  /* @__PURE__ */ pipe(
1434
1699
  /* @__PURE__ */ object({
1435
1700
  name: layerField(/* @__PURE__ */ string(), { fallback: "Frame", overridable: false }),
@@ -1450,6 +1715,7 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1450
1715
  ...LayerSchema.entries,
1451
1716
  ...InteractionsSchema.entries,
1452
1717
  ...CssOverrideSchema.entries,
1718
+ ...LinkSchema.entries,
1453
1719
  overflow: OverflowSchema,
1454
1720
  borderRadius: BorderRadiusSchema
1455
1721
  })
@@ -1462,33 +1728,22 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1462
1728
  whiteSpace: layerField(/* @__PURE__ */ enum_(Object.keys(whiteSpace)), {
1463
1729
  fallback: whiteSpace.pre
1464
1730
  }),
1465
- variableContent: layerField(/* @__PURE__ */ string(), { fallback: null, variable: true }),
1731
+ textAlign: layerField(/* @__PURE__ */ string(), { fallback: "left" }),
1466
1732
  parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1467
- attributes: layerField(
1468
- /* @__PURE__ */ object({
1469
- fontSize: layerField(/* @__PURE__ */ string(), { fallback: "14px" }),
1470
- color: layerField(/* @__PURE__ */ string(), { fallback: "#000" }),
1471
- lineHeight: layerField(/* @__PURE__ */ string(), { fallback: "14px" }),
1472
- fontWeight: layerField(/* @__PURE__ */ string(), { fallback: "normal" }),
1473
- letterSpacing: layerField(/* @__PURE__ */ string(), { fallback: "0px" }),
1474
- textTransform: layerField(/* @__PURE__ */ string(), { fallback: "none" }),
1475
- textDecoration: layerField(/* @__PURE__ */ string(), { fallback: "none" }),
1476
- whiteSpace: layerField(/* @__PURE__ */ string(), { fallback: "pre" }),
1477
- textAlign: layerField(/* @__PURE__ */ string(), { fallback: "left" })
1478
- }),
1479
- { fallback: {} }
1480
- ),
1481
1733
  ...GraphFieldSchema.entries,
1482
1734
  ...OverridesSchema.entries,
1735
+ ...CssOverrideSchema.entries,
1483
1736
  ...PositionSchema.entries,
1484
1737
  ...SceneSchema.entries,
1485
- ...SizeSchema.entries
1738
+ ...SizeSchema.entries,
1739
+ ...InteractionsSchema.entries,
1740
+ ...LinkSchema.entries
1486
1741
  });
1487
1742
  /* @__PURE__ */ object({
1488
1743
  name: layerField(/* @__PURE__ */ string(), { fallback: "Fragment", overridable: false }),
1489
1744
  parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1490
1745
  horizontalGrow: layerField(/* @__PURE__ */ enum_(Object.keys(fragmentGrowingMode)), {
1491
- fallback: fragmentGrowingMode.auto,
1746
+ fallback: fragmentGrowingMode.fill,
1492
1747
  overridable: false
1493
1748
  }),
1494
1749
  verticalGrow: layerField(/* @__PURE__ */ enum_(Object.keys(fragmentGrowingMode)), {
@@ -1528,13 +1783,17 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1528
1783
  ...OverridesSchema.entries,
1529
1784
  ...PositionSchema.entries,
1530
1785
  ...SizeSchema.entries,
1531
- ...SceneSchema.entries
1786
+ ...SceneSchema.entries,
1787
+ ...InteractionsSchema.entries,
1788
+ ...LinkSchema.entries
1532
1789
  });
1533
1790
  /* @__PURE__ */ object({
1791
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1534
1792
  name: layerField(/* @__PURE__ */ string(), {
1535
1793
  fallback: "Number",
1536
1794
  overridable: false
1537
1795
  }),
1796
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1538
1797
  type: layerField(/* @__PURE__ */ literal(variableType.Number), {
1539
1798
  fallback: variableType.Number
1540
1799
  }),
@@ -1547,10 +1806,12 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1547
1806
  ...GraphFieldSchema.entries
1548
1807
  });
1549
1808
  /* @__PURE__ */ object({
1809
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1550
1810
  name: layerField(/* @__PURE__ */ string(), {
1551
1811
  fallback: "Boolean",
1552
1812
  overridable: false
1553
1813
  }),
1814
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1554
1815
  type: layerField(/* @__PURE__ */ literal(variableType.Boolean), {
1555
1816
  fallback: variableType.Boolean
1556
1817
  }),
@@ -1559,10 +1820,12 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1559
1820
  ...GraphFieldSchema.entries
1560
1821
  });
1561
1822
  /* @__PURE__ */ object({
1823
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1562
1824
  name: layerField(/* @__PURE__ */ string(), {
1563
1825
  fallback: "String",
1564
1826
  overridable: false
1565
1827
  }),
1828
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1566
1829
  type: layerField(/* @__PURE__ */ literal(variableType.Color), {
1567
1830
  fallback: variableType.Color
1568
1831
  }),
@@ -1572,6 +1835,7 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1572
1835
  ...GraphFieldSchema.entries
1573
1836
  });
1574
1837
  /* @__PURE__ */ object({
1838
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1575
1839
  name: layerField(/* @__PURE__ */ string(), {
1576
1840
  fallback: "String",
1577
1841
  overridable: false
@@ -1579,6 +1843,7 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1579
1843
  type: layerField(/* @__PURE__ */ literal(variableType.String), {
1580
1844
  fallback: variableType.String
1581
1845
  }),
1846
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1582
1847
  defaultValue: layerField(/* @__PURE__ */ string(), { fallback: "" }),
1583
1848
  required: layerField(/* @__PURE__ */ boolean(), { fallback: false }),
1584
1849
  placeholder: layerField(/* @__PURE__ */ string(), { fallback: "" }),
@@ -1586,10 +1851,12 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1586
1851
  ...GraphFieldSchema.entries
1587
1852
  });
1588
1853
  /* @__PURE__ */ object({
1854
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1589
1855
  name: layerField(/* @__PURE__ */ string(), {
1590
1856
  fallback: "Event",
1591
1857
  overridable: false
1592
1858
  }),
1859
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1593
1860
  type: layerField(/* @__PURE__ */ literal(variableType.Event), {
1594
1861
  fallback: variableType.Event
1595
1862
  }),
@@ -1600,36 +1867,394 @@ const CssOverrideSchema = /* @__PURE__ */ object({
1600
1867
  required: layerField(/* @__PURE__ */ boolean(), { fallback: false }),
1601
1868
  ...GraphFieldSchema.entries
1602
1869
  });
1603
- const findGroups = (state) => {
1604
- var _a;
1605
- const cache = (_a = state.$styleSheet) == null ? void 0 : _a.cache;
1606
- const fragments = Array.from(cache.keys()).filter(
1870
+ /* @__PURE__ */ object({
1871
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1872
+ name: layerField(/* @__PURE__ */ string(), {
1873
+ fallback: "Link",
1874
+ overridable: false
1875
+ }),
1876
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1877
+ type: layerField(/* @__PURE__ */ literal(variableType.Link), {
1878
+ fallback: variableType.Link
1879
+ }),
1880
+ defaultValue: layerField(/* @__PURE__ */ string(), { fallback: "" }),
1881
+ required: layerField(/* @__PURE__ */ boolean(), { fallback: false }),
1882
+ ...GraphFieldSchema.entries
1883
+ });
1884
+ /* @__PURE__ */ object({
1885
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1886
+ name: layerField(/* @__PURE__ */ string(), {
1887
+ fallback: "Option",
1888
+ overridable: false
1889
+ }),
1890
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1891
+ type: layerField(/* @__PURE__ */ literal(variableType.Enum), {
1892
+ fallback: variableType.Enum
1893
+ }),
1894
+ defaultValue: layerField(/* @__PURE__ */ string(), { fallback: "" }),
1895
+ required: layerField(/* @__PURE__ */ boolean(), { fallback: false }),
1896
+ cases: layerField(
1897
+ /* @__PURE__ */ array(
1898
+ /* @__PURE__ */ object({
1899
+ id: /* @__PURE__ */ string(),
1900
+ name: /* @__PURE__ */ string()
1901
+ })
1902
+ ),
1903
+ { fallback: [] }
1904
+ ),
1905
+ ...GraphFieldSchema.entries
1906
+ });
1907
+ /* @__PURE__ */ object({
1908
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1909
+ name: layerField(/* @__PURE__ */ string(), {
1910
+ fallback: "Object",
1911
+ overridable: false
1912
+ }),
1913
+ type: layerField(/* @__PURE__ */ literal(variableType.Object), {
1914
+ fallback: variableType.Object
1915
+ }),
1916
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1917
+ defaultValue: layerField(/* @__PURE__ */ object({}), { fallback: {} }),
1918
+ fields: layerField(/* @__PURE__ */ record(/* @__PURE__ */ string(), linkValidator), { fallback: {} }),
1919
+ required: layerField(/* @__PURE__ */ boolean(), { fallback: false }),
1920
+ ...GraphFieldSchema.entries
1921
+ });
1922
+ /* @__PURE__ */ object({
1923
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1924
+ name: layerField(/* @__PURE__ */ string(), {
1925
+ fallback: "Image",
1926
+ overridable: false
1927
+ }),
1928
+ type: layerField(/* @__PURE__ */ literal(variableType.Image), {
1929
+ fallback: variableType.Image
1930
+ }),
1931
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1932
+ defaultValue: layerField(/* @__PURE__ */ string(), { fallback: null }),
1933
+ required: layerField(/* @__PURE__ */ boolean(), { fallback: false }),
1934
+ imageSize: layerField(/* @__PURE__ */ picklist(Object.keys(imagePaintScaleModes)), {
1935
+ fallback: imagePaintScaleModes.Auto
1936
+ }),
1937
+ ...GraphFieldSchema.entries
1938
+ });
1939
+ /* @__PURE__ */ pipe(
1940
+ /* @__PURE__ */ object({
1941
+ name: layerField(/* @__PURE__ */ string(), {
1942
+ fallback: "Collection",
1943
+ overridable: false
1944
+ }),
1945
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1946
+ source: layerField(linkValidator, {}),
1947
+ ...ChildrenSchema.entries,
1948
+ ...GraphFieldSchema.entries,
1949
+ ...OverridesSchema.entries,
1950
+ ...PositionSchema.entries,
1951
+ ...SceneSchema.entries,
1952
+ ...FillSchema.entries,
1953
+ ...BorderSchema.entries,
1954
+ ...SizeSchema.entries,
1955
+ ...LayerSchema.entries,
1956
+ ...InteractionsSchema.entries,
1957
+ ...CssOverrideSchema.entries,
1958
+ ...LinkSchema.entries
1959
+ })
1960
+ );
1961
+ /* @__PURE__ */ object({
1962
+ nodePropertyControlReference: layerField(/* @__PURE__ */ string(), { fallback: null }),
1963
+ name: layerField(/* @__PURE__ */ string(), {
1964
+ fallback: "Collection",
1965
+ overridable: false
1966
+ }),
1967
+ type: layerField(/* @__PURE__ */ literal(variableType.Array), {
1968
+ fallback: variableType.Array
1969
+ }),
1970
+ parent: layerField(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), { overridable: false }),
1971
+ defaultValue: layerField(/* @__PURE__ */ array(/* @__PURE__ */ any()), { fallback: [] }),
1972
+ definition: layerField(linkValidator, { fallback: null }),
1973
+ required: layerField(/* @__PURE__ */ boolean(), { fallback: false }),
1974
+ ...GraphFieldSchema.entries
1975
+ });
1976
+ const BASE_HEADERS = {
1977
+ "Content-Type": "application/json"
1978
+ };
1979
+ const createFetcher = (baseUrl, defaultHeaders = {}) => {
1980
+ const cache2 = /* @__PURE__ */ new Map();
1981
+ const inflightRequests = /* @__PURE__ */ new Map();
1982
+ const getCacheKey = (query2, variables, options) => JSON.stringify({ query: query2, variables, options });
1983
+ const query = async (query2, variables = {}, options = {}) => {
1984
+ const cacheKey = getCacheKey(query2, variables, options);
1985
+ if (cache2.has(cacheKey)) {
1986
+ return cache2.get(cacheKey);
1987
+ }
1988
+ if (inflightRequests.has(cacheKey)) {
1989
+ return inflightRequests.get(cacheKey);
1990
+ }
1991
+ const request = fetch(baseUrl, {
1992
+ ...options,
1993
+ method: "POST",
1994
+ body: JSON.stringify({ query: query2, variables }),
1995
+ credentials: "include",
1996
+ headers: {
1997
+ ...BASE_HEADERS,
1998
+ ...defaultHeaders,
1999
+ ...options.headers
2000
+ }
2001
+ }).then(async (res) => {
2002
+ if (!res.ok) throw new Error(`Fetch error: ${res.status}`);
2003
+ const data = await res.json();
2004
+ if (!query2.includes("mutation")) {
2005
+ cache2.set(cacheKey, data);
2006
+ }
2007
+ return data;
2008
+ }).finally(() => {
2009
+ inflightRequests.delete(cacheKey);
2010
+ });
2011
+ inflightRequests.set(cacheKey, request);
2012
+ return request;
2013
+ };
2014
+ const invalidate = (endpoint, options) => {
2015
+ cache2.delete(getCacheKey(endpoint, options));
2016
+ };
2017
+ const clearCache = () => cache2.clear();
2018
+ return { query, invalidate, clearCache };
2019
+ };
2020
+ const getFragmentQuery = (fragmentId, isSelf) => {
2021
+ return {
2022
+ query: isSelf ? `
2023
+ query FragmentDocument($fragmentId: Int!) {
2024
+ fragment(fragmentIds: [$fragmentId]) {
2025
+ id
2026
+ document
2027
+ linkedFragments {
2028
+ id
2029
+ document
2030
+ }
2031
+ }
2032
+ }
2033
+ ` : `
2034
+ query FragmentDocument($fragmentId: Int!) {
2035
+ clientFragment(fragmentId: $fragmentId) {
2036
+ id
2037
+ document
2038
+ linkedFragments {
2039
+ id
2040
+ document
2041
+ }
2042
+ }
2043
+ }`,
2044
+ variables: {
2045
+ fragmentId
2046
+ },
2047
+ _type: null
2048
+ };
2049
+ };
2050
+ var isObject = (input) => {
2051
+ return typeof input === "object" && input !== null && !Array.isArray(input);
2052
+ };
2053
+ var isEmptyValue = (value) => !value && (value === null || value === void 0);
2054
+ var isValue = (value) => !isEmptyValue(value);
2055
+ var createConstants = (...constants) => {
2056
+ return constants.reduce((acc, constant) => {
2057
+ acc[constant] = constant;
2058
+ return acc;
2059
+ }, {});
2060
+ };
2061
+ var isBrowser_default = typeof window !== "undefined";
2062
+ var getKey = (v) => isKey(v) ? v.slice(1) : null;
2063
+ var isKey = (v) => typeof v === "string" && v.startsWith("$");
2064
+ function hashGenerator(layerKey) {
2065
+ let hash = 0;
2066
+ for (let i2 = 0; i2 < layerKey.length; i2++) {
2067
+ hash = (hash << 5) - hash + layerKey.charCodeAt(i2);
2068
+ hash |= 0;
2069
+ }
2070
+ const raw = Math.abs(hash).toString(36);
2071
+ return /^[0-9]/.test(raw) ? `h${raw}` : raw;
2072
+ }
2073
+ const fetchBeacon = (baseUrl) => {
2074
+ const sender = isBrowser_default && typeof (navigator == null ? void 0 : navigator.sendBeacon) === "function" ? navigator.sendBeacon : () => null;
2075
+ const sendBeacon = (data) => {
2076
+ try {
2077
+ sender("/graphql", "test");
2078
+ } catch (e) {
2079
+ console.error(e);
2080
+ }
2081
+ };
2082
+ return {
2083
+ sendBeacon
2084
+ };
2085
+ };
2086
+ const getAreaListQuery = (areaCodes) => {
2087
+ return {
2088
+ query: `query($areaCodes: [String!]!) {
2089
+ clientAreas(areaCodes: $areaCodes) {
2090
+ variant {
2091
+ fragment {
2092
+ props
2093
+ fragment {
2094
+ id
2095
+ document
2096
+ linkedFragments {
2097
+ id
2098
+ document
2099
+ }
2100
+ }
2101
+ }
2102
+ }
2103
+ }
2104
+ }`,
2105
+ variables: {
2106
+ areaCodes
2107
+ }
2108
+ };
2109
+ };
2110
+ const fetchPlugin = (state) => {
2111
+ var _a, _b, _c;
2112
+ const isSelf = ((_a = state == null ? void 0 : state.env) == null ? void 0 : _a.isSelf) ?? false;
2113
+ const url = (_b = state == null ? void 0 : state.env) == null ? void 0 : _b.backendEndpoint;
2114
+ const apiToken = (_c = state == null ? void 0 : state.env) == null ? void 0 : _c.apiToken;
2115
+ const fetcher = createFetcher(url, {
2116
+ Authorization: `Bearer ${apiToken}`
2117
+ });
2118
+ const beaconFetcher = fetchBeacon();
2119
+ const queryFragment = async (fragmentId) => {
2120
+ var _a2;
2121
+ if (!apiToken || !fragmentId) return null;
2122
+ if (state.$fetch.cacheDocuments.has(fragmentId)) {
2123
+ return state.$fetch.cacheDocuments.get(fragmentId);
2124
+ }
2125
+ const fragmentQuery = getFragmentQuery(fragmentId, isSelf);
2126
+ const response = await fetcher.query(
2127
+ fragmentQuery.query,
2128
+ fragmentQuery.variables,
2129
+ { referrerPolicy: "unsafe-url" }
2130
+ );
2131
+ let fragment = null;
2132
+ if (!!(response == null ? void 0 : response.data) && "clientFragment" in response.data) {
2133
+ fragment = response.data.clientFragment;
2134
+ }
2135
+ if (!!(response == null ? void 0 : response.data) && "fragment" in response.data) {
2136
+ fragment = (_a2 = response.data.fragment) == null ? void 0 : _a2.at(0);
2137
+ }
2138
+ const fragmentDocument = fragment == null ? void 0 : fragment.document;
2139
+ if (!fragmentDocument) {
2140
+ console.error("Empty document");
2141
+ return null;
2142
+ }
2143
+ if (fragment) {
2144
+ state.$fetch.cacheDocuments.set(fragmentId, fragmentDocument);
2145
+ if (Array.isArray(fragment.linkedFragments)) {
2146
+ fragment.linkedFragments.forEach(
2147
+ (linkedFragment) => state.$fetch.cacheDocuments.set(
2148
+ linkedFragment.id,
2149
+ linkedFragment.document
2150
+ )
2151
+ );
2152
+ }
2153
+ return fragmentDocument;
2154
+ }
2155
+ return null;
2156
+ };
2157
+ const queryArea = async (areaCode) => {
2158
+ return queryAreaList([areaCode]).then((res) => res == null ? void 0 : res.at(0));
2159
+ };
2160
+ const queryAreaList = async (areaCodes) => {
2161
+ var _a2;
2162
+ if (!apiToken || !areaCodes) return null;
2163
+ const nonLoadedAreas = areaCodes.filter(
2164
+ (code) => !state.$fetch.cacheAreaDocuments.has(code)
2165
+ );
2166
+ if (!nonLoadedAreas.length) {
2167
+ return areaCodes.map(state.$fetch.cacheAreaDocuments.get);
2168
+ }
2169
+ const areaQuery = getAreaListQuery(areaCodes);
2170
+ const response = await fetcher.query(
2171
+ areaQuery.query,
2172
+ areaQuery.variables,
2173
+ { referrerPolicy: "unsafe-url" }
2174
+ );
2175
+ const areas = (_a2 = response == null ? void 0 : response.data) == null ? void 0 : _a2.clientAreas;
2176
+ if (areas) {
2177
+ areas.forEach((area, index2) => {
2178
+ const areaCode = areaCodes == null ? void 0 : areaCodes.at(index2);
2179
+ state.$fetch.cacheDocuments.set(
2180
+ area.variant.fragment.fragment.id,
2181
+ area.variant.fragment.fragment.document
2182
+ );
2183
+ if (Array.isArray(area.variant.fragment.fragment.linkedFragments)) {
2184
+ area.variant.fragment.fragment.linkedFragments.forEach(
2185
+ (linkedFragment) => state.$fetch.cacheDocuments.set(
2186
+ linkedFragment.id,
2187
+ linkedFragment.document
2188
+ )
2189
+ );
2190
+ }
2191
+ const entity = {
2192
+ fragmentId: area.variant.fragment.fragment.id,
2193
+ props: area.variant.fragment.props
2194
+ };
2195
+ state.$fetch.cacheAreaDocuments.set(areaCode, entity);
2196
+ });
2197
+ return areaCodes.map((code) => state.$fetch.cacheAreaDocuments.get(code));
2198
+ }
2199
+ return null;
2200
+ };
2201
+ state.$fetch = {
2202
+ cacheDocuments: /* @__PURE__ */ new Map(),
2203
+ cacheAreaDocuments: /* @__PURE__ */ new Map(),
2204
+ queryFragment,
2205
+ queryArea,
2206
+ queryAreaList,
2207
+ query: fetcher.query,
2208
+ sendBeacon: beaconFetcher.sendBeacon,
2209
+ readFragment: (fragmentId) => state.$fetch.cacheDocuments.get(fragmentId) ?? null,
2210
+ readArea: (areaCode) => state.$fetch.cacheAreaDocuments.get(areaCode) ?? null
2211
+ };
2212
+ };
2213
+ const getAllChildren = (layerResolver, layerKey, acc = []) => {
2214
+ var _a;
2215
+ const layer = layerResolver(layerKey) ?? {};
2216
+ if (acc.length === 0) {
2217
+ acc.push(keyOfEntity(layerKey));
2218
+ }
2219
+ (_a = layer == null ? void 0 : layer.children) == null ? void 0 : _a.forEach((child) => {
2220
+ if (child) {
2221
+ acc.push(keyOfEntity(child));
2222
+ getAllChildren(layerResolver, child, acc);
2223
+ }
2224
+ });
2225
+ return acc;
2226
+ };
2227
+ const buildCssBlock = (block) => {
2228
+ if (!block || block.css === "") return "";
2229
+ return `.${block.hash} {${block.css}}`;
2230
+ };
2231
+ const findGroups = (styles, layerResolver) => {
2232
+ const fragments = Object.keys(styles).filter(
1607
2233
  (key) => key == null ? void 0 : key.includes(index.nodes.Fragment)
1608
- ) ?? [];
2234
+ );
1609
2235
  const createFragmentSlice = (fragmentLayerKey) => {
1610
- var _a2;
1611
- const rootLayer = (_a2 = cache.get(fragmentLayerKey)) == null ? void 0 : _a2.layer;
2236
+ const rootLayer = layerResolver(fragmentLayerKey);
1612
2237
  const breakpoints = ((rootLayer == null ? void 0 : rootLayer.children) ?? []).map(
1613
- (child) => {
1614
- var _a3;
1615
- return (_a3 = cache.get(child)) == null ? void 0 : _a3.layer;
1616
- }
2238
+ (child) => layerResolver(child)
1617
2239
  );
1618
2240
  const primaryBreakpoint = breakpoints.find(
1619
2241
  (breakpoint) => breakpoint == null ? void 0 : breakpoint.isPrimary
1620
2242
  );
1621
- const smaller = breakpoints.filter((f) => !!f && (f == null ? void 0 : f.width) < (primaryBreakpoint == null ? void 0 : primaryBreakpoint.width)).sort((a2, b2) => b2.width - a2.width);
1622
- const larger = breakpoints.filter((f) => !!f && (f == null ? void 0 : f.width) > (primaryBreakpoint == null ? void 0 : primaryBreakpoint.width)).sort((a2, b2) => a2.width - b2.width);
2243
+ const smaller = breakpoints.filter((f2) => !!f2 && (f2 == null ? void 0 : f2.width) < (primaryBreakpoint == null ? void 0 : primaryBreakpoint.width)).sort((a2, b) => b.width - a2.width);
2244
+ const larger = breakpoints.filter((f2) => !!f2 && (f2 == null ? void 0 : f2.width) > (primaryBreakpoint == null ? void 0 : primaryBreakpoint.width)).sort((a2, b) => a2.width - b.width);
1623
2245
  return {
2246
+ fragmentLayerKey,
1624
2247
  fragment: rootLayer,
1625
- primary: primaryBreakpoint,
2248
+ primary: `${primaryBreakpoint._type}:${primaryBreakpoint == null ? void 0 : primaryBreakpoint._id}`,
1626
2249
  smaller: smaller ?? [],
1627
2250
  larger: larger ?? []
1628
2251
  };
1629
2252
  };
1630
2253
  return fragments.map(createFragmentSlice).filter((slice) => slice.primary);
1631
2254
  };
1632
- const toCSS = (styles) => Object.entries(styles).filter(([, value]) => isValue(value) && value !== "").map(
2255
+ const toCSS = (styles) => Object.entries(styles).filter(
2256
+ ([key, value]) => isValue(value) && value !== "" && !["_type", "_id"].includes(key)
2257
+ ).map(
1633
2258
  ([key, value]) => `${key.replace(/([A-Z])/g, "-$1").toLowerCase()}: ${value};`
1634
2259
  ).join("\n");
1635
2260
  function compareRules(prev = {}, next = {}) {
@@ -1641,92 +2266,216 @@ function compareRules(prev = {}, next = {}) {
1641
2266
  }
1642
2267
  return diff;
1643
2268
  }
1644
- const makeCss = (state) => (entity) => {
1645
- var _a, _b, _c, _d, _e;
1646
- const cache = (_a = state.$styleSheet) == null ? void 0 : _a.cache;
1647
- const layerKey = state.keyOfEntity(entity);
1648
- const cacheLayer = cache.get(layerKey);
1649
- const isPrimary = !((_b = cacheLayer == null ? void 0 : cacheLayer.layer) == null ? void 0 : _b.overrideFrom);
1650
- const layerHash = hashGenerator(
1651
- isPrimary ? layerKey : getKey((_c = cacheLayer == null ? void 0 : cacheLayer.layer) == null ? void 0 : _c.overrideFrom)
1652
- );
1653
- const layerCss = cacheLayer == null ? void 0 : cacheLayer.styles;
1654
- const overriderLayerCss = ((_e = cache.get(getKey((_d = cacheLayer == null ? void 0 : cacheLayer.layer) == null ? void 0 : _d.overrideFrom))) == null ? void 0 : _e.styles) ?? {};
2269
+ const makeCss = (styles, layerResolver) => (layerKey) => {
2270
+ const cacheLayer = layerResolver(layerKey);
2271
+ const isPrimary = !(cacheLayer == null ? void 0 : cacheLayer.overrideFrom);
2272
+ const overrideFromKey = (cacheLayer == null ? void 0 : cacheLayer.overrideFrom) ? String(getKey(cacheLayer == null ? void 0 : cacheLayer.overrideFrom)) : void 0;
2273
+ const layerHash = hashGenerator(isPrimary ? layerKey : overrideFromKey);
2274
+ const layerCss = styles == null ? void 0 : styles[layerKey];
2275
+ const overriderLayerCss = overrideFromKey ? (styles == null ? void 0 : styles[overrideFromKey]) ?? {} : {};
1655
2276
  const resultCssRules = compareRules(overriderLayerCss, layerCss);
2277
+ const cssOverride = (cacheLayer == null ? void 0 : cacheLayer.cssOverride) ?? "";
1656
2278
  return {
1657
2279
  hash: layerHash,
1658
- css: toCSS(resultCssRules)
2280
+ css: toCSS(resultCssRules) + cssOverride
1659
2281
  };
1660
2282
  };
1661
- const getAllChildren = (state, start, acc = []) => {
1662
- var _a, _b;
1663
- const cache = (_a = state.$styleSheet) == null ? void 0 : _a.cache;
1664
- const layerKey = state.keyOfEntity(start);
1665
- const { layer } = cache.get(layerKey) ?? {};
1666
- if (acc.length === 0) {
1667
- acc.push(layerKey);
2283
+ const autoInjector = (key, state, graphKey, transformStyles) => {
2284
+ const removeStyle = () => {
2285
+ if (!isBrowser_default) return;
2286
+ const el = document.getElementById(key);
2287
+ if (el) el.remove();
2288
+ };
2289
+ const injectStyle = (styles) => {
2290
+ if (!isBrowser_default) return;
2291
+ if (!styles) {
2292
+ removeStyle();
2293
+ return;
2294
+ }
2295
+ const existing = document.getElementById(key);
2296
+ if (existing && existing.tagName === "STYLE") {
2297
+ existing.textContent = styles;
2298
+ return;
2299
+ }
2300
+ if (existing) existing.remove();
2301
+ const style = document.createElement("style");
2302
+ style.id = key;
2303
+ style.textContent = styles;
2304
+ document.head.appendChild(style);
2305
+ };
2306
+ let isMounted = false;
2307
+ let pendingStyles = "";
2308
+ state.subscribe(
2309
+ graphKey,
2310
+ (next) => {
2311
+ const styles = (transformStyles == null ? void 0 : transformStyles(next)) ?? (next == null ? void 0 : next.styles) ?? [];
2312
+ const resultStyle = styles.join("\n");
2313
+ pendingStyles = resultStyle;
2314
+ if (isMounted) {
2315
+ injectStyle(resultStyle);
2316
+ }
2317
+ },
2318
+ { directChangesOnly: true }
2319
+ );
2320
+ const mount = () => {
2321
+ isMounted = true;
2322
+ if (pendingStyles) {
2323
+ injectStyle(pendingStyles);
2324
+ } else {
2325
+ removeStyle();
2326
+ }
2327
+ };
2328
+ const unmount = () => {
2329
+ isMounted = false;
2330
+ removeStyle();
2331
+ };
2332
+ return { mount, unmount };
2333
+ };
2334
+ function generatePrimaryCssBlocks(layerResolver, group, cssMaker) {
2335
+ const children = getAllChildren(layerResolver, group.primary);
2336
+ return children.map(cssMaker).map(buildCssBlock);
2337
+ }
2338
+ function generateSmallerCssBlocks(layerResolver, group, cssMaker) {
2339
+ return group.smaller.map(
2340
+ (smallerLayer, index2, arr) => {
2341
+ const smallerChildren = getAllChildren(layerResolver, smallerLayer);
2342
+ const smallerCssBlocks = smallerChildren.map(cssMaker);
2343
+ const max = index2 === 0 ? group.primary.width - 1 : arr[index2 - 1].width;
2344
+ return `@container (max-width: ${max}px) {${smallerCssBlocks.map(buildCssBlock).join("")}}`;
2345
+ }
2346
+ );
2347
+ }
2348
+ function generateLargerCssBlocks(layerResolver, group, cssMaker) {
2349
+ return group.larger.map(
2350
+ (largerLayer, index2, arr) => {
2351
+ const largerChildren = getAllChildren(layerResolver, largerLayer);
2352
+ const largerCssBlocks = largerChildren.map(cssMaker);
2353
+ const min = largerLayer.width;
2354
+ const max = index2 < arr.length - 1 ? arr[index2 + 1].width - 1 : null;
2355
+ const containerQuery = max ? `@container (min-width: ${min}px) and (max-width: ${max}px)` : `@container (min-width: ${min}px)`;
2356
+ return `${containerQuery} {${largerCssBlocks.map(buildCssBlock).join("")}}`;
2357
+ }
2358
+ );
2359
+ }
2360
+ function extractStyleSheet(styles, layerResolver) {
2361
+ const [group] = findGroups(styles, layerResolver);
2362
+ if (!group) {
2363
+ return [];
1668
2364
  }
1669
- (_b = layer == null ? void 0 : layer.children) == null ? void 0 : _b.forEach((child) => {
1670
- acc.push(child);
1671
- getAllChildren(state, child, acc);
2365
+ const cssMaker = makeCss(styles, layerResolver);
2366
+ const fragmentCssRules = [];
2367
+ fragmentCssRules.push(buildCssBlock(cssMaker(group.fragmentLayerKey)));
2368
+ const primaryStyles = generatePrimaryCssBlocks(
2369
+ layerResolver,
2370
+ group,
2371
+ cssMaker
2372
+ );
2373
+ fragmentCssRules.push(...primaryStyles);
2374
+ fragmentCssRules.push(
2375
+ ...generateSmallerCssBlocks(layerResolver, group, cssMaker)
2376
+ );
2377
+ fragmentCssRules.push(
2378
+ ...generateLargerCssBlocks(layerResolver, group, cssMaker)
2379
+ );
2380
+ return fragmentCssRules;
2381
+ }
2382
+ const fragmentStylesheetPlugin = (state) => {
2383
+ const KEY = `${PLUGIN_TYPES.FragmentStylesheet}:root`;
2384
+ const addStyle = (layerKey, style) => {
2385
+ state.mutate(KEY, {
2386
+ styles: {
2387
+ [layerKey]: style
2388
+ }
2389
+ });
2390
+ };
2391
+ state.mutate(KEY, {
2392
+ styles: {}
1672
2393
  });
1673
- return acc;
1674
- };
1675
- const buildCssBlock = (block) => {
1676
- if (!block || block.css === "") return "";
1677
- return `.${block.hash} {${block.css}}`;
2394
+ const fragmentStyleInjector = autoInjector(state.key, state, KEY, (graph) => {
2395
+ return extractStyleSheet(graph.styles, state.resolve);
2396
+ });
2397
+ const destroyStyles = () => {
2398
+ state.mutate(
2399
+ KEY,
2400
+ {
2401
+ styles: {}
2402
+ },
2403
+ { replace: true }
2404
+ );
2405
+ fragmentStyleInjector.unmount();
2406
+ };
2407
+ state.$styleSheet = {
2408
+ key: KEY,
2409
+ addStyle,
2410
+ mount: fragmentStyleInjector.mount,
2411
+ unmount: destroyStyles,
2412
+ extract: (withTag) => {
2413
+ var _a;
2414
+ const graph = state.resolve(KEY);
2415
+ const styles = extractStyleSheet(graph == null ? void 0 : graph.styles, state.resolve);
2416
+ const resultStyle = styles.join("\n");
2417
+ if (withTag) {
2418
+ const id = state.entityOfKey((_a = state.$fragment) == null ? void 0 : _a.root);
2419
+ return `<style id="fragment-${id._id}">${resultStyle}</style>`;
2420
+ }
2421
+ return resultStyle;
2422
+ }
2423
+ };
2424
+ return state;
1678
2425
  };
1679
- const styleSheetPlugin = (state) => {
1680
- const extractStyleSheet = () => {
1681
- const fragments = findGroups(state);
1682
- const cssMaker = makeCss(state);
1683
- const fragmentsStyle = fragments.map((group) => {
1684
- const fragmentCssRules = [];
1685
- fragmentCssRules.push(buildCssBlock(cssMaker(group.fragment)));
1686
- const children = getAllChildren(state, group.primary);
1687
- const primaryCssBlocks = children.map(cssMaker);
1688
- primaryCssBlocks.forEach((block) => {
1689
- fragmentCssRules.push(buildCssBlock(block));
1690
- });
1691
- group.smaller.forEach((smallerLayer, index2, arr) => {
1692
- const smallerChildren = getAllChildren(state, smallerLayer);
1693
- const smallerCssBlocks = smallerChildren.map(cssMaker);
1694
- const max = index2 === 0 ? group.primary.width - 1 : arr[index2 - 1].width;
1695
- fragmentCssRules.push(
1696
- `@container (max-width: ${max}px) {${smallerCssBlocks.map(buildCssBlock).join("")}}`
1697
- );
1698
- });
1699
- group.larger.forEach((largerLayer, index2, arr) => {
1700
- const largerChildren = getAllChildren(state, largerLayer);
1701
- const largerCssBlocks = largerChildren.map((l) => cssMaker(l, 123));
1702
- const min = largerLayer.width;
1703
- const max = index2 < arr.length - 1 ? arr[index2 + 1].width - 1 : null;
1704
- const containerQuery = max ? `@container (min-width: ${min}px) and (max-width: ${max}px)` : `@container (min-width: ${min}px)`;
1705
- fragmentCssRules.push(
1706
- `${containerQuery} {${largerCssBlocks.map(buildCssBlock).join("")}}`
1707
- );
1708
- });
1709
- fragmentCssRules.push(`[data-key^="Text"] { p {margin: 0;} }`);
1710
- return {
1711
- fragment: state.keyOfEntity(group.fragment),
1712
- styles: fragmentCssRules
1713
- };
2426
+ const globalCss = '[data-key^="Fragment"] {\n [data-key^="Text"] {\n p {\n margin: 0;\n font-size: 14px;\n color: #000;\n font-weight: 400;\n }\n }\n\n /* 1. Use a more-intuitive box-sizing model */\n\n *, *::before, *::after {\n box-sizing: border-box;\n }\n\n /* 2. Remove default margin */\n\n * {\n margin: 0;\n }\n\n /* 3. Enable keyword animations */\n @media (prefers-reduced-motion: no-preference) {\n html {\n interpolate-size: allow-keywords;\n }\n }\n\n body {\n /* 4. Add accessible line-height */\n line-height: 1.5;\n /* 5. Improve text rendering */\n -webkit-font-smoothing: antialiased;\n }\n\n /* 6. Improve media defaults */\n\n img, picture, video, canvas, svg {\n display: block;\n max-width: 100%;\n }\n\n /* 7. Inherit fonts for form controls */\n\n input, button, textarea, select {\n font: inherit;\n }\n\n /* 8. Avoid text overflows */\n\n p, h1, h2, h3, h4, h5, h6 {\n overflow-wrap: break-word;\n }\n\n /*\n 10. Create a root stacking context\n */\n\n #root, #__next {\n isolation: isolate;\n }\n\n a {\n text-decoration: none;\n }\n}\n';
2427
+ const globalStylesheetPlugin = (state) => {
2428
+ if (!("$fragments" in state)) {
2429
+ throw new Error("GlobalStylesheetPlugin need $fragments plugin");
2430
+ }
2431
+ const KEY = `${PLUGIN_TYPES.GlobalStylesheet}:root`;
2432
+ const addStyle = (style) => {
2433
+ state.mutate(KEY, {
2434
+ styles: [style]
1714
2435
  });
1715
- return fragmentsStyle;
1716
2436
  };
1717
- state.$styleSheet = {
1718
- cache: /* @__PURE__ */ new Map(),
1719
- addStyle: (layerKey, styles, layer) => {
1720
- var _a, _b;
1721
- return (_b = (_a = state.$styleSheet) == null ? void 0 : _a.cache) == null ? void 0 : _b.set(layerKey, { styles, layer });
1722
- },
1723
- extract: extractStyleSheet
2437
+ state.mutate({
2438
+ _type: PLUGIN_TYPES.GlobalStylesheet,
2439
+ _id: "root",
2440
+ styles: []
2441
+ });
2442
+ const globalStyleInjector = autoInjector("global", state, KEY);
2443
+ state.$globalStylesheet = {
2444
+ key: KEY,
2445
+ addStyle,
2446
+ mount: globalStyleInjector.mount,
2447
+ unmount: globalStyleInjector.unmount,
2448
+ extractStyles: () => {
2449
+ const allFragments = state.$fragments.getManagers();
2450
+ const styles = Object.entries(allFragments).filter(([, value]) => !!(value == null ? void 0 : value.resolve)).map(([, manager]) => manager.$styleSheet.extract(true));
2451
+ return styles.join("");
2452
+ }
1724
2453
  };
2454
+ addStyle(globalCss);
2455
+ globalStyleInjector.mount();
2456
+ return state;
1725
2457
  };
1726
- const fragmentsPlugin = (state) => {
2458
+ const scopesPlugin = (state) => {
2459
+ const scopesMap = /* @__PURE__ */ new Map();
2460
+ const registerScope = (layerKey, scopeValue) => {
2461
+ scopesMap.set(layerKey, scopeValue);
2462
+ };
2463
+ state.$scopes = {
2464
+ scopes: scopesMap,
2465
+ registerScope
2466
+ };
2467
+ return state;
2468
+ };
2469
+ const fragmentsPlugin = (options) => (state) => {
2470
+ const plugins = (options == null ? void 0 : options.plugins) ?? [];
1727
2471
  const createFragmentManager = (fragmentId, initialDocument = {}) => {
1728
2472
  var _a, _b;
1729
2473
  if (!fragmentId || !initialDocument) return null;
2474
+ const fragmentLayerId = (initialDocument == null ? void 0 : initialDocument._type) === index.nodes.Fragment ? initialDocument == null ? void 0 : initialDocument._id : null;
2475
+ if (!fragmentLayerId) {
2476
+ console.error("Cannot find fragment layer id");
2477
+ return;
2478
+ }
1730
2479
  const cacheManager = (_b = (_a = state.resolve(state.$fragments.key)) == null ? void 0 : _a.managers) == null ? void 0 : _b[fragmentId];
1731
2480
  if (cacheManager) {
1732
2481
  return cacheManager;
@@ -1739,21 +2488,33 @@ const fragmentsPlugin = (state) => {
1739
2488
  _type: "Spring",
1740
2489
  _id: "root"
1741
2490
  };
1742
- const manager = it({
2491
+ const manager = createState({
1743
2492
  _type: "FragmentManager",
1744
2493
  _id: fragmentId,
1745
2494
  initialState: initialDocument,
1746
2495
  plugins: [
1747
2496
  (state2) => {
1748
2497
  state2.$fragment = {
1749
- root: `${index.nodes.Fragment}:${fragmentId}`,
2498
+ root: `${index.nodes.Fragment}:${fragmentLayerId}`,
1750
2499
  temp: "Temp:root"
1751
2500
  };
1752
2501
  },
1753
2502
  // cssPlugin,
1754
- styleSheetPlugin
2503
+ fragmentStylesheetPlugin,
2504
+ scopesPlugin,
2505
+ ...plugins
1755
2506
  ],
1756
- skip: [b, a, isKey]
2507
+ skip: [
2508
+ g,
2509
+ f,
2510
+ isKey,
2511
+ u([
2512
+ ...Object.keys(index.nodes),
2513
+ "Temp",
2514
+ "Spring",
2515
+ PLUGIN_TYPES.FragmentStylesheet
2516
+ ])
2517
+ ]
1757
2518
  });
1758
2519
  manager.mutate(tempGraph);
1759
2520
  manager.mutate(springGraph);
@@ -1772,13 +2533,13 @@ const fragmentsPlugin = (state) => {
1772
2533
  return (_a = state.resolve(state.$fragments.key)) == null ? void 0 : _a.managers;
1773
2534
  };
1774
2535
  state.$fragments = {
1775
- key: `FragmentsPlugin:root`,
2536
+ key: `${PLUGIN_TYPES.FragmentsPlugin}:root`,
1776
2537
  createFragmentManager,
1777
2538
  getManager,
1778
2539
  getManagers
1779
2540
  };
1780
2541
  state.mutate({
1781
- _type: "FragmentsPlugin",
2542
+ _type: PLUGIN_TYPES.FragmentsPlugin,
1782
2543
  _id: "root",
1783
2544
  managers: {}
1784
2545
  });
@@ -1787,76 +2548,255 @@ const fragmentsPlugin = (state) => {
1787
2548
  const addClientMetric = `mutation AddClientMetric($type: ClientMetricType!, $value: String) {
1788
2549
  addClientMetric(metric: {metricType: $type, metricValue: $value})
1789
2550
  }`;
1790
- const types = createConstants$1(
2551
+ const pendingPixels = /* @__PURE__ */ new Set();
2552
+ const sendWithImage = (url) => {
2553
+ try {
2554
+ const pixel = new Image();
2555
+ pixel.referrerPolicy = "no-referrer";
2556
+ const handleCleanup = () => {
2557
+ pixel.removeEventListener("load", handleCleanup);
2558
+ pixel.removeEventListener("error", handleCleanup);
2559
+ pendingPixels.delete(pixel);
2560
+ };
2561
+ pixel.addEventListener("load", handleCleanup, { once: true });
2562
+ pixel.addEventListener("error", handleCleanup, { once: true });
2563
+ pendingPixels.add(pixel);
2564
+ pixel.src = url;
2565
+ } catch {
2566
+ }
2567
+ };
2568
+ const sendWithFetch = (url) => {
2569
+ if (typeof fetch !== "function") {
2570
+ return false;
2571
+ }
2572
+ try {
2573
+ fetch(url, {
2574
+ method: "GET",
2575
+ mode: "no-cors",
2576
+ keepalive: true
2577
+ }).catch(() => void 0);
2578
+ return true;
2579
+ } catch {
2580
+ return false;
2581
+ }
2582
+ };
2583
+ const sendWithNavigatorBeacon = (url) => {
2584
+ if (typeof navigator === "undefined" || typeof navigator.sendBeacon !== "function") {
2585
+ return false;
2586
+ }
2587
+ try {
2588
+ return navigator.sendBeacon(url);
2589
+ } catch {
2590
+ return false;
2591
+ }
2592
+ };
2593
+ const trackAdPixel = (pixelUrl, customBeacon) => {
2594
+ if (!isBrowser_default) {
2595
+ return;
2596
+ }
2597
+ const url = pixelUrl == null ? void 0 : pixelUrl.trim();
2598
+ if (!url) {
2599
+ return;
2600
+ }
2601
+ if (typeof customBeacon === "function") {
2602
+ try {
2603
+ const result = customBeacon(url);
2604
+ if (result === true) {
2605
+ return;
2606
+ }
2607
+ } catch {
2608
+ }
2609
+ }
2610
+ if (sendWithNavigatorBeacon(url)) {
2611
+ return;
2612
+ }
2613
+ if (sendWithFetch(url)) {
2614
+ return;
2615
+ }
2616
+ sendWithImage(url);
2617
+ };
2618
+ const types = createConstants(
1791
2619
  "INIT_SESSION",
1792
2620
  "RELEASE_SESSION",
1793
2621
  "REACH_PROJECT_GOAL"
1794
2622
  );
1795
- const metricsPlugin = (state) => {
1796
- const sendMetric = (type, value) => {
1797
- var _a, _b;
1798
- (_a = state == null ? void 0 : state.$fetch) == null ? void 0 : _a.sendBeacon;
1799
- const query = (_b = state == null ? void 0 : state.$fetch) == null ? void 0 : _b.query;
1800
- query(addClientMetric, { type, value });
1801
- };
1802
- const initClient = async () => {
1803
- console.log("initClient");
1804
- sendMetric(types.INIT_SESSION);
1805
- };
1806
- const releaseClient = async () => {
1807
- sendMetric(types.RELEASE_SESSION);
2623
+ const globalMetricsPlugin = (state) => {
2624
+ const sendMetric = async (type, value) => {
2625
+ var _a;
2626
+ const query = (_a = state == null ? void 0 : state.$fetch) == null ? void 0 : _a.query;
2627
+ await query(addClientMetric, { type, value });
1808
2628
  };
1809
2629
  const reachGoal = (goal) => {
1810
2630
  sendMetric(types.REACH_PROJECT_GOAL, goal);
1811
2631
  };
2632
+ const sendAdPixel = (pixelUrl) => {
2633
+ var _a;
2634
+ trackAdPixel(pixelUrl, (_a = state == null ? void 0 : state.$fetch) == null ? void 0 : _a.sendBeacon);
2635
+ };
1812
2636
  state.$metrics = {
1813
- initClient,
1814
- releaseClient,
1815
- reachGoal
2637
+ reachGoal,
2638
+ trackAdPixel: sendAdPixel
1816
2639
  };
1817
2640
  };
2641
+ const loadPlugin = (state) => {
2642
+ if (!["$fetch", "$fragments"].every((field) => field in state)) {
2643
+ console.error("LoadFragmentPlugin depends from Fetch and Fragments plugin");
2644
+ return state;
2645
+ }
2646
+ const resourceCache = /* @__PURE__ */ new Map();
2647
+ const createSuspenseResource = (key, fetcher) => {
2648
+ if (resourceCache.has(key)) return resourceCache.get(key);
2649
+ let status = "pending";
2650
+ let result;
2651
+ const suspender = fetcher().then(
2652
+ (r2) => {
2653
+ status = "success";
2654
+ result = r2;
2655
+ },
2656
+ (e) => {
2657
+ status = "error";
2658
+ result = e;
2659
+ }
2660
+ );
2661
+ const resource = {
2662
+ read() {
2663
+ if (status === "pending") throw suspender;
2664
+ if (status === "error") throw result;
2665
+ return result;
2666
+ }
2667
+ };
2668
+ resourceCache.set(key, resource);
2669
+ return resource;
2670
+ };
2671
+ const loadFragment = (fragmentId, options) => {
2672
+ var _a, _b;
2673
+ const suspense = options == null ? void 0 : options.suspense;
2674
+ const readFragment = (_a = state == null ? void 0 : state.$fetch) == null ? void 0 : _a.readFragment(fragmentId);
2675
+ const fragmentManager = (_b = state == null ? void 0 : state.$fragments) == null ? void 0 : _b.getManager(fragmentId);
2676
+ if (readFragment && !fragmentManager) {
2677
+ return state.$fragments.createFragmentManager(fragmentId, readFragment);
2678
+ }
2679
+ if (readFragment && fragmentManager) return fragmentManager;
2680
+ const loader = async () => {
2681
+ var _a2;
2682
+ const fragmentDocument = await ((_a2 = state == null ? void 0 : state.$fetch) == null ? void 0 : _a2.queryFragment(fragmentId));
2683
+ return state.$fragments.createFragmentManager(
2684
+ fragmentId,
2685
+ fragmentDocument
2686
+ );
2687
+ };
2688
+ if (suspense) {
2689
+ const resource = createSuspenseResource(fragmentId, loader);
2690
+ return resource.read();
2691
+ }
2692
+ return loader();
2693
+ };
2694
+ const loadArea = (areaCode, options) => {
2695
+ var _a;
2696
+ const suspense = options == null ? void 0 : options.suspense;
2697
+ const readArea2 = (_a = state == null ? void 0 : state.$fetch) == null ? void 0 : _a.readArea(areaCode);
2698
+ if (readArea2) return readArea2;
2699
+ const loader = async () => {
2700
+ var _a2;
2701
+ const areaEntity = await ((_a2 = state == null ? void 0 : state.$fetch) == null ? void 0 : _a2.queryArea(areaCode));
2702
+ console.log(areaEntity);
2703
+ await loadFragment(areaEntity == null ? void 0 : areaEntity.fragmentId, {
2704
+ suspense: false
2705
+ });
2706
+ return areaEntity;
2707
+ };
2708
+ if (suspense) {
2709
+ const resource = createSuspenseResource(areaCode, loader);
2710
+ return resource.read();
2711
+ }
2712
+ return loader();
2713
+ };
2714
+ const readArea = () => {
2715
+ return state;
2716
+ };
2717
+ state.$load = {
2718
+ loadFragment,
2719
+ loadArea,
2720
+ readArea
2721
+ };
2722
+ };
2723
+ const PLUGIN_TYPES = createConstants(
2724
+ "FragmentsPlugin",
2725
+ "GlobalStylesheet",
2726
+ "FragmentStylesheet"
2727
+ );
1818
2728
  const createFragmentsClient = (options) => {
1819
- return it({
2729
+ const BACKEND_TARGET = (options == null ? void 0 : options.isSelf) ? "/graphql" : "http://85.192.29.65/graphql";
2730
+ return createState({
1820
2731
  _type: "GlobalManager",
1821
2732
  initialState: {},
2733
+ skip: [
2734
+ u([
2735
+ ...Object.keys(index.nodes),
2736
+ ...Object.keys(PLUGIN_TYPES)
2737
+ ])
2738
+ ],
1822
2739
  plugins: [
1823
2740
  (state) => {
1824
2741
  state.env = {
1825
2742
  isSelf: (options == null ? void 0 : options.isSelf) ?? false,
1826
- url: options == null ? void 0 : options.url,
2743
+ backendEndpoint: BACKEND_TARGET,
1827
2744
  apiToken: options == null ? void 0 : options.apiToken
1828
2745
  };
1829
- state.$global = {};
1830
- state.extractStyles = async () => {
1831
- const allFragments = state.$fragments.getManagers();
1832
- const extractors = Object.entries(allFragments).filter(([, value]) => !!(value == null ? void 0 : value.resolve)).map(([, manager]) => manager.$styleSheet.extract());
1833
- const extractedStyles = await Promise.all(extractors);
1834
- return Object.values(
1835
- extractedStyles.reduce((acc, extrected) => {
1836
- Object.entries(extrected).forEach(([key, styleTag]) => {
1837
- acc[key] = styleTag;
1838
- });
1839
- return acc;
1840
- }, {})
1841
- );
1842
- };
1843
2746
  },
1844
2747
  fetchPlugin,
1845
- fragmentsPlugin,
1846
- metricsPlugin,
1847
- (state) => {
1848
- var _a, _b, _c, _d, _e;
1849
- if (isBrowser_default) {
1850
- if (!((_a = state == null ? void 0 : state.env) == null ? void 0 : _a.isSelf)) {
1851
- (_c = (_b = state == null ? void 0 : state.$metrics) == null ? void 0 : _b.initClient) == null ? void 0 : _c.call(_b);
1852
- window.addEventListener(
1853
- "beforeunload",
1854
- (_e = (_d = state == null ? void 0 : state.$metrics) == null ? void 0 : _d.releaseClient) == null ? void 0 : _e.call(_d)
1855
- );
1856
- }
1857
- }
1858
- }
2748
+ fragmentsPlugin({
2749
+ plugins: options == null ? void 0 : options.fragmentPlugins
2750
+ }),
2751
+ loadPlugin,
2752
+ globalMetricsPlugin,
2753
+ globalStylesheetPlugin
1859
2754
  ]
1860
2755
  });
1861
2756
  };
2757
+ const ssrPlugin = (state) => {
2758
+ var _a, _b, _c;
2759
+ if (!["$fragments"].every((field) => field in state)) {
2760
+ console.error("SSRPlugin depends from Fragments plugin");
2761
+ return state;
2762
+ }
2763
+ const cacheDocuments = (_a = state == null ? void 0 : state.$fetch) == null ? void 0 : _a.cacheDocuments;
2764
+ const cacheAreas = (_b = state == null ? void 0 : state.$fetch) == null ? void 0 : _b.cacheAreaDocuments;
2765
+ const createManager = (_c = state == null ? void 0 : state.$fragments) == null ? void 0 : _c.createFragmentManager;
2766
+ const fromMap = (map) => {
2767
+ return Array.from(map).reduce((acc, [key, value]) => {
2768
+ acc[key] = value;
2769
+ return acc;
2770
+ }, {});
2771
+ };
2772
+ const extractData = () => {
2773
+ const documents = fromMap(cacheDocuments.entries());
2774
+ const areas = fromMap(cacheAreas.entries());
2775
+ return {
2776
+ documents,
2777
+ areas
2778
+ };
2779
+ };
2780
+ const restoreData = (input) => {
2781
+ if (!input || typeof input !== "object" && !Array.isArray(input))
2782
+ return null;
2783
+ if ("documents" in input && isObject(input.documents)) {
2784
+ Object.entries(input.documents).forEach(([fragmentId, doc]) => {
2785
+ cacheDocuments.set(+fragmentId, doc);
2786
+ createManager(+fragmentId, doc);
2787
+ });
2788
+ }
2789
+ if ("areas" in input && isObject(input.areas)) {
2790
+ Object.entries(input.areas).forEach(([areaCode, entity]) => {
2791
+ cacheAreas.set(areaCode, entity);
2792
+ });
2793
+ }
2794
+ };
2795
+ state.$ssr = {
2796
+ extractData,
2797
+ restoreData
2798
+ };
2799
+ return state;
2800
+ };
1862
2801
  exports.createFragmentsClient = createFragmentsClient;
2802
+ exports.ssrPlugin = ssrPlugin;