goatly 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +874 -1
- package/bin/goatly.js +99 -0
- package/dist/cli/index.js +234 -0
- package/dist/compat/gatsby-node-entry.js +16 -0
- package/dist/compat/gatsby-package.json +6 -0
- package/dist/compat/md5-file.js +47 -0
- package/dist/compat-apis.json +72 -0
- package/dist/compat-apis.json.js +62 -0
- package/dist/graphql.js +3 -0
- package/dist/node/actions/index.js +619 -0
- package/dist/node/actions/job-store.js +180 -0
- package/dist/node/actions/jobs.js +174 -0
- package/dist/node/api-runner.js +258 -0
- package/dist/node/bootstrap.js +569 -0
- package/dist/node/build/assets.js +110 -0
- package/dist/node/build/incremental.js +208 -0
- package/dist/node/build/index.js +763 -0
- package/dist/node/build/memory-governor.js +450 -0
- package/dist/node/build/output-dirs.js +70 -0
- package/dist/node/build/page-data.js +40 -0
- package/dist/node/build/page-files.js +186 -0
- package/dist/node/build/partitioned-state.js +258 -0
- package/dist/node/build/query-worker.js +626 -0
- package/dist/node/build/query-workers.js +863 -0
- package/dist/node/build/render-thread.js +103 -0
- package/dist/node/build/render-worker.js +162 -0
- package/dist/node/build/state.js +24 -0
- package/dist/node/build/timing-breakdown.js +216 -0
- package/dist/node/build/work-clock.js +75 -0
- package/dist/node/build/worker-pool.js +242 -0
- package/dist/node/cache-layout.js +99 -0
- package/dist/node/cache.js +1430 -0
- package/dist/node/compat/chokidar-shim.js +148 -0
- package/dist/node/compat/core-utils-lmdb.js +145 -0
- package/dist/node/compat/create-node-id-shim.js +1 -0
- package/dist/node/compat/module-hooks.js +245 -0
- package/dist/node/compat/redux-shim.js +1 -0
- package/dist/node/config/index.js +162 -0
- package/dist/node/config/not-found-pages.js +95 -0
- package/dist/node/datastore/codec.js +144 -0
- package/dist/node/datastore/index.js +127 -0
- package/dist/node/datastore/logfile/cache.js +89 -0
- package/dist/node/datastore/logfile/index.js +1329 -0
- package/dist/node/datastore/logfile/record.js +71 -0
- package/dist/node/datastore/types.js +1 -0
- package/dist/node/develop/express-compat.js +207 -0
- package/dist/node/develop/graphiql.js +22 -0
- package/dist/node/develop/hydration-report.js +41 -0
- package/dist/node/develop/index.js +618 -0
- package/dist/node/develop/local-url.js +10 -0
- package/dist/node/develop/ssr-runner.js +66 -0
- package/dist/node/gql.js +5 -0
- package/dist/node/index.js +15 -0
- package/dist/node/info.js +270 -0
- package/dist/node/internal-plugins/data-bridge.js +196 -0
- package/dist/node/internal-plugins/page-creator.js +318 -0
- package/dist/node/loader/import-module.js +160 -0
- package/dist/node/node-helpers.js +66 -0
- package/dist/node/not-found-pages.js +220 -0
- package/dist/node/plugins/api-list.js +12 -0
- package/dist/node/plugins/load-plugins.js +427 -0
- package/dist/node/plugins/resolve-plugin.js +79 -0
- package/dist/node/plugins/static-exports.js +64 -0
- package/dist/node/query/compile.js +326 -0
- package/dist/node/query/dependencies.js +45 -0
- package/dist/node/query/execute.js +417 -0
- package/dist/node/query/extract.js +372 -0
- package/dist/node/query/gql-tada-introspection.js +124 -0
- package/dist/node/query/graphql-env.js +231 -0
- package/dist/node/query/graphql-runner.js +79 -0
- package/dist/node/redux/actions.js +1 -0
- package/dist/node/redux/index.js +133 -0
- package/dist/node/redux/node-changes.js +128 -0
- package/dist/node/redux/reducers.js +193 -0
- package/dist/node/redux/state.js +71 -0
- package/dist/node/renderer.js +124 -0
- package/dist/node/reporter-transports.js +259 -0
- package/dist/node/reporter.js +497 -0
- package/dist/node/schema/date.js +539 -0
- package/dist/node/schema/extensions.js +315 -0
- package/dist/node/schema/index.js +542 -0
- package/dist/node/schema/infer.js +388 -0
- package/dist/node/schema/inline-objects.js +128 -0
- package/dist/node/schema/naming.js +20 -0
- package/dist/node/schema/node-model.js +207 -0
- package/dist/node/schema/query-engine.js +1808 -0
- package/dist/node/schema/resolver-kinds.js +7 -0
- package/dist/node/schema/resolvers.js +273 -0
- package/dist/node/schema/type-builders.js +45 -0
- package/dist/node/schema/types.js +241 -0
- package/dist/node/serve.js +90 -0
- package/dist/node/site-page-nodes.js +277 -0
- package/dist/node/types.js +1 -0
- package/dist/node/utils/content-digest.js +107 -0
- package/dist/node/utils/cpus.js +104 -0
- package/dist/node/utils/create-node-id.js +51 -0
- package/dist/node/utils/env.js +25 -0
- package/dist/node/utils/fs-retry.js +74 -0
- package/dist/node/utils/memory-signals.js +441 -0
- package/dist/node/utils/memory.js +657 -0
- package/dist/node/utils/murmurhash.js +32 -0
- package/dist/node/utils/parser.js +33 -0
- package/dist/node/utils/partition-hash.js +19 -0
- package/dist/node/utils/paths.js +122 -0
- package/dist/node/utils/resolver.js +48 -0
- package/dist/node/utils/runtime.js +5 -0
- package/dist/node/utils/serializable.js +41 -0
- package/dist/node/utils/strings.js +41 -0
- package/dist/node/vite/config.js +289 -0
- package/dist/node/vite/paths.js +12 -0
- package/dist/node/vite/plugin-deps.js +232 -0
- package/dist/node/vite/plugin.js +283 -0
- package/dist/node/vite/react-compiler.js +362 -0
- package/dist/node/vite/source-files.js +83 -0
- package/dist/node/vite/static-image.js +136 -0
- package/dist/node/vite/styled-components.js +73 -0
- package/dist/node/vite/transforms.js +330 -0
- package/dist/node/wasm-data/host.js +406 -0
- package/dist/node/wasm-data/lower.js +406 -0
- package/dist/node/wasm-data/runner.js +79 -0
- package/dist/node/wasm-data/worker.js +95 -0
- package/dist/reporter.js +5 -0
- package/dist/runtime/api-runner.js +81 -0
- package/dist/runtime/app.js +256 -0
- package/dist/runtime/client-entry.js +4 -0
- package/dist/runtime/client.js +383 -0
- package/dist/runtime/default-html.js +31 -0
- package/dist/runtime/head-markup.js +100 -0
- package/dist/runtime/head-sync.js +101 -0
- package/dist/runtime/head-tags.js +45 -0
- package/dist/runtime/hydration-report.js +111 -0
- package/dist/runtime/index.js +12 -0
- package/dist/runtime/link.js +293 -0
- package/dist/runtime/loader.js +449 -0
- package/dist/runtime/not-found.js +61 -0
- package/dist/runtime/page-renderer.js +35 -0
- package/dist/runtime/preamble.js +47 -0
- package/dist/runtime/react-compat.js +14 -0
- package/dist/runtime/renderer-shared.js +10 -0
- package/dist/runtime/renderers/react-client.js +14 -0
- package/dist/runtime/renderers/react-server.js +99 -0
- package/dist/runtime/renderers/react.js +17 -0
- package/dist/runtime/renderers/types.js +1 -0
- package/dist/runtime/root-error-handlers.js +29 -0
- package/dist/runtime/router/history.js +132 -0
- package/dist/runtime/router/index.js +240 -0
- package/dist/runtime/router/utils.js +118 -0
- package/dist/runtime/script.js +110 -0
- package/dist/runtime/scroll.js +40 -0
- package/dist/runtime/slice.js +11 -0
- package/dist/runtime/ssr.js +240 -0
- package/dist/runtime/static-query.js +47 -0
- package/dist/utils.js +4 -0
- package/package.json +105 -3
- package/types/graphql-tada.d.ts +223 -0
- package/types/graphql.d.ts +2 -0
- package/types/index.d.ts +2287 -0
- package/types/node.d.ts +389 -0
- package/types/reporter.d.ts +187 -0
- package/types/router.d.ts +102 -0
- package/types/vendor/gql-tada.d.ts +2529 -0
|
@@ -0,0 +1,1808 @@
|
|
|
1
|
+
import { getArgumentValues, getNamedType, isAbstractType, isInterfaceType, isLeafType, isObjectType, isUnionType } from "../gql.js";
|
|
2
|
+
import { getDataStore, getDataStoreGeneration, readingNodesOfTypes } from "../datastore/index.js";
|
|
3
|
+
import { QueryDependencies } from "../query/dependencies.js";
|
|
4
|
+
import { readsOwnFieldOnly, syncVariantOf, trackInlineObjects } from "./inline-objects.js";
|
|
5
|
+
import { getTypesTick } from "../redux/node-changes.js";
|
|
6
|
+
import { detachString, detachValue } from "../utils/strings.js";
|
|
7
|
+
import { isBun } from "../utils/runtime.js";
|
|
8
|
+
import { onAction } from "../redux/index.js";
|
|
9
|
+
import picomatch from "picomatch";
|
|
10
|
+
// src/node/schema/query-engine.ts
|
|
11
|
+
/**
|
|
12
|
+
* In-memory query engine used by `nodeModel.findAll/findOne` and the `allX`/`x`
|
|
13
|
+
* root fields. Supports all Gatsby filter operators, Gatsby 5 sort syntax,
|
|
14
|
+
* lazily built `eq`/`in` indexes, materialization of fields with custom resolvers
|
|
15
|
+
* and a result cache for repeated list queries (e.g. paginated listings).
|
|
16
|
+
*/
|
|
17
|
+
const OPERATORS = /* @__PURE__ */ new Set([
|
|
18
|
+
"eq",
|
|
19
|
+
"ne",
|
|
20
|
+
"in",
|
|
21
|
+
"nin",
|
|
22
|
+
"regex",
|
|
23
|
+
"glob",
|
|
24
|
+
"gt",
|
|
25
|
+
"gte",
|
|
26
|
+
"lt",
|
|
27
|
+
"lte"
|
|
28
|
+
]);
|
|
29
|
+
/**
|
|
30
|
+
* Cache versions. Values computed by resolvers may read any node (also without nodeModel, e.g. a
|
|
31
|
+
* captured getNode), so they are cached for `dataVersion`: any node change. The lazy path's caches
|
|
32
|
+
* of raw values of nodes of the queried types only (id lists, value indexes, projections, results
|
|
33
|
+
* of queries without resolvers) use `typesStamp`: changes of nodes of other types keep them (the
|
|
34
|
+
* SitePage node of a createPage between two queries of createPages). The eager path, for stores
|
|
35
|
+
* without `lazy`, caches for `dataVersion`.
|
|
36
|
+
*/
|
|
37
|
+
let dataVersion = 0;
|
|
38
|
+
/** the schema changed or caches were invalidated: every cache */
|
|
39
|
+
let globalVersion = 0;
|
|
40
|
+
const bump = () => {
|
|
41
|
+
dataVersion++;
|
|
42
|
+
};
|
|
43
|
+
const bumpAll = () => {
|
|
44
|
+
dataVersion++;
|
|
45
|
+
globalVersion++;
|
|
46
|
+
};
|
|
47
|
+
for (const t of [
|
|
48
|
+
"CREATE_NODE",
|
|
49
|
+
"DELETE_NODE",
|
|
50
|
+
"ADD_FIELD_TO_NODE",
|
|
51
|
+
"ADD_CHILD_NODE_TO_PARENT_NODE"
|
|
52
|
+
]) onAction(t, bump);
|
|
53
|
+
onAction("SET_SCHEMA", bumpAll);
|
|
54
|
+
function invalidateQueryCaches() {
|
|
55
|
+
bumpAll();
|
|
56
|
+
}
|
|
57
|
+
function getDataVersion() {
|
|
58
|
+
return dataVersion;
|
|
59
|
+
}
|
|
60
|
+
/** stamp of caches computed by resolvers (any node change, schema or store) */
|
|
61
|
+
function dataStamp() {
|
|
62
|
+
return `d${dataVersion}:${globalVersion}:${getDataStoreGeneration()}`;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Stamp of caches of raw values of nodes of exactly these types: the per-type change ticks are
|
|
66
|
+
* bumped by the reducer, before any listener runs (also for the old type of a retyped node).
|
|
67
|
+
*/
|
|
68
|
+
function typesStamp(typeNames) {
|
|
69
|
+
return `${globalVersion}:${getDataStoreGeneration()}:${getTypesTick(typeNames)}`;
|
|
70
|
+
}
|
|
71
|
+
function getValueAt(obj, path) {
|
|
72
|
+
const segments = typeof path === "string" ? path.split(".") : path;
|
|
73
|
+
let current = obj;
|
|
74
|
+
for (let i = 0; i < segments.length; i++) {
|
|
75
|
+
if (current == null) return void 0;
|
|
76
|
+
if (Array.isArray(current)) {
|
|
77
|
+
const rest = segments.slice(i);
|
|
78
|
+
return current.map((c) => getValueAt(c, rest)).filter((v) => v !== void 0).flat();
|
|
79
|
+
}
|
|
80
|
+
current = current[segments[i]];
|
|
81
|
+
}
|
|
82
|
+
return current;
|
|
83
|
+
}
|
|
84
|
+
function compareAscending(a, b) {
|
|
85
|
+
if (a === b) return 0;
|
|
86
|
+
const aNil = a === null || a === void 0 || typeof a === "number" && Number.isNaN(a);
|
|
87
|
+
const bNil = b === null || b === void 0 || typeof b === "number" && Number.isNaN(b);
|
|
88
|
+
if (aNil && bNil) return 0;
|
|
89
|
+
if (aNil) return 1;
|
|
90
|
+
if (bNil) return -1;
|
|
91
|
+
if (a instanceof Date) a = a.getTime();
|
|
92
|
+
if (b instanceof Date) b = b.getTime();
|
|
93
|
+
if (Array.isArray(a)) a = a[0];
|
|
94
|
+
if (Array.isArray(b)) b = b[0];
|
|
95
|
+
if (typeof a === "boolean") a = a ? 1 : 0;
|
|
96
|
+
if (typeof b === "boolean") b = b ? 1 : 0;
|
|
97
|
+
if (a > b) return 1;
|
|
98
|
+
if (a < b) return -1;
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
/** Converts Gatsby 5 (`{frontmatter: {date: DESC}}`) and Gatsby 4 (`{fields, order}`) sort args. */
|
|
102
|
+
function normalizeSort(sort) {
|
|
103
|
+
if (!sort) return [];
|
|
104
|
+
if (!Array.isArray(sort) && Array.isArray(sort.fields)) {
|
|
105
|
+
const orders = [].concat(sort.order ?? []);
|
|
106
|
+
return sort.fields.map((f, i) => ({
|
|
107
|
+
path: f.split(/___|\./),
|
|
108
|
+
order: String(orders[i] ?? orders[0] ?? "ASC").toUpperCase() === "DESC" ? "DESC" : "ASC"
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
const out = [];
|
|
112
|
+
const walk = (obj, prefix) => {
|
|
113
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
114
|
+
if (value == null) continue;
|
|
115
|
+
if (typeof value === "string") out.push({
|
|
116
|
+
path: [...prefix, key],
|
|
117
|
+
order: value.toUpperCase() === "DESC" ? "DESC" : "ASC"
|
|
118
|
+
});
|
|
119
|
+
else if (typeof value === "object") walk(value, [...prefix, key]);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
for (const s of [].concat(sort)) if (s && typeof s === "object") walk(s, []);
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
/** Converts a Gatsby 5 field selector (`{frontmatter: {tags: SELECT}}`) to a dot path. */
|
|
126
|
+
function fieldSelectorToPath(selector) {
|
|
127
|
+
if (typeof selector === "string") return selector.replace(/___/g, ".");
|
|
128
|
+
const parts = [];
|
|
129
|
+
let current = selector;
|
|
130
|
+
while (current && typeof current === "object") {
|
|
131
|
+
const key = Object.keys(current)[0];
|
|
132
|
+
if (!key) break;
|
|
133
|
+
parts.push(key);
|
|
134
|
+
current = current[key];
|
|
135
|
+
}
|
|
136
|
+
return parts.join(".");
|
|
137
|
+
}
|
|
138
|
+
function toRegExp(value) {
|
|
139
|
+
if (value instanceof RegExp) return value;
|
|
140
|
+
const str = String(value);
|
|
141
|
+
const m = /^\/(.*)\/([gimsuyd]*)$/s.exec(str);
|
|
142
|
+
return m ? new RegExp(m[1], m[2].replace("g", "")) : new RegExp(str);
|
|
143
|
+
}
|
|
144
|
+
const looseEq = (a, b) => b === null ? a == null : a === b;
|
|
145
|
+
function compileLeaf(ops) {
|
|
146
|
+
const tests = [];
|
|
147
|
+
const some = (test) => (v) => Array.isArray(v) ? v.some(test) : test(v);
|
|
148
|
+
for (const [op, fv] of Object.entries(ops)) {
|
|
149
|
+
if (fv === void 0) continue;
|
|
150
|
+
switch (op) {
|
|
151
|
+
case "eq":
|
|
152
|
+
tests.push((v) => Array.isArray(v) ? fv === null ? v.length === 0 : v.some((x) => looseEq(x, fv)) : looseEq(v, fv));
|
|
153
|
+
break;
|
|
154
|
+
case "ne":
|
|
155
|
+
tests.push((v) => Array.isArray(v) ? fv === null ? v.length > 0 : !v.some((x) => looseEq(x, fv)) : !looseEq(v, fv));
|
|
156
|
+
break;
|
|
157
|
+
case "in": {
|
|
158
|
+
const list = [].concat(fv);
|
|
159
|
+
const set = new Set(list);
|
|
160
|
+
const hasNull = list.includes(null);
|
|
161
|
+
tests.push((v) => {
|
|
162
|
+
if (v == null) return hasNull;
|
|
163
|
+
if (Array.isArray(v)) return v.some((x) => set.has(x) || hasNull && x == null);
|
|
164
|
+
return set.has(v);
|
|
165
|
+
});
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
case "nin": {
|
|
169
|
+
const list = [].concat(fv);
|
|
170
|
+
const set = new Set(list);
|
|
171
|
+
const hasNull = list.includes(null);
|
|
172
|
+
tests.push((v) => {
|
|
173
|
+
if (v == null) return !hasNull;
|
|
174
|
+
if (Array.isArray(v)) return v.every((x) => !set.has(x) && !(hasNull && x == null));
|
|
175
|
+
return !set.has(v);
|
|
176
|
+
});
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
case "regex": {
|
|
180
|
+
const re = toRegExp(fv);
|
|
181
|
+
tests.push(some((x) => typeof x === "string" && re.test(x)));
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
case "glob": {
|
|
185
|
+
const isMatch = picomatch(String(fv));
|
|
186
|
+
tests.push(some((x) => typeof x === "string" && isMatch(x)));
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
case "gt":
|
|
190
|
+
tests.push(some((x) => x != null && x > fv));
|
|
191
|
+
break;
|
|
192
|
+
case "gte":
|
|
193
|
+
tests.push(some((x) => x != null && x >= fv));
|
|
194
|
+
break;
|
|
195
|
+
case "lt":
|
|
196
|
+
tests.push(some((x) => x != null && x < fv));
|
|
197
|
+
break;
|
|
198
|
+
case "lte": tests.push(some((x) => x != null && x <= fv));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (tests.length === 1) return tests[0];
|
|
202
|
+
return (v) => {
|
|
203
|
+
for (const t of tests) if (!t(v)) return false;
|
|
204
|
+
return true;
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
const EMPTY = Object.freeze({});
|
|
208
|
+
function isOperatorObject(value) {
|
|
209
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
210
|
+
const keys = Object.keys(value);
|
|
211
|
+
return keys.length > 0 && keys.every((k) => OPERATORS.has(k));
|
|
212
|
+
}
|
|
213
|
+
function fieldsOf(type) {
|
|
214
|
+
if (type && (isObjectType(type) || isInterfaceType(type))) return type.getFields();
|
|
215
|
+
}
|
|
216
|
+
/** Compiles a (schema-aware) Gatsby filter object into a predicate. */
|
|
217
|
+
function compileFilter(filter, type) {
|
|
218
|
+
if (!filter || Object.keys(filter).length === 0) return () => true;
|
|
219
|
+
const fields = fieldsOf(type);
|
|
220
|
+
const preds = [];
|
|
221
|
+
for (const [field, value] of Object.entries(filter)) {
|
|
222
|
+
if (value === void 0 || value === null) continue;
|
|
223
|
+
const def = fields?.[field];
|
|
224
|
+
const named = def ? getNamedType(def.type) : void 0;
|
|
225
|
+
if (named ? isLeafType(named) : isOperatorObject(value)) {
|
|
226
|
+
const leaf = compileLeaf(value);
|
|
227
|
+
preds.push((obj) => leaf(obj?.[field]));
|
|
228
|
+
} else if (value && typeof value === "object" && "elemMatch" in value) {
|
|
229
|
+
const sub = compileFilter(value.elemMatch, named);
|
|
230
|
+
preds.push((obj) => {
|
|
231
|
+
const v = obj?.[field];
|
|
232
|
+
if (v == null) return false;
|
|
233
|
+
return Array.isArray(v) ? v.some((e) => e != null && sub(e)) : sub(v);
|
|
234
|
+
});
|
|
235
|
+
} else if (value && typeof value === "object") {
|
|
236
|
+
const sub = compileFilter(value, named);
|
|
237
|
+
preds.push((obj) => {
|
|
238
|
+
const v = obj?.[field];
|
|
239
|
+
if (Array.isArray(v)) return v.length ? v.some((e) => sub(e ?? EMPTY)) : sub(EMPTY);
|
|
240
|
+
return sub(v ?? EMPTY);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (preds.length === 1) return preds[0];
|
|
245
|
+
return (obj) => {
|
|
246
|
+
for (const p of preds) if (!p(obj)) return false;
|
|
247
|
+
return true;
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function addPath(tree, path) {
|
|
251
|
+
let current = tree;
|
|
252
|
+
for (let i = 0; i < path.length; i++) {
|
|
253
|
+
const key = path[i];
|
|
254
|
+
const isLast = i === path.length - 1;
|
|
255
|
+
let next = current.get(key);
|
|
256
|
+
if (isLast) {
|
|
257
|
+
if (next === void 0) current.set(key, null);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (!next) {
|
|
261
|
+
next = /* @__PURE__ */ new Map();
|
|
262
|
+
current.set(key, next);
|
|
263
|
+
}
|
|
264
|
+
current = next;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function filterToTree(filter, tree, prefix = []) {
|
|
268
|
+
if (!filter || typeof filter !== "object") return;
|
|
269
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
270
|
+
if (value == null) continue;
|
|
271
|
+
if (isOperatorObject(value)) addPath(tree, [...prefix, key]);
|
|
272
|
+
else if (typeof value === "object" && "elemMatch" in value) {
|
|
273
|
+
addPath(tree, [...prefix, key]);
|
|
274
|
+
filterToTree(value.elemMatch, tree, [...prefix, key]);
|
|
275
|
+
} else if (typeof value === "object") filterToTree(value, tree, [...prefix, key]);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
function treeKey(tree) {
|
|
279
|
+
const parts = [];
|
|
280
|
+
for (const [k, v] of tree) parts.push(v ? `${k}{${treeKey(v)}}` : k);
|
|
281
|
+
return parts.join(",");
|
|
282
|
+
}
|
|
283
|
+
function hasCustomResolver(def) {
|
|
284
|
+
const resolve = def?.resolve;
|
|
285
|
+
if (!resolve) return false;
|
|
286
|
+
if (resolve.__goatlyPassthrough) return false;
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
function treeNeedsResolve(tree, type, schema, seen = /* @__PURE__ */ new Set()) {
|
|
290
|
+
if (type && isInterfaceType(type)) {
|
|
291
|
+
for (const t of schema.getPossibleTypes(type)) if (treeNeedsResolve(tree, t, schema, seen)) return true;
|
|
292
|
+
}
|
|
293
|
+
const fields = fieldsOf(type);
|
|
294
|
+
if (!fields) return isAbstractType(type);
|
|
295
|
+
for (const [field, sub] of tree) {
|
|
296
|
+
const def = fields[field];
|
|
297
|
+
if (!def) continue;
|
|
298
|
+
if (hasCustomResolver(def)) return true;
|
|
299
|
+
if (sub) {
|
|
300
|
+
const named = getNamedType(def.type);
|
|
301
|
+
const key = `${named.name}:${treeKey(sub)}`;
|
|
302
|
+
if (seen.has(key)) continue;
|
|
303
|
+
seen.add(key);
|
|
304
|
+
if (isAbstractType(named)) {
|
|
305
|
+
for (const t of schema.getPossibleTypes(named)) if (treeNeedsResolve(sub, t, schema, seen)) return true;
|
|
306
|
+
} else if (treeNeedsResolve(sub, named, schema, seen)) return true;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
function fakeInfo(def, parentType, schema) {
|
|
312
|
+
return {
|
|
313
|
+
fieldName: def.name,
|
|
314
|
+
fieldNodes: [],
|
|
315
|
+
returnType: def.type,
|
|
316
|
+
parentType,
|
|
317
|
+
path: {
|
|
318
|
+
prev: void 0,
|
|
319
|
+
key: def.name,
|
|
320
|
+
typename: parentType.name
|
|
321
|
+
},
|
|
322
|
+
schema,
|
|
323
|
+
fragments: {},
|
|
324
|
+
rootValue: void 0,
|
|
325
|
+
operation: {
|
|
326
|
+
kind: "OperationDefinition",
|
|
327
|
+
operation: "query",
|
|
328
|
+
selectionSet: {
|
|
329
|
+
kind: "SelectionSet",
|
|
330
|
+
selections: []
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
variableValues: {}
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
function defaultArgs(def) {
|
|
337
|
+
const args = {};
|
|
338
|
+
for (const arg of def.args) if (arg.defaultValue !== void 0) args[arg.name] = arg.defaultValue;
|
|
339
|
+
return args;
|
|
340
|
+
}
|
|
341
|
+
function concreteType(value, type, schema) {
|
|
342
|
+
if (!isAbstractType(type)) return type;
|
|
343
|
+
return (value?.internal?.type ? schema.getType(value.internal.type) : void 0) ?? void 0;
|
|
344
|
+
}
|
|
345
|
+
async function materialize(obj, type, tree, rc) {
|
|
346
|
+
if (obj == null || typeof obj !== "object") return obj;
|
|
347
|
+
const fields = fieldsOf(type);
|
|
348
|
+
if (!fields) return obj;
|
|
349
|
+
const out = Array.isArray(obj) ? obj : { ...obj };
|
|
350
|
+
for (const [field, sub] of tree) {
|
|
351
|
+
const def = fields[field];
|
|
352
|
+
if (!def) continue;
|
|
353
|
+
let value = hasCustomResolver(def) ? await syncVariantOf(def.resolve)(obj, defaultArgs(def), rc.context, fakeInfo(def, type, rc.schema)) : obj[field];
|
|
354
|
+
if (sub && value != null) {
|
|
355
|
+
const named = getNamedType(def.type);
|
|
356
|
+
if (Array.isArray(value)) value = await Promise.all(value.map((v) => materialize(v, concreteType(v, named, rc.schema), sub, rc)));
|
|
357
|
+
else value = await materialize(value, concreteType(value, named, rc.schema), sub, rc);
|
|
358
|
+
}
|
|
359
|
+
out[field] = value;
|
|
360
|
+
}
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
const MAX_RESULT_CACHE = 1e3;
|
|
364
|
+
/**
|
|
365
|
+
* list items (nodes or ids) of all results of a result cache: results whose filter has a value of
|
|
366
|
+
* one page (e.g. `id: { ne: $id }`) are lists of almost every node, one per page
|
|
367
|
+
*/
|
|
368
|
+
const MAX_RESULT_ITEMS = 4e6;
|
|
369
|
+
/**
|
|
370
|
+
* Results cached by key, at most MAX_RESULT_CACHE of them and MAX_RESULT_ITEMS list items in all
|
|
371
|
+
* (each is a list of up to all nodes of its types): the least recently used ones are evicted.
|
|
372
|
+
*/
|
|
373
|
+
var ResultCache = class {
|
|
374
|
+
entries = /* @__PURE__ */ new Map();
|
|
375
|
+
items = 0;
|
|
376
|
+
get size() {
|
|
377
|
+
return this.entries.size;
|
|
378
|
+
}
|
|
379
|
+
get(key) {
|
|
380
|
+
return this.entries.get(key)?.value;
|
|
381
|
+
}
|
|
382
|
+
/** the entry is now the most recently used */
|
|
383
|
+
touch(key) {
|
|
384
|
+
const entry = this.entries.get(key);
|
|
385
|
+
if (!entry) return;
|
|
386
|
+
this.entries.delete(key);
|
|
387
|
+
this.entries.set(key, entry);
|
|
388
|
+
}
|
|
389
|
+
/** `items`: the length of the result's list */
|
|
390
|
+
set(key, value, items) {
|
|
391
|
+
this.delete(key);
|
|
392
|
+
if (items > MAX_RESULT_ITEMS) return;
|
|
393
|
+
this.entries.set(key, {
|
|
394
|
+
value,
|
|
395
|
+
items
|
|
396
|
+
});
|
|
397
|
+
this.items += items;
|
|
398
|
+
while (this.entries.size > MAX_RESULT_CACHE || this.items > MAX_RESULT_ITEMS) this.delete(this.entries.keys().next().value);
|
|
399
|
+
}
|
|
400
|
+
delete(key) {
|
|
401
|
+
const entry = this.entries.get(key);
|
|
402
|
+
if (!entry) return;
|
|
403
|
+
this.entries.delete(key);
|
|
404
|
+
this.items -= entry.items;
|
|
405
|
+
}
|
|
406
|
+
clear() {
|
|
407
|
+
this.entries.clear();
|
|
408
|
+
this.items = 0;
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
const indexCache = /* @__PURE__ */ new Map();
|
|
412
|
+
const resultCache = new ResultCache();
|
|
413
|
+
const viewCache = /* @__PURE__ */ new WeakMap();
|
|
414
|
+
/**
|
|
415
|
+
* Concurrent queries with the same key share one computation: page queries run concurrently, and
|
|
416
|
+
* between a cache miss and the cache write a query may wait (views with resolvers, lazy stores), so
|
|
417
|
+
* every list page starting meanwhile would sort all nodes again (65 times with 20k posts).
|
|
418
|
+
*/
|
|
419
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
420
|
+
function shared(key, compute) {
|
|
421
|
+
let pending = inflight.get(key);
|
|
422
|
+
if (!pending) {
|
|
423
|
+
pending = compute().finally(() => inflight.delete(key));
|
|
424
|
+
inflight.set(key, pending);
|
|
425
|
+
}
|
|
426
|
+
return pending;
|
|
427
|
+
}
|
|
428
|
+
/** dependencies collected while materializing a (cached) view */
|
|
429
|
+
const viewDeps = /* @__PURE__ */ new WeakMap();
|
|
430
|
+
/**
|
|
431
|
+
* `keepSlimNodes`: the slim nodes of unchanged types stay (e.g. from createPages for the page
|
|
432
|
+
* queries of the same build): they are copies of the stored data, not derived from the schema.
|
|
433
|
+
*/
|
|
434
|
+
function clearQueryEngineCaches(options = {}) {
|
|
435
|
+
const kept = options.keepSlimNodes ? [...slimSets].filter(([type, set]) => set.tooLarge === void 0 && set.stamp === typesStamp([type])) : [];
|
|
436
|
+
indexCache.clear();
|
|
437
|
+
resultCache.clear();
|
|
438
|
+
nodesCache.clear();
|
|
439
|
+
clearLazyQueryCaches();
|
|
440
|
+
bumpAll();
|
|
441
|
+
for (const [type, set] of kept) {
|
|
442
|
+
set.stamp = typesStamp([type]);
|
|
443
|
+
slimSets.set(type, set);
|
|
444
|
+
slimBytes += set.bytes;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/** drops the slim nodes (e.g. before query workers start, which keep their own) */
|
|
448
|
+
function clearSlimNodes() {
|
|
449
|
+
slimSets.clear();
|
|
450
|
+
slimBytes = 0;
|
|
451
|
+
}
|
|
452
|
+
function getNodeTypeNames(type, schema) {
|
|
453
|
+
if (isObjectType(type)) return [type.name];
|
|
454
|
+
if (isInterfaceType(type) || isUnionType(type)) return schema.getPossibleTypes(type).map((t) => t.name);
|
|
455
|
+
return [];
|
|
456
|
+
}
|
|
457
|
+
/** node lists per type set (one copy per data version instead of one per query) */
|
|
458
|
+
const nodesCache = /* @__PURE__ */ new Map();
|
|
459
|
+
function getNodesForTypes(typeNames) {
|
|
460
|
+
const key = typeNames.join("|");
|
|
461
|
+
const cached = nodesCache.get(key);
|
|
462
|
+
if (cached && cached.version === dataVersion) return cached.nodes;
|
|
463
|
+
const ds = getDataStore();
|
|
464
|
+
let all;
|
|
465
|
+
if (typeNames.length === 1) {
|
|
466
|
+
const nodes = ds.iterateNodesByType(typeNames[0]);
|
|
467
|
+
all = Array.isArray(nodes) ? nodes : [...nodes];
|
|
468
|
+
} else {
|
|
469
|
+
all = [];
|
|
470
|
+
for (const t of typeNames) for (const n of ds.iterateNodesByType(t)) all.push(n);
|
|
471
|
+
all.sort((a, b) => (a.internal.counter ?? 0) - (b.internal.counter ?? 0));
|
|
472
|
+
}
|
|
473
|
+
if (nodesCache.size >= 256) nodesCache.delete(nodesCache.keys().next().value);
|
|
474
|
+
nodesCache.set(key, {
|
|
475
|
+
version: dataVersion,
|
|
476
|
+
nodes: all
|
|
477
|
+
});
|
|
478
|
+
return all;
|
|
479
|
+
}
|
|
480
|
+
/** `in` lists longer than this are filtered by a scan */
|
|
481
|
+
const MAX_INDEXED_IN = 1e3;
|
|
482
|
+
/**
|
|
483
|
+
* Lazy stores: an indexed `eq` with more matches than this takes them from the projections of all
|
|
484
|
+
* nodes (one streaming scan per view set, of slim nodes when the type has them), like an `in`:
|
|
485
|
+
* loading them would decode most of the type's whole nodes for every page that starts meanwhile.
|
|
486
|
+
*/
|
|
487
|
+
const MAX_EQ_CANDIDATES = 256;
|
|
488
|
+
const isPrimitive = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
|
|
489
|
+
/**
|
|
490
|
+
* Finds a top level indexable `eq` – or else an `in` of primitive values (raw values, no custom
|
|
491
|
+
* resolvers along the path). An `in` with null is not indexable: null also matches nodes without
|
|
492
|
+
* a value. Index and filter compare alike (SameValueZero: Map keys, Set.has / ===).
|
|
493
|
+
* An `in` is indexed only for queries without resolvers: with resolvers, a scan records what they
|
|
494
|
+
* read for every node of the types and an indexed query for its candidates only (`in` queries keep
|
|
495
|
+
* the dependencies of a scan).
|
|
496
|
+
*/
|
|
497
|
+
function findIndexable(filter, type, schema, needsResolve) {
|
|
498
|
+
return findIndexableOp(filter, type, [], schema, "eq") ?? (needsResolve ? void 0 : findIndexableOp(filter, type, [], schema, "in"));
|
|
499
|
+
}
|
|
500
|
+
/** every indexable `eq` of the filter (see findIndexableOp) */
|
|
501
|
+
function findIndexableEqs(filter, type, prefix, schema, out = []) {
|
|
502
|
+
const fields = fieldsOf(type);
|
|
503
|
+
if (!fields || !filter) return out;
|
|
504
|
+
const possible = isInterfaceType(type) ? schema.getPossibleTypes(type) : [];
|
|
505
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
506
|
+
if (value == null || typeof value !== "object") continue;
|
|
507
|
+
const def = fields[key];
|
|
508
|
+
if (!def || hasCustomResolver(def)) continue;
|
|
509
|
+
if (possible.some((t) => fieldsOf(t)?.[key] && hasCustomResolver(fieldsOf(t)[key]))) continue;
|
|
510
|
+
const named = getNamedType(def.type);
|
|
511
|
+
if (isLeafType(named)) {
|
|
512
|
+
const operand = value.eq;
|
|
513
|
+
if (operand !== void 0 && operand !== null && typeof operand !== "object") out.push({
|
|
514
|
+
op: "eq",
|
|
515
|
+
path: [...prefix, key],
|
|
516
|
+
values: [operand]
|
|
517
|
+
});
|
|
518
|
+
} else if (!("elemMatch" in value) && isObjectType(named)) findIndexableEqs(value, named, [...prefix, key], schema, out);
|
|
519
|
+
}
|
|
520
|
+
return out;
|
|
521
|
+
}
|
|
522
|
+
function findIndexableOp(filter, type, prefix, schema, op) {
|
|
523
|
+
const fields = fieldsOf(type);
|
|
524
|
+
if (!fields || !filter) return void 0;
|
|
525
|
+
const possible = isInterfaceType(type) ? schema.getPossibleTypes(type) : [];
|
|
526
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
527
|
+
if (value == null || typeof value !== "object") continue;
|
|
528
|
+
const def = fields[key];
|
|
529
|
+
if (!def || hasCustomResolver(def)) continue;
|
|
530
|
+
if (possible.some((t) => fieldsOf(t)?.[key] && hasCustomResolver(fieldsOf(t)[key]))) continue;
|
|
531
|
+
const named = getNamedType(def.type);
|
|
532
|
+
if (isLeafType(named)) {
|
|
533
|
+
const operand = value[op];
|
|
534
|
+
if (op === "eq") {
|
|
535
|
+
if (operand !== void 0 && operand !== null && typeof operand !== "object") return {
|
|
536
|
+
op,
|
|
537
|
+
path: [...prefix, key],
|
|
538
|
+
values: [operand]
|
|
539
|
+
};
|
|
540
|
+
} else if (operand !== void 0) {
|
|
541
|
+
const list = [].concat(operand);
|
|
542
|
+
if (list.length <= MAX_INDEXED_IN && list.every(isPrimitive)) return {
|
|
543
|
+
op,
|
|
544
|
+
path: [...prefix, key],
|
|
545
|
+
values: list
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
} else if (!("elemMatch" in value) && isObjectType(named)) {
|
|
549
|
+
const found = findIndexableOp(value, named, [...prefix, key], schema, op);
|
|
550
|
+
if (found) return found;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Positions (in a node list) of the nodes in some buckets, ascending and each once: candidates in
|
|
556
|
+
* the order of the list, i.e. the order of an unindexed query (never bucket or value order).
|
|
557
|
+
*/
|
|
558
|
+
function unionOfPositions(buckets) {
|
|
559
|
+
let total = 0;
|
|
560
|
+
for (const bucket of buckets) if (bucket) total += bucket.length;
|
|
561
|
+
const all = new Uint32Array(total);
|
|
562
|
+
let k = 0;
|
|
563
|
+
for (const bucket of buckets) if (bucket) for (let j = 0; j < bucket.length; j++) all[k++] = bucket[j];
|
|
564
|
+
all.sort();
|
|
565
|
+
let n = 0;
|
|
566
|
+
for (let j = 0; j < total; j++) if (j === 0 || all[j] !== all[j - 1]) all[n++] = all[j];
|
|
567
|
+
return all.subarray(0, n);
|
|
568
|
+
}
|
|
569
|
+
function getIndex(typeNames, path) {
|
|
570
|
+
const key = `${typeNames.join("|")}::${path.join(".")}`;
|
|
571
|
+
const cached = indexCache.get(key);
|
|
572
|
+
if (cached && cached.version === dataVersion) return cached.index;
|
|
573
|
+
const index = /* @__PURE__ */ new Map();
|
|
574
|
+
for (const node of getNodesForTypes(typeNames)) {
|
|
575
|
+
const v = getValueAt(node, path);
|
|
576
|
+
const values = Array.isArray(v) ? new Set(v) : [v];
|
|
577
|
+
for (const value of values) {
|
|
578
|
+
if (value === void 0 || value === null) continue;
|
|
579
|
+
let bucket = index.get(value);
|
|
580
|
+
if (!bucket) {
|
|
581
|
+
bucket = [];
|
|
582
|
+
index.set(value, bucket);
|
|
583
|
+
}
|
|
584
|
+
bucket.push(node);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
indexCache.set(key, {
|
|
588
|
+
version: dataVersion,
|
|
589
|
+
index
|
|
590
|
+
});
|
|
591
|
+
return index;
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Runs a filter + sort query and returns the complete (unpaginated) result list.
|
|
595
|
+
*
|
|
596
|
+
* Records the data dependencies of the query in `rc.context.nodeModel.dependencies` (when the
|
|
597
|
+
* query runs with dependency tracking) with Gatsby's semantics: queries for a single node depend
|
|
598
|
+
* on the node found (or on its types when nothing was found), list queries on their node types –
|
|
599
|
+
* plus the nodes read by resolvers to filter/sort.
|
|
600
|
+
*/
|
|
601
|
+
async function runQuery(args, rc) {
|
|
602
|
+
const byId = runIdQuery(args, rc);
|
|
603
|
+
if (byId) return byId;
|
|
604
|
+
const { schema } = rc;
|
|
605
|
+
const type = typeof args.type === "string" ? schema.getType(args.type) : args.type;
|
|
606
|
+
if (!type) throw new Error(`Unknown type "${String(args.type)}"`);
|
|
607
|
+
const typeNames = getNodeTypeNames(type, schema);
|
|
608
|
+
if (typeNames.length === 0) return [];
|
|
609
|
+
readingNodesOfTypes(typeNames);
|
|
610
|
+
const tracked = rc.context?.nodeModel?.dependencies;
|
|
611
|
+
const { nodes, deps } = await runQueryInternal(args, rc, type, typeNames);
|
|
612
|
+
if (tracked) {
|
|
613
|
+
tracked.merge(deps);
|
|
614
|
+
if (args.firstOnly && nodes[0] && !normalizeSort(args.query?.sort).length) tracked.addNode(nodes[0].id);
|
|
615
|
+
else for (const t of typeNames) tracked.addConnection(t);
|
|
616
|
+
}
|
|
617
|
+
return nodes;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* `runQuery` of the most common page query, `x(id: { eq })`, answered synchronously (a node
|
|
621
|
+
* lookup) with the same result and dependencies. Undefined: another query (or an unknown type,
|
|
622
|
+
* which `runQuery` reports).
|
|
623
|
+
*/
|
|
624
|
+
function runIdQuery(args, rc) {
|
|
625
|
+
const id = idEq(args.query?.filter);
|
|
626
|
+
if (id === void 0) return void 0;
|
|
627
|
+
const { schema } = rc;
|
|
628
|
+
const type = typeof args.type === "string" ? schema.getType(args.type) : args.type;
|
|
629
|
+
if (!type) return void 0;
|
|
630
|
+
const typeNames = getNodeTypeNames(type, schema);
|
|
631
|
+
if (typeNames.length === 0) return [];
|
|
632
|
+
readingNodesOfTypes(typeNames);
|
|
633
|
+
const sorts = normalizeSort(args.query?.sort);
|
|
634
|
+
followDataStore();
|
|
635
|
+
const node = getDataStore().getNode(id);
|
|
636
|
+
const nodes = node && typeNames.includes(node.internal.type) ? [node] : [];
|
|
637
|
+
const tracked = rc.context?.nodeModel?.dependencies;
|
|
638
|
+
if (tracked) {
|
|
639
|
+
if (args.firstOnly && nodes[0] && !sorts.length) tracked.addNode(nodes[0].id);
|
|
640
|
+
else for (const t of typeNames) tracked.addConnection(t);
|
|
641
|
+
}
|
|
642
|
+
return nodes;
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Values JSON writes faithfully. nodeModel callers may pass others (RegExp, Date, NaN, undefined in
|
|
646
|
+
* lists, ...) that JSON writes like different values: such filters are not cached.
|
|
647
|
+
*/
|
|
648
|
+
function isJsonValue(value) {
|
|
649
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
650
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
651
|
+
if (Array.isArray(value)) return value.every(isJsonValue);
|
|
652
|
+
if (typeof value !== "object") return false;
|
|
653
|
+
const proto = Object.getPrototypeOf(value);
|
|
654
|
+
return (proto === Object.prototype || proto === null) && Object.values(value).every((v) => v === void 0 || isJsonValue(v));
|
|
655
|
+
}
|
|
656
|
+
/** the key of a cached result (none for a filter of other values) */
|
|
657
|
+
function resultKey(type, typeNames, filter, sorts) {
|
|
658
|
+
if (filter != null && !isJsonValue(filter)) return void 0;
|
|
659
|
+
return `${type.name}::${typeNames.join("|")}::${JSON.stringify(filter ?? null)}::${JSON.stringify(sorts)}`;
|
|
660
|
+
}
|
|
661
|
+
let dataStoreGeneration = getDataStoreGeneration();
|
|
662
|
+
/**
|
|
663
|
+
* The eager path's caches (node lists, indexes, results, views) are checked against `dataVersion`
|
|
664
|
+
* only: after setDataStore they would still hold the previous store's nodes. (The lazy path's
|
|
665
|
+
* stamps include the store generation.)
|
|
666
|
+
*/
|
|
667
|
+
function followDataStore() {
|
|
668
|
+
const generation = getDataStoreGeneration();
|
|
669
|
+
if (generation === dataStoreGeneration) return;
|
|
670
|
+
dataStoreGeneration = generation;
|
|
671
|
+
bump();
|
|
672
|
+
}
|
|
673
|
+
async function runQueryInternal(args, rc, type, typeNames) {
|
|
674
|
+
const { schema } = rc;
|
|
675
|
+
const filter = args.query?.filter;
|
|
676
|
+
const sorts = normalizeSort(args.query?.sort);
|
|
677
|
+
const hasFilter = !!filter && Object.keys(filter).length > 0;
|
|
678
|
+
followDataStore();
|
|
679
|
+
const version = dataVersion;
|
|
680
|
+
const id = idEq(filter);
|
|
681
|
+
if (id !== void 0) {
|
|
682
|
+
const node = getDataStore().getNode(id);
|
|
683
|
+
return { nodes: node && typeNames.includes(node.internal.type) ? [node] : [] };
|
|
684
|
+
}
|
|
685
|
+
if (isLazyStore()) {
|
|
686
|
+
const { ids, deps } = await runLazyQueryIds(args, rc, type, typeNames);
|
|
687
|
+
return {
|
|
688
|
+
nodes: nodesByIds(args.firstOnly ? ids.slice(0, 1) : ids),
|
|
689
|
+
deps
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
if (!hasFilter && !sorts.length) return { nodes: getNodesForTypes(typeNames) };
|
|
693
|
+
const indexable = hasFilter ? findIndexableOp(filter, type, [], schema, "eq") : void 0;
|
|
694
|
+
if (indexable) return sortAndFilter(args, rc, type, getIndex(typeNames, indexable.path).get(indexable.values[0]) ?? [], void 0, version);
|
|
695
|
+
const cacheKey = resultKey(type, typeNames, filter, sorts);
|
|
696
|
+
if (cacheKey === void 0) return sortAndFilter(args, rc, type, getNodesForTypes(typeNames), void 0, version);
|
|
697
|
+
const cached = resultCache.get(cacheKey);
|
|
698
|
+
if (cached && cached.version === dataVersion) {
|
|
699
|
+
resultCache.touch(cacheKey);
|
|
700
|
+
return {
|
|
701
|
+
nodes: cached.value,
|
|
702
|
+
deps: cached.deps
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
return shared(`eager:${version}:${args.firstOnly && !sorts.length ? "first:" : ""}${cacheKey}`, () => sortAndFilter(args, rc, type, getNodesForTypes(typeNames), cacheKey, version));
|
|
706
|
+
}
|
|
707
|
+
/** filters and sorts candidate nodes (and caches the result under `cacheKey`) */
|
|
708
|
+
async function sortAndFilter(args, rc, type, nodes, cacheKey, version) {
|
|
709
|
+
const { schema } = rc;
|
|
710
|
+
const filter = args.query?.filter;
|
|
711
|
+
const sorts = normalizeSort(args.query?.sort);
|
|
712
|
+
const hasFilter = !!filter && Object.keys(filter).length > 0;
|
|
713
|
+
const tree = /* @__PURE__ */ new Map();
|
|
714
|
+
if (hasFilter) filterToTree(filter, tree);
|
|
715
|
+
for (const s of sorts) addPath(tree, s.path);
|
|
716
|
+
const needsResolve = tree.size > 0 && treeNeedsResolve(tree, type, schema);
|
|
717
|
+
let pairs;
|
|
718
|
+
let deps;
|
|
719
|
+
if (needsResolve) {
|
|
720
|
+
const tk = treeKey(tree);
|
|
721
|
+
const nodeModel = rc.context?.nodeModel;
|
|
722
|
+
pairs = await Promise.all(nodes.map(async (node) => {
|
|
723
|
+
let views = viewCache.get(node);
|
|
724
|
+
if (!views) {
|
|
725
|
+
views = /* @__PURE__ */ new Map();
|
|
726
|
+
viewCache.set(node, views);
|
|
727
|
+
}
|
|
728
|
+
const vk = `${dataVersion}:${tk}`;
|
|
729
|
+
let view = views.get(vk);
|
|
730
|
+
if (view === void 0) {
|
|
731
|
+
const concrete = isAbstractType(type) ? schema.getType(node.internal.type) : type;
|
|
732
|
+
const collected = new QueryDependencies();
|
|
733
|
+
const viewRc = typeof nodeModel?.withDependencies === "function" ? {
|
|
734
|
+
...rc,
|
|
735
|
+
context: {
|
|
736
|
+
...rc.context,
|
|
737
|
+
nodeModel: nodeModel.withDependencies(collected)
|
|
738
|
+
}
|
|
739
|
+
} : rc;
|
|
740
|
+
trackInlineObjects(node);
|
|
741
|
+
view = project(await materialize(node, concrete, tree, viewRc), tree);
|
|
742
|
+
if (collected.size && view !== null && typeof view === "object") viewDeps.set(view, collected);
|
|
743
|
+
if (views.size > 8) views.clear();
|
|
744
|
+
views.set(vk, view);
|
|
745
|
+
}
|
|
746
|
+
return {
|
|
747
|
+
node,
|
|
748
|
+
view
|
|
749
|
+
};
|
|
750
|
+
}));
|
|
751
|
+
for (const p of pairs) {
|
|
752
|
+
const d = p.view !== null && typeof p.view === "object" ? viewDeps.get(p.view) : void 0;
|
|
753
|
+
if (d) (deps ??= new QueryDependencies()).merge(d);
|
|
754
|
+
}
|
|
755
|
+
} else pairs = nodes.map((node) => ({
|
|
756
|
+
node,
|
|
757
|
+
view: node
|
|
758
|
+
}));
|
|
759
|
+
if (hasFilter) {
|
|
760
|
+
const predicate = compileFilter(filter, type);
|
|
761
|
+
if (args.firstOnly && !sorts.length) {
|
|
762
|
+
const found = pairs.find((p) => predicate(p.view));
|
|
763
|
+
return {
|
|
764
|
+
nodes: found ? [found.node] : [],
|
|
765
|
+
deps
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
pairs = pairs.filter((p) => predicate(p.view));
|
|
769
|
+
}
|
|
770
|
+
if (sorts.length) {
|
|
771
|
+
const getters = sorts.map((s) => ({
|
|
772
|
+
path: s.path,
|
|
773
|
+
dir: s.order === "DESC" ? -1 : 1
|
|
774
|
+
}));
|
|
775
|
+
const keyed = pairs.map((p, i) => ({
|
|
776
|
+
p,
|
|
777
|
+
i,
|
|
778
|
+
keys: getters.map((g) => getValueAt(p.view, g.path))
|
|
779
|
+
}));
|
|
780
|
+
keyed.sort((a, b) => {
|
|
781
|
+
for (let k = 0; k < getters.length; k++) {
|
|
782
|
+
const c = compareAscending(a.keys[k], b.keys[k]);
|
|
783
|
+
if (c !== 0) return c * getters[k].dir;
|
|
784
|
+
}
|
|
785
|
+
return a.i - b.i;
|
|
786
|
+
});
|
|
787
|
+
pairs = keyed.map((k) => k.p);
|
|
788
|
+
}
|
|
789
|
+
const result = pairs.map((p) => p.node);
|
|
790
|
+
if (cacheKey) resultCache.set(cacheKey, {
|
|
791
|
+
version,
|
|
792
|
+
value: result,
|
|
793
|
+
deps
|
|
794
|
+
}, result.length);
|
|
795
|
+
return {
|
|
796
|
+
nodes: result,
|
|
797
|
+
deps
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
/** `{ id: { eq: "…" } }` (and nothing else) */
|
|
801
|
+
function idEq(filter) {
|
|
802
|
+
if (!filter || typeof filter !== "object") return void 0;
|
|
803
|
+
const keys = Object.keys(filter);
|
|
804
|
+
if (keys.length !== 1 || keys[0] !== "id") return void 0;
|
|
805
|
+
const op = filter.id;
|
|
806
|
+
if (!op || typeof op !== "object") return void 0;
|
|
807
|
+
const ops = Object.keys(op);
|
|
808
|
+
return ops.length === 1 && ops[0] === "eq" && typeof op.eq === "string" ? op.eq : void 0;
|
|
809
|
+
}
|
|
810
|
+
function isLazyStore() {
|
|
811
|
+
return getDataStore().lazy === true;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* The top-level fields of a connection's nodes that the query reads: the fields selected on its
|
|
815
|
+
* nodes (`nodes`, `edges { node next previous }`, also inside `group`) and the fields of its
|
|
816
|
+
* aggregations (`distinct`, `group`, `max`, `min`, `sum`). Undefined when the nodes must be whole:
|
|
817
|
+
* a selected field has a resolver that may read other fields of the node (anything but the
|
|
818
|
+
* default resolver and `@link`/`@dateformat` of their own field), or the selection has something
|
|
819
|
+
* else (e.g. a field a plugin added to the connection).
|
|
820
|
+
*/
|
|
821
|
+
function connectionReadFields(info, typeName) {
|
|
822
|
+
const type = info.schema.getType(typeName);
|
|
823
|
+
const connection = getNamedType(info.returnType);
|
|
824
|
+
if (!isObjectType(type) || !isObjectType(connection)) return void 0;
|
|
825
|
+
const fields = type.getFields();
|
|
826
|
+
const heads = /* @__PURE__ */ new Set();
|
|
827
|
+
const fieldsOfSelection = (selectionSet) => {
|
|
828
|
+
const out = [];
|
|
829
|
+
const visit = (set, depth) => {
|
|
830
|
+
if (!set || depth > 16) return;
|
|
831
|
+
for (const selection of set.selections) if (selection.kind === "Field") out.push(selection);
|
|
832
|
+
else if (selection.kind === "InlineFragment") visit(selection.selectionSet, depth + 1);
|
|
833
|
+
else visit(info.fragments[selection.name.value]?.selectionSet, depth + 1);
|
|
834
|
+
};
|
|
835
|
+
visit(selectionSet, 0);
|
|
836
|
+
return out;
|
|
837
|
+
};
|
|
838
|
+
const nodeFields = (selectionSet) => {
|
|
839
|
+
for (const field of fieldsOfSelection(selectionSet)) {
|
|
840
|
+
const name = field.name.value;
|
|
841
|
+
if (name === "__typename") continue;
|
|
842
|
+
const def = fields[name];
|
|
843
|
+
if (!def || !readsOwnFieldOnly(def.resolve)) return false;
|
|
844
|
+
heads.add(name);
|
|
845
|
+
}
|
|
846
|
+
return true;
|
|
847
|
+
};
|
|
848
|
+
const aggregated = (field, connectionType) => {
|
|
849
|
+
const def = connectionType.getFields()[field.name.value];
|
|
850
|
+
if (!def) return false;
|
|
851
|
+
try {
|
|
852
|
+
const path = fieldSelectorToPath(getArgumentValues(def, field, info.variableValues).field);
|
|
853
|
+
const head = path.split(".")[0];
|
|
854
|
+
if (!path || !fields[head] || !readsOwnFieldOnly(fields[head].resolve)) return false;
|
|
855
|
+
heads.add(head);
|
|
856
|
+
return true;
|
|
857
|
+
} catch {
|
|
858
|
+
return false;
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
const connectionFields = (selectionSet, connectionType, depth) => {
|
|
862
|
+
for (const field of fieldsOfSelection(selectionSet)) switch (field.name.value) {
|
|
863
|
+
case "__typename":
|
|
864
|
+
case "totalCount":
|
|
865
|
+
case "pageInfo":
|
|
866
|
+
case "field":
|
|
867
|
+
case "fieldValue": break;
|
|
868
|
+
case "nodes":
|
|
869
|
+
if (!nodeFields(field.selectionSet)) return false;
|
|
870
|
+
break;
|
|
871
|
+
case "edges":
|
|
872
|
+
for (const edge of fieldsOfSelection(field.selectionSet)) {
|
|
873
|
+
const name = edge.name.value;
|
|
874
|
+
if (name === "__typename") continue;
|
|
875
|
+
if (name !== "node" && name !== "next" && name !== "previous") return false;
|
|
876
|
+
if (!nodeFields(edge.selectionSet)) return false;
|
|
877
|
+
}
|
|
878
|
+
break;
|
|
879
|
+
case "distinct":
|
|
880
|
+
case "max":
|
|
881
|
+
case "min":
|
|
882
|
+
case "sum":
|
|
883
|
+
if (!aggregated(field, connectionType)) return false;
|
|
884
|
+
break;
|
|
885
|
+
case "group": {
|
|
886
|
+
if (depth > 2 || !aggregated(field, connectionType)) return false;
|
|
887
|
+
const group = getNamedType(connectionType.getFields().group.type);
|
|
888
|
+
if (!isObjectType(group) || !connectionFields(field.selectionSet, group, depth + 1)) return false;
|
|
889
|
+
break;
|
|
890
|
+
}
|
|
891
|
+
default: return false;
|
|
892
|
+
}
|
|
893
|
+
return true;
|
|
894
|
+
};
|
|
895
|
+
for (const fieldNode of info.fieldNodes) if (!connectionFields(fieldNode.selectionSet, connection, 0)) return void 0;
|
|
896
|
+
return heads;
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* A node a query returns, as a copy of its slim node when the slim nodes of its type are current
|
|
900
|
+
* and none of the fields `reads` was left out of it (a query that selects e.g. `id` and `slug` of
|
|
901
|
+
* every post decodes no whole node). Undefined: the store's node is needed.
|
|
902
|
+
*/
|
|
903
|
+
function slimResultNode(id, reads, setOf = currentSlimSet) {
|
|
904
|
+
const ds = getDataStore();
|
|
905
|
+
const set = setOf(typeof ds.getNodeType === "function" ? ds.getNodeType(id) : void 0);
|
|
906
|
+
if (!set) return void 0;
|
|
907
|
+
set.positions ??= new Map(set.ids.map((nodeId, i) => [nodeId, i]));
|
|
908
|
+
const at = set.positions.get(id);
|
|
909
|
+
if (at === void 0) return void 0;
|
|
910
|
+
const left = set.omitted.get(at);
|
|
911
|
+
if (left && left.some((key) => reads.has(key))) return void 0;
|
|
912
|
+
return { ...set.nodes[at] };
|
|
913
|
+
}
|
|
914
|
+
/** the slim set of a type, when it has all of the type's current nodes */
|
|
915
|
+
function currentSlimSet(type) {
|
|
916
|
+
const set = type === void 0 ? void 0 : slimSets.get(type);
|
|
917
|
+
if (!set || set.tooLarge !== void 0 || set.stamp !== typesStamp([type])) return void 0;
|
|
918
|
+
return set;
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Nodes for ids that a query returns (connections). `reads`: the top-level fields the query reads
|
|
922
|
+
* of them (connectionReadFields); then copies of current slim nodes where they have them all.
|
|
923
|
+
* Missing ones are skipped.
|
|
924
|
+
*/
|
|
925
|
+
function queryResultNodes(ids, reads) {
|
|
926
|
+
if (!ids.length) return [];
|
|
927
|
+
if (!reads) return nodesByIds(ids);
|
|
928
|
+
let looked = false;
|
|
929
|
+
let lastType;
|
|
930
|
+
let lastSet;
|
|
931
|
+
const setOf = (type) => {
|
|
932
|
+
if (!looked || type !== lastType) {
|
|
933
|
+
looked = true;
|
|
934
|
+
lastType = type;
|
|
935
|
+
lastSet = currentSlimSet(type);
|
|
936
|
+
}
|
|
937
|
+
return lastSet;
|
|
938
|
+
};
|
|
939
|
+
const nodes = ids.map((id) => slimResultNode(id, reads, setOf));
|
|
940
|
+
const missing = [];
|
|
941
|
+
for (let i = 0; i < ids.length; i++) if (!nodes[i]) missing.push(ids[i]);
|
|
942
|
+
if (missing.length === ids.length) return nodesByIds(ids);
|
|
943
|
+
if (missing.length) {
|
|
944
|
+
const found = new Map(nodesByIds(missing).map((n) => [n.id, n]));
|
|
945
|
+
for (let i = 0; i < ids.length; i++) nodes[i] ??= found.get(ids[i]);
|
|
946
|
+
}
|
|
947
|
+
return nodes.filter((n) => !!n);
|
|
948
|
+
}
|
|
949
|
+
/** a node a query returns (see queryResultNodes) */
|
|
950
|
+
function queryResultNode(id, reads) {
|
|
951
|
+
return reads && slimResultNode(id, reads) || getDataStore().getNode(id);
|
|
952
|
+
}
|
|
953
|
+
/** nodes for ids (missing ones are skipped) */
|
|
954
|
+
function nodesByIds(ids) {
|
|
955
|
+
if (!ids.length) return [];
|
|
956
|
+
const ds = getDataStore();
|
|
957
|
+
return (typeof ds.getNodesByIds === "function" ? ds.getNodesByIds(ids) : ids.map((id) => ds.getNode(id))).filter((n) => !!n);
|
|
958
|
+
}
|
|
959
|
+
/** nodes for ids, in the order of `ids` (undefined: missing) */
|
|
960
|
+
function nodesAt(ids) {
|
|
961
|
+
if (!ids.length) return [];
|
|
962
|
+
const ds = getDataStore();
|
|
963
|
+
return typeof ds.getNodesByIds === "function" ? ds.getNodesByIds(ids) : ids.map((id) => ds.getNode(id));
|
|
964
|
+
}
|
|
965
|
+
const lazyIndexCache = /* @__PURE__ */ new Map();
|
|
966
|
+
const lazyViewCache = /* @__PURE__ */ new Map();
|
|
967
|
+
const lazyResultCache = new ResultCache();
|
|
968
|
+
const MAX_LAZY_VIEW_SETS = 32;
|
|
969
|
+
function clearLazyQueryCaches() {
|
|
970
|
+
slimSets.clear();
|
|
971
|
+
slimBytes = 0;
|
|
972
|
+
lazyIdsCache.clear();
|
|
973
|
+
lazyIndexCache.clear();
|
|
974
|
+
lazyViewCache.clear();
|
|
975
|
+
lazyResultCache.clear();
|
|
976
|
+
}
|
|
977
|
+
const lazyIdsCache = /* @__PURE__ */ new Map();
|
|
978
|
+
/**
|
|
979
|
+
* All node ids of the types in insertion order. Cached (the store copies its id list for every
|
|
980
|
+
* call): callers only read or slice it.
|
|
981
|
+
*/
|
|
982
|
+
function lazyIds(typeNames) {
|
|
983
|
+
return lazyIdsEntry(typeNames).ids;
|
|
984
|
+
}
|
|
985
|
+
function lazyIdsEntry(typeNames) {
|
|
986
|
+
const key = typeNames.join("|");
|
|
987
|
+
const stamp = typesStamp(typeNames);
|
|
988
|
+
const cached = lazyIdsCache.get(key);
|
|
989
|
+
if (cached && cached.stamp === stamp) return cached;
|
|
990
|
+
const ds = getDataStore();
|
|
991
|
+
let ids;
|
|
992
|
+
if (typeNames.length === 1 && typeof ds.getNodeIdsByType === "function") ids = ds.getNodeIdsByType(typeNames[0]);
|
|
993
|
+
else {
|
|
994
|
+
const all = [];
|
|
995
|
+
for (const t of typeNames) for (const node of ds.iterateNodesByType(t)) all.push({
|
|
996
|
+
id: detachString(node.id),
|
|
997
|
+
counter: node.internal.counter ?? 0
|
|
998
|
+
});
|
|
999
|
+
ids = all.sort((a, b) => a.counter - b.counter).map((e) => e.id);
|
|
1000
|
+
}
|
|
1001
|
+
if (lazyIdsCache.size >= 256) lazyIdsCache.delete(lazyIdsCache.keys().next().value);
|
|
1002
|
+
const entry = {
|
|
1003
|
+
stamp,
|
|
1004
|
+
ids
|
|
1005
|
+
};
|
|
1006
|
+
lazyIdsCache.set(key, entry);
|
|
1007
|
+
return entry;
|
|
1008
|
+
}
|
|
1009
|
+
function lazyPositions(typeNames) {
|
|
1010
|
+
const entry = lazyIdsEntry(typeNames);
|
|
1011
|
+
entry.positions ??= new Map(entry.ids.map((id, i) => [id, i]));
|
|
1012
|
+
return entry;
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Top-level fields of about this size or more are left out of slim nodes: strings of 1,024
|
|
1016
|
+
* characters or more (e.g. a post's HTML) and objects or lists that large (e.g. rich text as JSON,
|
|
1017
|
+
* a list of images).
|
|
1018
|
+
*/
|
|
1019
|
+
const SLIM_OMIT_BYTES = 2064;
|
|
1020
|
+
/** slim sets of a thread take at most about this much memory (estimated), else types are scanned */
|
|
1021
|
+
let SLIM_BUDGET = slimBudgetMb(process.env.GOATLY_SLIM_NODES_MB) * 1024 * 1024;
|
|
1022
|
+
function slimBudgetMb(value) {
|
|
1023
|
+
const mb = Number(value ?? 128);
|
|
1024
|
+
return Number.isFinite(mb) && mb >= 0 ? mb : 128;
|
|
1025
|
+
}
|
|
1026
|
+
/** fields the engine reads from every node it gets: never left out */
|
|
1027
|
+
const SLIM_KEEP = /* @__PURE__ */ new Set([
|
|
1028
|
+
"id",
|
|
1029
|
+
"parent",
|
|
1030
|
+
"children",
|
|
1031
|
+
"internal"
|
|
1032
|
+
]);
|
|
1033
|
+
/**
|
|
1034
|
+
* Query workers: slim nodes take a tenth of the worker's heap (`heapMb`, its budget or limit),
|
|
1035
|
+
* 128–512 MB, unless GOATLY_SLIM_NODES_MB is set. A type over the budget costs more than its
|
|
1036
|
+
* slim nodes would: each of its view sets and indexes decodes every whole node of the type.
|
|
1037
|
+
*/
|
|
1038
|
+
function setSlimNodesHeap(heapMb) {
|
|
1039
|
+
if (process.env.GOATLY_SLIM_NODES_MB !== void 0 || !(heapMb > 0)) return;
|
|
1040
|
+
SLIM_BUDGET = Math.min(512, Math.max(128, Math.round(heapMb / 10))) * 1024 * 1024;
|
|
1041
|
+
}
|
|
1042
|
+
/** (tests) the memory for slim nodes in bytes */
|
|
1043
|
+
function setSlimNodesBudget(bytes) {
|
|
1044
|
+
SLIM_BUDGET = bytes;
|
|
1045
|
+
clearSlimNodes();
|
|
1046
|
+
}
|
|
1047
|
+
const slimSets = /* @__PURE__ */ new Map();
|
|
1048
|
+
let slimBytes = 0;
|
|
1049
|
+
/**
|
|
1050
|
+
* Bytes that approxSize and sizeUpTo counted beyond V8's size of one-byte strings since it was
|
|
1051
|
+
* reset (they count every character as 2 bytes). V8 keeps strings of Latin-1 characters at one
|
|
1052
|
+
* byte per character, in about 32 + length bytes: a flat string's 16-byte header, and 16 more for
|
|
1053
|
+
* the slice of a decoded node's string or the string table entry of an interned copy (see
|
|
1054
|
+
* detachString). A slim set's estimate subtracts the difference, for strings of 16 or more
|
|
1055
|
+
* characters (shorter ones are counted as before). JavaScriptCore's strings take more memory
|
|
1056
|
+
* besides: there the estimate stays as it is.
|
|
1057
|
+
*/
|
|
1058
|
+
let oneByteSaving = 0;
|
|
1059
|
+
const countOneByte = !isBun;
|
|
1060
|
+
/** any character beyond Latin-1 (V8 then keeps the string at two bytes per character) */
|
|
1061
|
+
const TWO_BYTE = /[\u0100-\uffff]/;
|
|
1062
|
+
/**
|
|
1063
|
+
* strings this long are counted at 2 bytes per character (unread: a field with one is left out
|
|
1064
|
+
* of slim nodes, unless it is one of SLIM_KEEP's)
|
|
1065
|
+
*/
|
|
1066
|
+
const ONE_BYTE_CHECKED = 1024;
|
|
1067
|
+
function stringSize(value) {
|
|
1068
|
+
const { length } = value;
|
|
1069
|
+
if (countOneByte && length > 16 && length < ONE_BYTE_CHECKED && !TWO_BYTE.test(value)) oneByteSaving += length - 16;
|
|
1070
|
+
return 16 + length * 2;
|
|
1071
|
+
}
|
|
1072
|
+
/** a rough size of a value in memory (strings 2 bytes per character) */
|
|
1073
|
+
function approxSize(value, depth = 0) {
|
|
1074
|
+
if (typeof value === "string") return stringSize(value);
|
|
1075
|
+
if (value === null || typeof value !== "object") return 8;
|
|
1076
|
+
if (depth > 4) return 64;
|
|
1077
|
+
let size = 32;
|
|
1078
|
+
if (Array.isArray(value)) for (const v of value) size += 8 + approxSize(v, depth + 1);
|
|
1079
|
+
else for (const k in value) size += 24 + approxSize(value[k], depth + 1);
|
|
1080
|
+
return size;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* approxSize without its depth limit, up to `limit`: whether a field is large (e.g. rich text as
|
|
1084
|
+
* nested JSON, whose content approxSize counts as 64 bytes per object from depth 5 on)
|
|
1085
|
+
*/
|
|
1086
|
+
function sizeUpTo(value, limit) {
|
|
1087
|
+
if (typeof value === "string") return stringSize(value);
|
|
1088
|
+
if (value === null || typeof value !== "object") return 8;
|
|
1089
|
+
let size = 0;
|
|
1090
|
+
const stack = [value];
|
|
1091
|
+
while (stack.length && size < limit) {
|
|
1092
|
+
const v = stack.pop();
|
|
1093
|
+
if (typeof v === "string") size += stringSize(v);
|
|
1094
|
+
else if (v === null || typeof v !== "object") size += 8;
|
|
1095
|
+
else if (Array.isArray(v)) {
|
|
1096
|
+
size += 32;
|
|
1097
|
+
for (const item of v) {
|
|
1098
|
+
if ((size += 8) >= limit) break;
|
|
1099
|
+
stack.push(item);
|
|
1100
|
+
}
|
|
1101
|
+
} else {
|
|
1102
|
+
size += 32;
|
|
1103
|
+
for (const k in v) {
|
|
1104
|
+
if ((size += 24) >= limit) break;
|
|
1105
|
+
stack.push(v[k]);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
return size;
|
|
1110
|
+
}
|
|
1111
|
+
function slimSetOf(type) {
|
|
1112
|
+
const stamp = typesStamp([type]);
|
|
1113
|
+
const cached = slimSets.get(type);
|
|
1114
|
+
if (cached && cached.stamp === stamp) {
|
|
1115
|
+
if (cached.tooLarge === void 0) return cached;
|
|
1116
|
+
if (slimBytes >= cached.tooLarge) return void 0;
|
|
1117
|
+
}
|
|
1118
|
+
for (const [t, set] of slimSets) if (t === type || set.stamp !== typesStamp([t])) {
|
|
1119
|
+
slimBytes -= set.bytes;
|
|
1120
|
+
slimSets.delete(t);
|
|
1121
|
+
}
|
|
1122
|
+
const set = {
|
|
1123
|
+
stamp,
|
|
1124
|
+
ids: [],
|
|
1125
|
+
nodes: [],
|
|
1126
|
+
omitted: /* @__PURE__ */ new Map(),
|
|
1127
|
+
bytes: 0
|
|
1128
|
+
};
|
|
1129
|
+
const scan = getDataStore().iterateNodesByType(type)[Symbol.iterator]();
|
|
1130
|
+
try {
|
|
1131
|
+
for (let next = scan.next(); !next.done; next = scan.next()) {
|
|
1132
|
+
const node = next.value;
|
|
1133
|
+
let slim = node;
|
|
1134
|
+
let omitted;
|
|
1135
|
+
let size = 96;
|
|
1136
|
+
oneByteSaving = 0;
|
|
1137
|
+
for (const key in node) {
|
|
1138
|
+
const value = node[key];
|
|
1139
|
+
if (SLIM_KEEP.has(key)) {
|
|
1140
|
+
size += 24 + approxSize(value);
|
|
1141
|
+
continue;
|
|
1142
|
+
}
|
|
1143
|
+
const saving = oneByteSaving;
|
|
1144
|
+
const bytes = sizeUpTo(value, SLIM_OMIT_BYTES);
|
|
1145
|
+
if (bytes >= SLIM_OMIT_BYTES) {
|
|
1146
|
+
(omitted ??= []).push(key);
|
|
1147
|
+
oneByteSaving = saving;
|
|
1148
|
+
} else size += 24 + bytes;
|
|
1149
|
+
}
|
|
1150
|
+
size -= oneByteSaving;
|
|
1151
|
+
if (omitted) {
|
|
1152
|
+
slim = {};
|
|
1153
|
+
for (const key in node) if (!omitted.includes(key)) slim[key] = detachValue(node[key]);
|
|
1154
|
+
set.omitted.set(set.nodes.length, omitted);
|
|
1155
|
+
}
|
|
1156
|
+
set.bytes += size;
|
|
1157
|
+
set.ids.push(slim.id);
|
|
1158
|
+
set.nodes.push(slim);
|
|
1159
|
+
const expected = set.nodes.length === 256 ? set.bytes / set.nodes.length * getDataStore().countNodes(type) : set.bytes;
|
|
1160
|
+
if (slimBytes + expected > SLIM_BUDGET) {
|
|
1161
|
+
slimSets.set(type, {
|
|
1162
|
+
stamp,
|
|
1163
|
+
tooLarge: slimBytes,
|
|
1164
|
+
ids: [],
|
|
1165
|
+
nodes: [],
|
|
1166
|
+
omitted: /* @__PURE__ */ new Map(),
|
|
1167
|
+
bytes: 0
|
|
1168
|
+
});
|
|
1169
|
+
return {
|
|
1170
|
+
givenUp: set,
|
|
1171
|
+
rest: scan
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
} catch (error) {
|
|
1176
|
+
scan.return?.();
|
|
1177
|
+
throw error;
|
|
1178
|
+
}
|
|
1179
|
+
slimBytes += set.bytes;
|
|
1180
|
+
slimSets.set(type, set);
|
|
1181
|
+
return set;
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* The nodes of a type for a scan that reads the top-level fields `heads`: slim nodes (whole ones
|
|
1185
|
+
* where one of these fields was left out), or the store's nodes when the type has no slim set.
|
|
1186
|
+
*/
|
|
1187
|
+
function* scanNodes(type, heads) {
|
|
1188
|
+
const slim = heads ? slimSetOf(type) : void 0;
|
|
1189
|
+
if (!slim) {
|
|
1190
|
+
yield* getDataStore().iterateNodesByType(type);
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
const givenUp = "givenUp" in slim;
|
|
1194
|
+
const { ids, nodes, omitted } = givenUp ? slim.givenUp : slim;
|
|
1195
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
1196
|
+
const left = omitted.get(i);
|
|
1197
|
+
const node = left && left.some((key) => heads.has(key)) ? getDataStore().getNode(ids[i]) : nodes[i];
|
|
1198
|
+
if (givenUp) nodes[i] = void 0;
|
|
1199
|
+
if (node) yield node;
|
|
1200
|
+
}
|
|
1201
|
+
if (!givenUp) return;
|
|
1202
|
+
let done = false;
|
|
1203
|
+
try {
|
|
1204
|
+
for (let next = slim.rest.next(); !(done = !!next.done); next = slim.rest.next()) yield next.value;
|
|
1205
|
+
} finally {
|
|
1206
|
+
if (!done) slim.rest.return?.();
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* The top-level fields a view of the tree reads, when slim nodes give the same views: every
|
|
1211
|
+
* top-level field is read as is or by a resolver that reads only its own field (undefined: a
|
|
1212
|
+
* resolver may read other fields of the node).
|
|
1213
|
+
*/
|
|
1214
|
+
function slimHeads(tree, typeNames, schema, needsResolve) {
|
|
1215
|
+
if (needsResolve) for (const t of typeNames) {
|
|
1216
|
+
const fields = fieldsOf(schema.getType(t));
|
|
1217
|
+
if (!fields) return void 0;
|
|
1218
|
+
for (const field of tree.keys()) {
|
|
1219
|
+
const def = fields[field];
|
|
1220
|
+
if (def && hasCustomResolver(def) && !readsOwnFieldOnly(def.resolve)) return void 0;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
return new Set(tree.keys());
|
|
1224
|
+
}
|
|
1225
|
+
/** value of a field path → node ids (built with one streaming scan per path) */
|
|
1226
|
+
function lazyIndex(typeNames, path) {
|
|
1227
|
+
const key = `${typeNames.join("|")}::${path.join(".")}`;
|
|
1228
|
+
const stamp = typesStamp(typeNames);
|
|
1229
|
+
const cached = lazyIndexCache.get(key);
|
|
1230
|
+
if (cached && cached.stamp === stamp) return cached.index;
|
|
1231
|
+
const index = /* @__PURE__ */ new Map();
|
|
1232
|
+
const heads = /* @__PURE__ */ new Set([path[0]]);
|
|
1233
|
+
for (const t of typeNames) for (const node of scanNodes(t, heads)) {
|
|
1234
|
+
const v = getValueAt(node, path);
|
|
1235
|
+
let id;
|
|
1236
|
+
for (const value of Array.isArray(v) ? new Set(v) : [v]) {
|
|
1237
|
+
if (value === void 0 || value === null) continue;
|
|
1238
|
+
let bucket = index.get(value);
|
|
1239
|
+
if (!bucket) {
|
|
1240
|
+
bucket = [];
|
|
1241
|
+
index.set(typeof value === "string" ? detachString(value) : value, bucket);
|
|
1242
|
+
}
|
|
1243
|
+
bucket.push(id ??= detachString(node.id));
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
if (typeNames.length > 1) {
|
|
1247
|
+
const { positions } = lazyPositions(typeNames);
|
|
1248
|
+
for (const bucket of index.values()) bucket.sort((a, b) => positions.get(a) - positions.get(b));
|
|
1249
|
+
}
|
|
1250
|
+
lazyIndexCache.set(key, {
|
|
1251
|
+
stamp,
|
|
1252
|
+
index
|
|
1253
|
+
});
|
|
1254
|
+
return index;
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* a copy of the parts of `value` the field tree needs (small, unlike the node). Its strings are
|
|
1258
|
+
* copies (detachString): views outlive the nodes they were made of, and a decoded node's strings
|
|
1259
|
+
* would keep the node's string blocks alive.
|
|
1260
|
+
*/
|
|
1261
|
+
function project(value, tree) {
|
|
1262
|
+
if (typeof value === "string") return detachString(value);
|
|
1263
|
+
if (value === null || typeof value !== "object" || value instanceof Date) return value;
|
|
1264
|
+
if (Array.isArray(value)) return value.map((v) => project(v, tree));
|
|
1265
|
+
if (!tree) return detachValue(value);
|
|
1266
|
+
const out = {};
|
|
1267
|
+
for (const [key, sub] of tree) if (key in value) out[key] = project(value[key], sub);
|
|
1268
|
+
return out;
|
|
1269
|
+
}
|
|
1270
|
+
/**
|
|
1271
|
+
* Filter/sort values ("views") of nodes: projections, or materialized resolver fields. Built for
|
|
1272
|
+
* all nodes of the types with one streaming scan (or for some ids only) and cached by id.
|
|
1273
|
+
*/
|
|
1274
|
+
async function lazyViews(typeNames, type, tree, needsResolve, rc, ids) {
|
|
1275
|
+
const key = `${type.name}::${typeNames.join("|")}::${treeKey(tree)}`;
|
|
1276
|
+
const stampNow = () => needsResolve ? dataStamp() : typesStamp(typeNames);
|
|
1277
|
+
const stamp = stampNow();
|
|
1278
|
+
let entry = lazyViewCache.get(key);
|
|
1279
|
+
if (!entry || entry.stamp !== stamp) {
|
|
1280
|
+
entry = {
|
|
1281
|
+
stamp,
|
|
1282
|
+
complete: false,
|
|
1283
|
+
views: /* @__PURE__ */ new Map()
|
|
1284
|
+
};
|
|
1285
|
+
if (lazyViewCache.size >= MAX_LAZY_VIEW_SETS) lazyViewCache.delete(lazyViewCache.keys().next().value);
|
|
1286
|
+
lazyViewCache.set(key, entry);
|
|
1287
|
+
}
|
|
1288
|
+
if (entry.complete) return entry;
|
|
1289
|
+
const { schema } = rc;
|
|
1290
|
+
const nodeModel = rc.context?.nodeModel;
|
|
1291
|
+
const viewOf = async (node) => {
|
|
1292
|
+
if (!needsResolve) return project(node, tree);
|
|
1293
|
+
const concrete = isAbstractType(type) ? schema.getType(node.internal.type) : type;
|
|
1294
|
+
const collected = new QueryDependencies();
|
|
1295
|
+
const viewRc = typeof nodeModel?.withDependencies === "function" ? {
|
|
1296
|
+
...rc,
|
|
1297
|
+
context: {
|
|
1298
|
+
...rc.context,
|
|
1299
|
+
nodeModel: nodeModel.withDependencies(collected)
|
|
1300
|
+
}
|
|
1301
|
+
} : rc;
|
|
1302
|
+
trackInlineObjects(node);
|
|
1303
|
+
const view = project(await materialize(node, concrete, tree, viewRc), tree);
|
|
1304
|
+
if (collected.size && view !== null && typeof view === "object") viewDeps.set(view, internDeps(entry.deps ??= /* @__PURE__ */ new Map(), collected));
|
|
1305
|
+
return view;
|
|
1306
|
+
};
|
|
1307
|
+
const views = entry.views;
|
|
1308
|
+
if (ids) {
|
|
1309
|
+
const missing = ids.filter((id) => !views.has(id));
|
|
1310
|
+
for (let start = 0; start < missing.length; start += 64) {
|
|
1311
|
+
const chunk = missing.slice(start, start + 64);
|
|
1312
|
+
const found = nodesAt(chunk);
|
|
1313
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
1314
|
+
const node = found[i];
|
|
1315
|
+
if (node) views.set(chunk[i], {
|
|
1316
|
+
view: await viewOf(node),
|
|
1317
|
+
counter: node.internal.counter ?? 0
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
entry.deps = void 0;
|
|
1322
|
+
return entry;
|
|
1323
|
+
}
|
|
1324
|
+
if (entry.scanning) {
|
|
1325
|
+
await entry.scanning;
|
|
1326
|
+
return entry;
|
|
1327
|
+
}
|
|
1328
|
+
const target = entry;
|
|
1329
|
+
const heads = slimHeads(tree, typeNames, schema, needsResolve);
|
|
1330
|
+
target.scanning = (async () => {
|
|
1331
|
+
for (const t of typeNames) {
|
|
1332
|
+
const batch = [];
|
|
1333
|
+
for (const node of scanNodes(t, heads)) {
|
|
1334
|
+
if (views.has(node.id)) continue;
|
|
1335
|
+
const id = detachString(node.id);
|
|
1336
|
+
const counter = node.internal.counter ?? 0;
|
|
1337
|
+
if (!needsResolve) {
|
|
1338
|
+
views.set(id, {
|
|
1339
|
+
view: project(node, tree),
|
|
1340
|
+
counter
|
|
1341
|
+
});
|
|
1342
|
+
continue;
|
|
1343
|
+
}
|
|
1344
|
+
batch.push(viewOf(node).then((view) => {
|
|
1345
|
+
views.set(id, {
|
|
1346
|
+
view,
|
|
1347
|
+
counter
|
|
1348
|
+
});
|
|
1349
|
+
}));
|
|
1350
|
+
if (batch.length >= 256) await Promise.all(batch.splice(0));
|
|
1351
|
+
}
|
|
1352
|
+
await Promise.all(batch);
|
|
1353
|
+
}
|
|
1354
|
+
if (target.stamp === stampNow()) target.complete = true;
|
|
1355
|
+
})();
|
|
1356
|
+
try {
|
|
1357
|
+
await target.scanning;
|
|
1358
|
+
} finally {
|
|
1359
|
+
target.scanning = void 0;
|
|
1360
|
+
target.deps = void 0;
|
|
1361
|
+
}
|
|
1362
|
+
return target;
|
|
1363
|
+
}
|
|
1364
|
+
async function runLazyQueryIds(args, rc, type, typeNames) {
|
|
1365
|
+
const filter = args.query?.filter;
|
|
1366
|
+
const sorts = normalizeSort(args.query?.sort);
|
|
1367
|
+
const hasFilter = !!filter && Object.keys(filter).length > 0;
|
|
1368
|
+
const id = idEq(filter);
|
|
1369
|
+
if (id !== void 0) {
|
|
1370
|
+
const node = getDataStore().getNode(id);
|
|
1371
|
+
return { ids: node && typeNames.includes(node.internal.type) ? [id] : [] };
|
|
1372
|
+
}
|
|
1373
|
+
if (!hasFilter && !sorts.length) return { ids: lazyIds(typeNames) };
|
|
1374
|
+
const tree = /* @__PURE__ */ new Map();
|
|
1375
|
+
if (hasFilter) filterToTree(filter, tree);
|
|
1376
|
+
for (const s of sorts) addPath(tree, s.path);
|
|
1377
|
+
const needsResolve = treeNeedsResolve(tree, type, rc.schema);
|
|
1378
|
+
const stamp = needsResolve ? dataStamp() : typesStamp(typeNames);
|
|
1379
|
+
const cacheKey = resultKey(type, typeNames, filter, sorts);
|
|
1380
|
+
const cached = cacheKey !== void 0 ? lazyResultCache.get(cacheKey) : void 0;
|
|
1381
|
+
if (cached && cached.stamp === stamp) {
|
|
1382
|
+
lazyResultCache.touch(cacheKey);
|
|
1383
|
+
return {
|
|
1384
|
+
ids: cached.ids,
|
|
1385
|
+
deps: cached.deps
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
const compute = () => computeLazyQueryIds(args, rc, type, typeNames, tree, needsResolve, stamp, cacheKey);
|
|
1389
|
+
return cacheKey === void 0 ? compute() : shared(`lazy:${stamp}:${cacheKey}`, compute);
|
|
1390
|
+
}
|
|
1391
|
+
async function computeLazyQueryIds(args, rc, type, typeNames, tree, needsResolve, stamp, cacheKey) {
|
|
1392
|
+
const filter = args.query?.filter;
|
|
1393
|
+
const sorts = normalizeSort(args.query?.sort);
|
|
1394
|
+
const hasFilter = !!filter && Object.keys(filter).length > 0;
|
|
1395
|
+
let indexable = hasFilter ? findIndexable(filter, type, rc.schema, needsResolve) : void 0;
|
|
1396
|
+
let candidates;
|
|
1397
|
+
if (indexable?.op === "eq") {
|
|
1398
|
+
candidates = lazyIndex(typeNames, indexable.path).get(indexable.values[0]) ?? [];
|
|
1399
|
+
if (candidates.length > MAX_EQ_CANDIDATES) for (const eq of findIndexableEqs(filter, type, [], rc.schema)) {
|
|
1400
|
+
if (eq.path.join(".") === indexable.path.join(".")) continue;
|
|
1401
|
+
const ids = lazyIndex(typeNames, eq.path).get(eq.values[0]) ?? [];
|
|
1402
|
+
if (ids.length < candidates.length) {
|
|
1403
|
+
candidates = ids;
|
|
1404
|
+
indexable = eq;
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
if (candidates.length > MAX_EQ_CANDIDATES) candidates = void 0;
|
|
1408
|
+
}
|
|
1409
|
+
const entry = await lazyViews(typeNames, type, tree, needsResolve, rc, candidates);
|
|
1410
|
+
let list;
|
|
1411
|
+
let positions;
|
|
1412
|
+
if (candidates) list = {
|
|
1413
|
+
ids: candidates,
|
|
1414
|
+
views: candidates.map((id) => entry.views.get(id)?.view)
|
|
1415
|
+
};
|
|
1416
|
+
else if (entry.complete) {
|
|
1417
|
+
list = entry.list ??= viewList(entry, typeNames);
|
|
1418
|
+
if (indexable) positions = listCandidates(list, indexable);
|
|
1419
|
+
else if (hasFilter) {
|
|
1420
|
+
const found = findViewIndexable(filter, type);
|
|
1421
|
+
if (found) positions = viewCandidates(list, found);
|
|
1422
|
+
}
|
|
1423
|
+
} else list = viewList(entry, typeNames);
|
|
1424
|
+
const deps = needsResolve ? list === entry.list ? listDeps(list) : viewsDeps(list.views) : void 0;
|
|
1425
|
+
const order = list === entry.list && sorts.length ? sortOrder(list, sorts) : void 0;
|
|
1426
|
+
const ids = filterAndSort(list.views, type, filter, sorts, positions, order).map((k) => list.ids[k]);
|
|
1427
|
+
if (cacheKey !== void 0) lazyResultCache.set(cacheKey, {
|
|
1428
|
+
stamp,
|
|
1429
|
+
ids,
|
|
1430
|
+
deps
|
|
1431
|
+
}, ids.length);
|
|
1432
|
+
return {
|
|
1433
|
+
ids,
|
|
1434
|
+
deps
|
|
1435
|
+
};
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* One QueryDependencies per distinct set of what views' resolvers read: the views of a set mostly
|
|
1439
|
+
* read the same few nodes (e.g. 200 authors of 50k posts), and an id read from a decoded node would
|
|
1440
|
+
* keep the node's string block alive (see detachString) – the kept ids are copies.
|
|
1441
|
+
*/
|
|
1442
|
+
function internDeps(pool, deps) {
|
|
1443
|
+
const key = `${[...deps.nodes].sort().join("\0")}\u0001${[...deps.connections].sort().join("\0")}`;
|
|
1444
|
+
let shared = pool.get(key);
|
|
1445
|
+
if (!shared) {
|
|
1446
|
+
shared = new QueryDependencies();
|
|
1447
|
+
for (const id of deps.nodes) shared.addNode(detachString(id));
|
|
1448
|
+
for (const type of deps.connections) shared.addConnection(type);
|
|
1449
|
+
pool.set(key, shared);
|
|
1450
|
+
}
|
|
1451
|
+
return shared;
|
|
1452
|
+
}
|
|
1453
|
+
/** the views of a view set in insertion order */
|
|
1454
|
+
function viewList(entry, typeNames) {
|
|
1455
|
+
const { views } = entry;
|
|
1456
|
+
let ids;
|
|
1457
|
+
if (typeNames.length === 1 && typeof getDataStore().getNodeIdsByType === "function") ids = lazyIds(typeNames);
|
|
1458
|
+
else {
|
|
1459
|
+
const byCounter = [];
|
|
1460
|
+
for (const [id, v] of views) byCounter.push({
|
|
1461
|
+
id,
|
|
1462
|
+
counter: v.counter
|
|
1463
|
+
});
|
|
1464
|
+
byCounter.sort((a, b) => a.counter - b.counter);
|
|
1465
|
+
ids = byCounter.map((e) => e.id);
|
|
1466
|
+
}
|
|
1467
|
+
return {
|
|
1468
|
+
ids,
|
|
1469
|
+
views: ids.map((id) => views.get(id)?.view)
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* Positions (ascending) of the views with one of the values at the path: a superset of the
|
|
1474
|
+
* matches of an indexable filter. The projections hold the filtered paths' raw values (indexable
|
|
1475
|
+
* paths have no resolvers), so the value index of a view list loads no node.
|
|
1476
|
+
*/
|
|
1477
|
+
function listCandidates(list, { path, values }) {
|
|
1478
|
+
return candidatesOf(listIndex(list, JSON.stringify(path), (view, add) => {
|
|
1479
|
+
const v = getValueAt(view, path);
|
|
1480
|
+
if (Array.isArray(v)) for (const value of v) add(value);
|
|
1481
|
+
else add(v);
|
|
1482
|
+
}), values);
|
|
1483
|
+
}
|
|
1484
|
+
function findViewIndexable(filter, type) {
|
|
1485
|
+
return findViewOp(filter, type, [], "eq") ?? findViewOp(filter, type, [], "in");
|
|
1486
|
+
}
|
|
1487
|
+
/** walks the filter like compileFilter: one of the conjuncts of its predicate */
|
|
1488
|
+
function findViewOp(filter, type, steps, op) {
|
|
1489
|
+
if (!filter || typeof filter !== "object") return void 0;
|
|
1490
|
+
const fields = fieldsOf(type);
|
|
1491
|
+
for (const [field, value] of Object.entries(filter)) {
|
|
1492
|
+
if (value === void 0 || value === null) continue;
|
|
1493
|
+
const def = fields?.[field];
|
|
1494
|
+
const named = def ? getNamedType(def.type) : void 0;
|
|
1495
|
+
if (named ? isLeafType(named) : isOperatorObject(value)) {
|
|
1496
|
+
const values = indexedValues(value, op);
|
|
1497
|
+
if (values) return {
|
|
1498
|
+
steps,
|
|
1499
|
+
leaf: field,
|
|
1500
|
+
values
|
|
1501
|
+
};
|
|
1502
|
+
} else if (typeof value === "object") {
|
|
1503
|
+
const elemMatch = "elemMatch" in value;
|
|
1504
|
+
const found = findViewOp(elemMatch ? value.elemMatch : value, named, [...steps, {
|
|
1505
|
+
field,
|
|
1506
|
+
elemMatch
|
|
1507
|
+
}], op);
|
|
1508
|
+
if (found) return found;
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* The values a leaf's `eq` (non-null, not an object) or `in` (primitives, so no null) matches –
|
|
1514
|
+
* from the operands compileLeaf reads (own enumerable ones).
|
|
1515
|
+
*/
|
|
1516
|
+
function indexedValues(ops, op) {
|
|
1517
|
+
for (const [key, operand] of Object.entries(ops)) {
|
|
1518
|
+
if (key !== op || operand === void 0) continue;
|
|
1519
|
+
if (op === "eq") return operand !== null && typeof operand !== "object" ? [operand] : void 0;
|
|
1520
|
+
const list = [].concat(operand);
|
|
1521
|
+
return list.length <= MAX_INDEXED_IN && list.every(isPrimitive) ? list : void 0;
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
/** positions (ascending) of the views with one of the values where the predicate reads them */
|
|
1525
|
+
function viewCandidates(list, { steps, leaf, values }) {
|
|
1526
|
+
return candidatesOf(listIndex(list, JSON.stringify({
|
|
1527
|
+
steps,
|
|
1528
|
+
leaf
|
|
1529
|
+
}), (view, add) => readLeaf(view, steps, 0, leaf, add)), values);
|
|
1530
|
+
}
|
|
1531
|
+
/** the values compileFilter's predicate compares at the leaf (elemMatch, objects and lists) */
|
|
1532
|
+
function readLeaf(obj, steps, i, leaf, add) {
|
|
1533
|
+
if (i === steps.length) {
|
|
1534
|
+
const v = obj?.[leaf];
|
|
1535
|
+
if (Array.isArray(v)) for (const x of v) add(x);
|
|
1536
|
+
else add(v);
|
|
1537
|
+
return;
|
|
1538
|
+
}
|
|
1539
|
+
const { field, elemMatch } = steps[i];
|
|
1540
|
+
const v = obj?.[field];
|
|
1541
|
+
if (elemMatch) {
|
|
1542
|
+
if (v == null) return;
|
|
1543
|
+
if (!Array.isArray(v)) readLeaf(v, steps, i + 1, leaf, add);
|
|
1544
|
+
else for (const e of v) if (e != null) readLeaf(e, steps, i + 1, leaf, add);
|
|
1545
|
+
} else if (!Array.isArray(v)) readLeaf(v ?? EMPTY, steps, i + 1, leaf, add);
|
|
1546
|
+
else if (!v.length) readLeaf(EMPTY, steps, i + 1, leaf, add);
|
|
1547
|
+
else for (const e of v) readLeaf(e ?? EMPTY, steps, i + 1, leaf, add);
|
|
1548
|
+
}
|
|
1549
|
+
const NO_POSITIONS = /* @__PURE__ */ new Uint32Array(0);
|
|
1550
|
+
function listIndex(list, key, valuesOf) {
|
|
1551
|
+
let index = list.indexes?.get(key);
|
|
1552
|
+
if (!index) {
|
|
1553
|
+
index = positionIndex(list.views, valuesOf);
|
|
1554
|
+
(list.indexes ??= /* @__PURE__ */ new Map()).set(key, index);
|
|
1555
|
+
}
|
|
1556
|
+
return index;
|
|
1557
|
+
}
|
|
1558
|
+
function positionIndex(views, valuesOf) {
|
|
1559
|
+
const lists = /* @__PURE__ */ new Map();
|
|
1560
|
+
let total = 0;
|
|
1561
|
+
let k = 0;
|
|
1562
|
+
const add = (value) => {
|
|
1563
|
+
if (value === void 0 || value === null) return;
|
|
1564
|
+
let list = lists.get(value);
|
|
1565
|
+
if (!list) lists.set(value, list = []);
|
|
1566
|
+
else if (list[list.length - 1] === k) return;
|
|
1567
|
+
list.push(k);
|
|
1568
|
+
total++;
|
|
1569
|
+
};
|
|
1570
|
+
for (; k < views.length; k++) if (views[k] !== void 0) valuesOf(views[k], add);
|
|
1571
|
+
const starts = new Uint32Array(lists.size + 1);
|
|
1572
|
+
const positions = new Uint32Array(total);
|
|
1573
|
+
let b = 0;
|
|
1574
|
+
let at = 0;
|
|
1575
|
+
for (const [value, list] of lists) {
|
|
1576
|
+
starts[b] = at;
|
|
1577
|
+
for (const p of list) positions[at++] = p;
|
|
1578
|
+
lists.set(value, b++);
|
|
1579
|
+
}
|
|
1580
|
+
starts[b] = at;
|
|
1581
|
+
return {
|
|
1582
|
+
buckets: lists,
|
|
1583
|
+
starts,
|
|
1584
|
+
positions
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
function candidatesOf(index, values) {
|
|
1588
|
+
const bucket = (value) => {
|
|
1589
|
+
const b = index.buckets.get(value);
|
|
1590
|
+
return b === void 0 ? void 0 : index.positions.subarray(index.starts[b], index.starts[b + 1]);
|
|
1591
|
+
};
|
|
1592
|
+
if (values.length === 1) return bucket(values[0]) ?? NO_POSITIONS;
|
|
1593
|
+
return unionOfPositions([...new Set(values)].map(bucket));
|
|
1594
|
+
}
|
|
1595
|
+
/** `viewsDeps` of a complete set's list, computed once (the views of the list never change) */
|
|
1596
|
+
function listDeps(list) {
|
|
1597
|
+
if (list.deps === void 0) list.deps = viewsDeps(list.views) ?? null;
|
|
1598
|
+
return list.deps ?? void 0;
|
|
1599
|
+
}
|
|
1600
|
+
/** what resolvers read to materialize the views (a result depends on the values of all of them) */
|
|
1601
|
+
function viewsDeps(views) {
|
|
1602
|
+
let deps;
|
|
1603
|
+
let last;
|
|
1604
|
+
for (const view of views) {
|
|
1605
|
+
const d = view !== null && typeof view === "object" ? viewDeps.get(view) : void 0;
|
|
1606
|
+
if (d && d !== last) (deps ??= new QueryDependencies()).merge(last = d);
|
|
1607
|
+
}
|
|
1608
|
+
return deps;
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* The positions of all views of a (complete) list in the sort's order, computed once per sort.
|
|
1612
|
+
* Undefined unless the sort's order is total (each field's values all numbers or all strings, see
|
|
1613
|
+
* sortByKeys): compareAscending does not order mixed values transitively, and the matches of a
|
|
1614
|
+
* filter, sorted, could come out in another order than in the order of all views.
|
|
1615
|
+
*/
|
|
1616
|
+
function sortOrder(list, sorts) {
|
|
1617
|
+
const key = JSON.stringify(sorts);
|
|
1618
|
+
let sorted = list.orders?.get(key);
|
|
1619
|
+
if (sorted === void 0) {
|
|
1620
|
+
const positions = sortByKeys(list.views, range(list.views.length), sorts);
|
|
1621
|
+
if (positions) {
|
|
1622
|
+
const order = Uint32Array.from(positions);
|
|
1623
|
+
const rank = new Uint32Array(order.length);
|
|
1624
|
+
for (let i = 0; i < order.length; i++) rank[order[i]] = i;
|
|
1625
|
+
sorted = {
|
|
1626
|
+
order,
|
|
1627
|
+
rank
|
|
1628
|
+
};
|
|
1629
|
+
} else sorted = null;
|
|
1630
|
+
(list.orders ??= /* @__PURE__ */ new Map()).set(key, sorted);
|
|
1631
|
+
}
|
|
1632
|
+
return sorted ?? void 0;
|
|
1633
|
+
}
|
|
1634
|
+
/**
|
|
1635
|
+
* Positions of the views matching the filter (of all views, or of the `candidates`: ascending
|
|
1636
|
+
* positions), sorted – ties keep the order of the list, like Gatsby. With `order` (the views'
|
|
1637
|
+
* positions in the sort's order, see sortOrder) nothing is sorted: the matches are taken in that
|
|
1638
|
+
* order (ties are in list order there, too).
|
|
1639
|
+
*/
|
|
1640
|
+
function filterAndSort(views, type, filter, sorts, candidates, order) {
|
|
1641
|
+
const hasFilter = !!filter && Object.keys(filter).length > 0;
|
|
1642
|
+
if (order && sorts.length) {
|
|
1643
|
+
const predicate = hasFilter ? compileFilter(filter, type) : void 0;
|
|
1644
|
+
const out = [];
|
|
1645
|
+
if (!candidates) {
|
|
1646
|
+
for (const k of order.order) if (!predicate || views[k] !== void 0 && predicate(views[k])) out.push(k);
|
|
1647
|
+
return out;
|
|
1648
|
+
}
|
|
1649
|
+
for (let c = 0; c < candidates.length; c++) {
|
|
1650
|
+
const k = candidates[c];
|
|
1651
|
+
if (!predicate || views[k] !== void 0 && predicate(views[k])) out.push(k);
|
|
1652
|
+
}
|
|
1653
|
+
const { rank } = order;
|
|
1654
|
+
return out.sort((a, b) => rank[a] - rank[b]);
|
|
1655
|
+
}
|
|
1656
|
+
let positions;
|
|
1657
|
+
if (hasFilter) {
|
|
1658
|
+
const predicate = compileFilter(filter, type);
|
|
1659
|
+
positions = [];
|
|
1660
|
+
const count = candidates ? candidates.length : views.length;
|
|
1661
|
+
for (let c = 0; c < count; c++) {
|
|
1662
|
+
const k = candidates ? candidates[c] : c;
|
|
1663
|
+
if (views[k] !== void 0 && predicate(views[k])) positions.push(k);
|
|
1664
|
+
}
|
|
1665
|
+
} else positions = range(views.length);
|
|
1666
|
+
if (sorts.length && positions.length > 1) positions = sortPositions(views, positions, sorts);
|
|
1667
|
+
return positions;
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Sorts positions (ascending) like `compareAscending` per sort field, ties in list order. With
|
|
1671
|
+
* the values of each field all numbers or all strings (after its Date/array/boolean conversions,
|
|
1672
|
+
* nil aside), that comparison is a total order: a comparison of precomputed keys gives the one
|
|
1673
|
+
* sorted order. Other values (e.g. numbers and strings mixed, which `>`/`<` do not order
|
|
1674
|
+
* transitively) are sorted with `compareAscending` itself, exactly as always.
|
|
1675
|
+
*/
|
|
1676
|
+
function sortPositions(views, positions, sorts) {
|
|
1677
|
+
return sortByKeys(views, positions, sorts) ?? compareSort(positions, sorts.map((s) => positions.map((k) => getValueAt(views[k], s.path))), sorts);
|
|
1678
|
+
}
|
|
1679
|
+
/** sortPositions by precomputed keys: undefined when a field's values are not of one kind */
|
|
1680
|
+
function sortByKeys(views, positions, sorts) {
|
|
1681
|
+
const values = sorts.map((s) => positions.map((k) => getValueAt(views[k], s.path)));
|
|
1682
|
+
const compares = [];
|
|
1683
|
+
for (let g = 0; g < sorts.length; g++) {
|
|
1684
|
+
const compare = keyCompare(values[g], sorts[g].order === "DESC" ? -1 : 1);
|
|
1685
|
+
if (compare === void 0) return void 0;
|
|
1686
|
+
if (compare) compares.push(compare);
|
|
1687
|
+
}
|
|
1688
|
+
const order = range(positions.length);
|
|
1689
|
+
if (compares.length === 1) order.sort(compares[0]);
|
|
1690
|
+
else if (compares.length > 1) order.sort((a, b) => {
|
|
1691
|
+
for (const compare of compares) {
|
|
1692
|
+
const c = compare(a, b);
|
|
1693
|
+
if (c !== 0) return c;
|
|
1694
|
+
}
|
|
1695
|
+
return 0;
|
|
1696
|
+
});
|
|
1697
|
+
return order.map((i) => positions[i]);
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* `compareAscending(values[a], values[b]) * dir` from keys: numbers (Float64Array, NaN for nil)
|
|
1701
|
+
* or strings (undefined for nil). Null: all values are nil; undefined: no such keys.
|
|
1702
|
+
*/
|
|
1703
|
+
function keyCompare(values, dir) {
|
|
1704
|
+
let numbers;
|
|
1705
|
+
let strings;
|
|
1706
|
+
for (let i = 0; i < values.length; i++) {
|
|
1707
|
+
let v = values[i];
|
|
1708
|
+
if (v === null || v === void 0 || typeof v === "number" && Number.isNaN(v)) continue;
|
|
1709
|
+
if (v instanceof Date) v = v.getTime();
|
|
1710
|
+
if (Array.isArray(v)) v = v[0];
|
|
1711
|
+
if (typeof v === "boolean") v = v ? 1 : 0;
|
|
1712
|
+
if (typeof v === "number" && !Number.isNaN(v) && !strings) (numbers ??= new Float64Array(values.length).fill(NaN))[i] = v;
|
|
1713
|
+
else if (typeof v === "string" && !numbers) (strings ??= Array(values.length).fill(void 0))[i] = v;
|
|
1714
|
+
else return void 0;
|
|
1715
|
+
}
|
|
1716
|
+
if (numbers) {
|
|
1717
|
+
const keys = numbers;
|
|
1718
|
+
return (a, b) => {
|
|
1719
|
+
const x = keys[a];
|
|
1720
|
+
const y = keys[b];
|
|
1721
|
+
if (x === y) return 0;
|
|
1722
|
+
if (x !== x) return y !== y ? 0 : dir;
|
|
1723
|
+
if (y !== y) return -dir;
|
|
1724
|
+
return x < y ? -dir : dir;
|
|
1725
|
+
};
|
|
1726
|
+
}
|
|
1727
|
+
if (strings) {
|
|
1728
|
+
const keys = strings;
|
|
1729
|
+
return (a, b) => {
|
|
1730
|
+
const x = keys[a];
|
|
1731
|
+
const y = keys[b];
|
|
1732
|
+
if (x === y) return 0;
|
|
1733
|
+
if (x === void 0) return dir;
|
|
1734
|
+
if (y === void 0) return -dir;
|
|
1735
|
+
return x < y ? -dir : dir;
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
return null;
|
|
1739
|
+
}
|
|
1740
|
+
/** [0, 1, …, n - 1] */
|
|
1741
|
+
function range(n) {
|
|
1742
|
+
const out = [];
|
|
1743
|
+
for (let i = 0; i < n; i++) out.push(i);
|
|
1744
|
+
return out;
|
|
1745
|
+
}
|
|
1746
|
+
/** the sort by `compareAscending` (any values) */
|
|
1747
|
+
function compareSort(positions, values, sorts) {
|
|
1748
|
+
const dirs = sorts.map((s) => s.order === "DESC" ? -1 : 1);
|
|
1749
|
+
const keyed = positions.map((k, i) => ({
|
|
1750
|
+
k,
|
|
1751
|
+
keys: values.map((v) => v[i])
|
|
1752
|
+
}));
|
|
1753
|
+
keyed.sort((a, b) => {
|
|
1754
|
+
for (let g = 0; g < dirs.length; g++) {
|
|
1755
|
+
const c = compareAscending(a.keys[g], b.keys[g]);
|
|
1756
|
+
if (c !== 0) return c * dirs[g];
|
|
1757
|
+
}
|
|
1758
|
+
return a.k - b.k;
|
|
1759
|
+
});
|
|
1760
|
+
return keyed.map((e) => e.k);
|
|
1761
|
+
}
|
|
1762
|
+
/**
|
|
1763
|
+
* (tests) A filter and sort over views like over a complete view set's: the candidates of the
|
|
1764
|
+
* view index (undefined: none answers the filter), the result from them and from a scan.
|
|
1765
|
+
*/
|
|
1766
|
+
function viewListQuery(views, filter, sorts = [], type) {
|
|
1767
|
+
const found = filter ? findViewIndexable(filter, type) : void 0;
|
|
1768
|
+
const candidates = found && viewCandidates({
|
|
1769
|
+
ids: [],
|
|
1770
|
+
views
|
|
1771
|
+
}, found);
|
|
1772
|
+
return {
|
|
1773
|
+
candidates: candidates && Array.from(candidates),
|
|
1774
|
+
positions: filterAndSort(views, type, filter, sorts, candidates),
|
|
1775
|
+
scan: filterAndSort(views, type, filter, sorts)
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* Like `runQuery`, but returns node ids – lets paginated connections and `findAll` with
|
|
1780
|
+
* skip/limit resolve only the nodes they return (lazy datastores). Records dependencies like
|
|
1781
|
+
* `runQuery`.
|
|
1782
|
+
*/
|
|
1783
|
+
async function runQueryIds(args, rc) {
|
|
1784
|
+
const { schema } = rc;
|
|
1785
|
+
const type = typeof args.type === "string" ? schema.getType(args.type) : args.type;
|
|
1786
|
+
if (!type) throw new Error(`Unknown type "${String(args.type)}"`);
|
|
1787
|
+
const typeNames = getNodeTypeNames(type, schema);
|
|
1788
|
+
if (typeNames.length === 0) return [];
|
|
1789
|
+
if (!isLazyStore()) return (await runQuery(args, rc)).map((n) => n.id);
|
|
1790
|
+
readingNodesOfTypes(typeNames);
|
|
1791
|
+
const { ids, deps } = await runLazyQueryIds(args, rc, type, typeNames);
|
|
1792
|
+
const tracked = rc.context?.nodeModel?.dependencies;
|
|
1793
|
+
if (tracked) {
|
|
1794
|
+
tracked.merge(deps);
|
|
1795
|
+
if (args.firstOnly && ids[0] && !normalizeSort(args.query?.sort).length) tracked.addNode(ids[0]);
|
|
1796
|
+
else for (const t of typeNames) tracked.addConnection(t);
|
|
1797
|
+
}
|
|
1798
|
+
return ids;
|
|
1799
|
+
}
|
|
1800
|
+
/** Resolves (materializes) a field path on a node, e.g. for distinct/group on resolver fields. */
|
|
1801
|
+
async function resolveFieldPath(node, type, path, rc) {
|
|
1802
|
+
const tree = /* @__PURE__ */ new Map();
|
|
1803
|
+
addPath(tree, path);
|
|
1804
|
+
if (!treeNeedsResolve(tree, type, rc.schema)) return getValueAt(node, path);
|
|
1805
|
+
trackInlineObjects(node);
|
|
1806
|
+
return getValueAt(await materialize(node, type, tree, rc), path);
|
|
1807
|
+
}
|
|
1808
|
+
export { clearLazyQueryCaches, clearQueryEngineCaches, clearSlimNodes, compileFilter, connectionReadFields, fieldSelectorToPath, getDataVersion, getNodeTypeNames, getValueAt, hasCustomResolver, invalidateQueryCaches, isLazyStore, nodesByIds, normalizeSort, queryResultNode, queryResultNodes, resolveFieldPath, runIdQuery, runQuery, runQueryIds, setSlimNodesBudget, setSlimNodesHeap, viewListQuery };
|