@tinacms/graphql 0.0.0-d7c745e-20250102002342 → 0.0.0-db8aa8e-20250228034006

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -27,8 +27,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
28
 
29
29
  // src/index.ts
30
- var src_exports = {};
31
- __export(src_exports, {
30
+ var index_exports = {};
31
+ __export(index_exports, {
32
32
  AuditFileSystemBridge: () => AuditFileSystemBridge,
33
33
  Database: () => Database,
34
34
  FilesystemBridge: () => FilesystemBridge,
@@ -62,7 +62,7 @@ __export(src_exports, {
62
62
  transformDocument: () => transformDocument,
63
63
  transformDocumentIntoPayload: () => transformDocumentIntoPayload
64
64
  });
65
- module.exports = __toCommonJS(src_exports);
65
+ module.exports = __toCommonJS(index_exports);
66
66
 
67
67
  // src/build.ts
68
68
  var import_graphql2 = require("graphql");
@@ -1095,41 +1095,6 @@ function* walk(maybeNode, visited = /* @__PURE__ */ new WeakSet()) {
1095
1095
  yield maybeNode;
1096
1096
  visited.add(maybeNode);
1097
1097
  }
1098
- function addNamespaceToSchema(maybeNode, namespace = []) {
1099
- if (typeof maybeNode === "string") {
1100
- return maybeNode;
1101
- }
1102
- if (typeof maybeNode === "boolean") {
1103
- return maybeNode;
1104
- }
1105
- const newNode = maybeNode;
1106
- const keys = Object.keys(maybeNode);
1107
- Object.values(maybeNode).map((m, index) => {
1108
- const key = keys[index];
1109
- if (Array.isArray(m)) {
1110
- newNode[key] = m.map((element) => {
1111
- if (!element) {
1112
- return;
1113
- }
1114
- if (!element.hasOwnProperty("name")) {
1115
- return element;
1116
- }
1117
- const value = element.name || element.value;
1118
- return addNamespaceToSchema(element, [...namespace, value]);
1119
- });
1120
- } else {
1121
- if (!m) {
1122
- return;
1123
- }
1124
- if (!m.hasOwnProperty("name")) {
1125
- newNode[key] = m;
1126
- } else {
1127
- newNode[key] = addNamespaceToSchema(m, [...namespace, m.name]);
1128
- }
1129
- }
1130
- });
1131
- return { ...newNode, namespace };
1132
- }
1133
1098
  var generateNamespacedFieldName = (names, suffix = "") => {
1134
1099
  return (suffix ? [...names, suffix] : names).map(capitalize).join("");
1135
1100
  };
@@ -2965,12 +2930,13 @@ var filterSelections = (arr) => {
2965
2930
  };
2966
2931
 
2967
2932
  // src/schema/createSchema.ts
2968
- var import_schema_tools2 = require("@tinacms/schema-tools");
2933
+ var import_schema_tools3 = require("@tinacms/schema-tools");
2969
2934
 
2970
2935
  // src/schema/validate.ts
2936
+ var import_schema_tools = require("@tinacms/schema-tools");
2971
2937
  var import_lodash2 = __toESM(require("lodash.clonedeep"));
2972
2938
  var yup2 = __toESM(require("yup"));
2973
- var import_schema_tools = require("@tinacms/schema-tools");
2939
+ var import_schema_tools2 = require("@tinacms/schema-tools");
2974
2940
  var FIELD_TYPES = [
2975
2941
  "string",
2976
2942
  "number",
@@ -2983,7 +2949,7 @@ var FIELD_TYPES = [
2983
2949
  "password"
2984
2950
  ];
2985
2951
  var validateSchema = async (schema) => {
2986
- const schema2 = addNamespaceToSchema(
2952
+ const schema2 = (0, import_schema_tools.addNamespaceToSchema)(
2987
2953
  (0, import_lodash2.default)(schema)
2988
2954
  );
2989
2955
  const collections = await sequential(
@@ -2992,7 +2958,7 @@ var validateSchema = async (schema) => {
2992
2958
  );
2993
2959
  validationCollectionsPathAndMatch(collections);
2994
2960
  if (schema2.config) {
2995
- const config = (0, import_schema_tools.validateTinaCloudSchemaConfig)(schema2.config);
2961
+ const config = (0, import_schema_tools2.validateTinaCloudSchemaConfig)(schema2.config);
2996
2962
  return {
2997
2963
  collections,
2998
2964
  config
@@ -3124,7 +3090,7 @@ var validateField = async (field) => {
3124
3090
  // package.json
3125
3091
  var package_default = {
3126
3092
  name: "@tinacms/graphql",
3127
- version: "1.5.9",
3093
+ version: "1.5.13",
3128
3094
  main: "dist/index.js",
3129
3095
  module: "dist/index.mjs",
3130
3096
  typings: "dist/index.d.ts",
@@ -3151,8 +3117,8 @@ var package_default = {
3151
3117
  build: "tinacms-scripts build",
3152
3118
  docs: "pnpm typedoc",
3153
3119
  serve: "pnpm nodemon dist/server.js",
3154
- test: "jest",
3155
- "test-watch": "jest --watch"
3120
+ test: "vitest run",
3121
+ "test-watch": "vitest"
3156
3122
  },
3157
3123
  dependencies: {
3158
3124
  "@iarna/toml": "^2.2.5",
@@ -3160,12 +3126,12 @@ var package_default = {
3160
3126
  "@tinacms/schema-tools": "workspace:*",
3161
3127
  "abstract-level": "^1.0.4",
3162
3128
  "date-fns": "^2.30.0",
3163
- "fast-glob": "^3.3.2",
3164
- "fs-extra": "^11.2.0",
3129
+ "fast-glob": "^3.3.3",
3130
+ "fs-extra": "^11.3.0",
3165
3131
  "glob-parent": "^6.0.2",
3166
3132
  graphql: "15.8.0",
3167
3133
  "gray-matter": "^4.0.3",
3168
- "isomorphic-git": "^1.27.1",
3134
+ "isomorphic-git": "^1.29.0",
3169
3135
  "js-sha1": "^0.6.0",
3170
3136
  "js-yaml": "^3.14.1",
3171
3137
  "jsonpath-plus": "10.1.0",
@@ -3175,7 +3141,7 @@ var package_default = {
3175
3141
  "many-level": "^2.0.0",
3176
3142
  micromatch: "4.0.8",
3177
3143
  "normalize-path": "^3.0.0",
3178
- "readable-stream": "^4.5.2",
3144
+ "readable-stream": "^4.7.0",
3179
3145
  scmp: "^2.1.0",
3180
3146
  yup: "^0.32.11"
3181
3147
  },
@@ -3193,24 +3159,23 @@ var package_default = {
3193
3159
  "@types/estree": "^0.0.50",
3194
3160
  "@types/express": "^4.17.21",
3195
3161
  "@types/fs-extra": "^9.0.13",
3196
- "@types/jest": "^26.0.24",
3197
3162
  "@types/js-yaml": "^3.12.10",
3198
3163
  "@types/lodash.camelcase": "^4.3.9",
3199
3164
  "@types/lodash.upperfirst": "^4.3.9",
3200
3165
  "@types/lru-cache": "^5.1.1",
3201
3166
  "@types/mdast": "^3.0.15",
3202
3167
  "@types/micromatch": "^4.0.9",
3203
- "@types/node": "^22.9.0",
3168
+ "@types/node": "^22.13.1",
3204
3169
  "@types/normalize-path": "^3.0.2",
3205
3170
  "@types/ws": "^7.4.7",
3206
3171
  "@types/yup": "^0.29.14",
3207
- jest: "^29.7.0",
3208
- "jest-diff": "^29.7.0",
3209
3172
  "jest-file-snapshot": "^0.5.0",
3210
- "jest-matcher-utils": "^29.7.0",
3211
3173
  "memory-level": "^1.0.0",
3212
3174
  nodemon: "3.1.4",
3213
- typescript: "^5.6.3"
3175
+ typescript: "^5.7.3",
3176
+ vite: "^4.5.9",
3177
+ vitest: "^0.32.4",
3178
+ zod: "^3.24.2"
3214
3179
  }
3215
3180
  };
3216
3181
 
@@ -3225,7 +3190,7 @@ var createSchema = async ({
3225
3190
  if (flags && flags.length > 0) {
3226
3191
  meta["flags"] = flags;
3227
3192
  }
3228
- return new import_schema_tools2.TinaSchema({
3193
+ return new import_schema_tools3.TinaSchema({
3229
3194
  version: {
3230
3195
  fullVersion: package_default.version,
3231
3196
  major,
@@ -3723,7 +3688,7 @@ var import_path2 = __toESM(require("path"));
3723
3688
  var import_toml = __toESM(require("@iarna/toml"));
3724
3689
  var import_js_yaml = __toESM(require("js-yaml"));
3725
3690
  var import_gray_matter = __toESM(require("gray-matter"));
3726
- var import_schema_tools3 = require("@tinacms/schema-tools");
3691
+ var import_schema_tools4 = require("@tinacms/schema-tools");
3727
3692
  var import_micromatch = __toESM(require("micromatch"));
3728
3693
  var import_path = __toESM(require("path"));
3729
3694
 
@@ -3936,7 +3901,7 @@ var scanAllContent = async (tinaSchema, bridge, callback) => {
3936
3901
  const filesSeen = /* @__PURE__ */ new Map();
3937
3902
  const duplicateFiles = /* @__PURE__ */ new Set();
3938
3903
  await sequential(tinaSchema.getCollections(), async (collection) => {
3939
- const normalPath = (0, import_schema_tools3.normalizePath)(collection.path);
3904
+ const normalPath = (0, import_schema_tools4.normalizePath)(collection.path);
3940
3905
  const format = collection.format || "md";
3941
3906
  const documentPaths = await bridge.glob(normalPath, format);
3942
3907
  const matches = tinaSchema.getMatches({ collection });
@@ -4048,7 +4013,7 @@ var getTemplateForFile = (templateInfo, data) => {
4048
4013
  throw new Error(`Unable to determine template`);
4049
4014
  };
4050
4015
  var loadAndParseWithAliases = async (bridge, filepath, collection, templateInfo) => {
4051
- const dataString = await bridge.get((0, import_schema_tools3.normalizePath)(filepath));
4016
+ const dataString = await bridge.get((0, import_schema_tools4.normalizePath)(filepath));
4052
4017
  const data = parseFile(
4053
4018
  dataString,
4054
4019
  import_path.default.extname(filepath),
@@ -4070,6 +4035,9 @@ var loadAndParseWithAliases = async (bridge, filepath, collection, templateInfo)
4070
4035
 
4071
4036
  // src/database/datalayer.ts
4072
4037
  var DEFAULT_COLLECTION_SORT_KEY = "__filepath__";
4038
+ var REFS_COLLECTIONS_SORT_KEY = "__refs__";
4039
+ var REFS_REFERENCE_FIELD = "__tina_ref__";
4040
+ var REFS_PATH_FIELD = "__tina_ref_path__";
4073
4041
  var DEFAULT_NUMERIC_LPAD = 4;
4074
4042
  var applyPadding = (input, pad) => {
4075
4043
  if (pad) {
@@ -4527,7 +4495,7 @@ var FolderTreeBuilder = class {
4527
4495
  return this._tree;
4528
4496
  }
4529
4497
  update(documentPath, collectionPath) {
4530
- let folderPath = import_path2.default.dirname((0, import_schema_tools3.normalizePath)(documentPath));
4498
+ let folderPath = import_path2.default.dirname((0, import_schema_tools4.normalizePath)(documentPath));
4531
4499
  if (folderPath === ".") {
4532
4500
  folderPath = "";
4533
4501
  }
@@ -4540,7 +4508,7 @@ var FolderTreeBuilder = class {
4540
4508
  if (!this._tree[current2]) {
4541
4509
  this._tree[current2] = /* @__PURE__ */ new Set();
4542
4510
  }
4543
- this._tree[current2].add((0, import_schema_tools3.normalizePath)(import_path2.default.join(current2, part)));
4511
+ this._tree[current2].add((0, import_schema_tools4.normalizePath)(import_path2.default.join(current2, part)));
4544
4512
  parent.push(part);
4545
4513
  });
4546
4514
  const current = parent.join("/");
@@ -4643,6 +4611,51 @@ var makeIndexOpsForDocument = (filepath, collection, indexDefinitions, data, opT
4643
4611
  }
4644
4612
  return result;
4645
4613
  };
4614
+ var makeRefOpsForDocument = (filepath, collection, references, data, opType, level) => {
4615
+ const result = [];
4616
+ if (collection) {
4617
+ for (const [c, referencePaths] of Object.entries(references || {})) {
4618
+ if (!referencePaths.length) {
4619
+ continue;
4620
+ }
4621
+ const collectionSublevel = level.sublevel(c, SUBLEVEL_OPTIONS);
4622
+ const refSublevel = collectionSublevel.sublevel(
4623
+ REFS_COLLECTIONS_SORT_KEY,
4624
+ SUBLEVEL_OPTIONS
4625
+ );
4626
+ const references2 = {};
4627
+ for (const path7 of referencePaths) {
4628
+ const ref = (0, import_jsonpath_plus.JSONPath)({ path: path7, json: data });
4629
+ if (Array.isArray(ref)) {
4630
+ for (const r of ref) {
4631
+ if (references2[r]) {
4632
+ references2[r].push(path7);
4633
+ } else {
4634
+ references2[r] = [path7];
4635
+ }
4636
+ }
4637
+ } else {
4638
+ if (references2[ref]) {
4639
+ references2[ref].push(path7);
4640
+ } else {
4641
+ references2[ref] = [path7];
4642
+ }
4643
+ }
4644
+ }
4645
+ for (const ref of Object.keys(references2)) {
4646
+ for (const path7 of references2[ref]) {
4647
+ result.push({
4648
+ type: opType,
4649
+ key: `${ref}${INDEX_KEY_FIELD_SEPARATOR}${path7}${INDEX_KEY_FIELD_SEPARATOR}${filepath}`,
4650
+ sublevel: refSublevel,
4651
+ value: opType === "put" ? {} : void 0
4652
+ });
4653
+ }
4654
+ }
4655
+ }
4656
+ }
4657
+ return result;
4658
+ };
4646
4659
  var makeStringEscaper = (regex, replacement) => {
4647
4660
  return (input) => {
4648
4661
  if (Array.isArray(input)) {
@@ -4864,20 +4877,22 @@ var transformDocumentIntoPayload = async (fullPath, rawData, tinaSchema, config,
4864
4877
  throw e;
4865
4878
  }
4866
4879
  };
4867
- var updateObjectWithJsonPath = (obj, path7, newValue) => {
4880
+ var updateObjectWithJsonPath = (obj, path7, oldValue, newValue) => {
4868
4881
  if (!path7.includes(".") && !path7.includes("[")) {
4869
- if (path7 in obj) {
4882
+ if (path7 in obj && obj[path7] === oldValue) {
4870
4883
  obj[path7] = newValue;
4871
4884
  }
4872
4885
  return obj;
4873
4886
  }
4874
- const parentPath = path7.replace(/\.[^.]+$/, "");
4875
- const keyToUpdate = path7.match(/[^.]+$/)[0];
4887
+ const parentPath = path7.replace(/\.[^.\[\]]+$/, "");
4888
+ const keyToUpdate = path7.match(/[^.\[\]]+$/)[0];
4876
4889
  const parents = (0, import_jsonpath_plus2.JSONPath)({ path: parentPath, json: obj, resultType: "value" });
4877
4890
  if (parents.length > 0) {
4878
4891
  parents.forEach((parent) => {
4879
4892
  if (parent && typeof parent === "object" && keyToUpdate in parent) {
4880
- parent[keyToUpdate] = newValue;
4893
+ if (parent[keyToUpdate] === oldValue) {
4894
+ parent[keyToUpdate] = newValue;
4895
+ }
4881
4896
  }
4882
4897
  });
4883
4898
  }
@@ -5260,17 +5275,15 @@ var Resolver = class {
5260
5275
  await this.deleteDocument(realPath);
5261
5276
  if (await this.hasReferences(realPath, collection)) {
5262
5277
  const collRefs = await this.findReferences(realPath, collection);
5263
- for (const [collection2, refFields] of Object.entries(collRefs)) {
5264
- for (const [refPath, refs] of Object.entries(refFields)) {
5265
- let refDoc = await this.getRaw(refPath);
5266
- for (const ref of refs) {
5267
- refDoc = updateObjectWithJsonPath(
5268
- refDoc,
5269
- ref.path.join("."),
5270
- null
5271
- );
5278
+ for (const [collection2, docsWithRefs] of Object.entries(collRefs)) {
5279
+ for (const [pathToDocWithRef, referencePaths] of Object.entries(
5280
+ docsWithRefs
5281
+ )) {
5282
+ let refDoc = await this.getRaw(pathToDocWithRef);
5283
+ for (const path7 of referencePaths) {
5284
+ refDoc = updateObjectWithJsonPath(refDoc, path7, realPath, null);
5272
5285
  }
5273
- await this.database.put(refPath, refDoc, collection2);
5286
+ await this.database.put(pathToDocWithRef, refDoc, collection2);
5274
5287
  }
5275
5288
  }
5276
5289
  }
@@ -5290,20 +5303,26 @@ var Resolver = class {
5290
5303
  collection == null ? void 0 : collection.path,
5291
5304
  args.params.relativePath
5292
5305
  );
5306
+ if (newRealPath === realPath) {
5307
+ return doc;
5308
+ }
5293
5309
  await this.database.put(newRealPath, doc._rawData, collection.name);
5294
5310
  await this.deleteDocument(realPath);
5295
5311
  const collRefs = await this.findReferences(realPath, collection);
5296
- for (const [collection2, refFields] of Object.entries(collRefs)) {
5297
- for (const [refPath, refs] of Object.entries(refFields)) {
5298
- let refDoc = await this.getRaw(refPath);
5299
- for (const ref of refs) {
5300
- refDoc = updateObjectWithJsonPath(
5301
- refDoc,
5302
- ref.path.join("."),
5312
+ for (const [collection2, docsWithRefs] of Object.entries(collRefs)) {
5313
+ for (const [pathToDocWithRef, referencePaths] of Object.entries(
5314
+ docsWithRefs
5315
+ )) {
5316
+ let docWithRef = await this.getRaw(pathToDocWithRef);
5317
+ for (const path7 of referencePaths) {
5318
+ docWithRef = updateObjectWithJsonPath(
5319
+ docWithRef,
5320
+ path7,
5321
+ realPath,
5303
5322
  newRealPath
5304
5323
  );
5305
5324
  }
5306
- await this.database.put(refPath, refDoc, collection2);
5325
+ await this.database.put(pathToDocWithRef, docWithRef, collection2);
5307
5326
  }
5308
5327
  }
5309
5328
  return this.getDocument(newRealPath);
@@ -5435,35 +5454,30 @@ var Resolver = class {
5435
5454
  */
5436
5455
  this.hasReferences = async (id, c) => {
5437
5456
  let count = 0;
5438
- const deepRefs = this.tinaSchema.findReferences(c.name);
5439
- for (const [collection, refs] of Object.entries(deepRefs)) {
5440
- for (const ref of refs) {
5441
- await this.database.query(
5442
- {
5443
- collection,
5444
- filterChain: makeFilterChain({
5445
- conditions: [
5446
- {
5447
- filterPath: ref.path.join("."),
5448
- filterExpression: {
5449
- _type: "reference",
5450
- _list: false,
5451
- eq: id
5452
- }
5453
- }
5454
- ]
5455
- }),
5456
- sort: ref.field.name
5457
- },
5458
- (refId) => {
5459
- count++;
5460
- return refId;
5461
- }
5462
- );
5463
- if (count) {
5464
- return true;
5465
- }
5457
+ await this.database.query(
5458
+ {
5459
+ collection: c.name,
5460
+ filterChain: makeFilterChain({
5461
+ conditions: [
5462
+ {
5463
+ filterPath: REFS_REFERENCE_FIELD,
5464
+ filterExpression: {
5465
+ _type: "string",
5466
+ _list: false,
5467
+ eq: id
5468
+ }
5469
+ }
5470
+ ]
5471
+ }),
5472
+ sort: REFS_COLLECTIONS_SORT_KEY
5473
+ },
5474
+ (refId) => {
5475
+ count++;
5476
+ return refId;
5466
5477
  }
5478
+ );
5479
+ if (count) {
5480
+ return true;
5467
5481
  }
5468
5482
  return false;
5469
5483
  };
@@ -5471,46 +5485,41 @@ var Resolver = class {
5471
5485
  * Finds references to a document
5472
5486
  * @param id the id of the document to find references to
5473
5487
  * @param c the collection to find references in
5474
- * @returns references to the document in the form of a map of collection names to a list of fields that reference the document
5488
+ * @returns a map of references to the document
5475
5489
  */
5476
5490
  this.findReferences = async (id, c) => {
5477
5491
  const references = {};
5478
- const deepRefs = this.tinaSchema.findReferences(c.name);
5479
- for (const [collection, refs] of Object.entries(deepRefs)) {
5480
- for (const ref of refs) {
5481
- await this.database.query(
5482
- {
5483
- collection,
5484
- filterChain: makeFilterChain({
5485
- conditions: [
5486
- {
5487
- filterPath: ref.path.join("."),
5488
- filterExpression: {
5489
- _type: "reference",
5490
- _list: false,
5491
- eq: id
5492
- }
5493
- }
5494
- ]
5495
- }),
5496
- sort: ref.field.name
5497
- },
5498
- (refId) => {
5499
- if (!references[collection]) {
5500
- references[collection] = {};
5501
- }
5502
- if (!references[collection][refId]) {
5503
- references[collection][refId] = [];
5492
+ await this.database.query(
5493
+ {
5494
+ collection: c.name,
5495
+ filterChain: makeFilterChain({
5496
+ conditions: [
5497
+ {
5498
+ filterPath: REFS_REFERENCE_FIELD,
5499
+ filterExpression: {
5500
+ _type: "string",
5501
+ _list: false,
5502
+ eq: id
5503
+ }
5504
5504
  }
5505
- references[collection][refId].push({
5506
- path: ref.path,
5507
- field: ref.field
5508
- });
5509
- return refId;
5510
- }
5511
- );
5505
+ ]
5506
+ }),
5507
+ sort: REFS_COLLECTIONS_SORT_KEY
5508
+ },
5509
+ (refId, rawItem) => {
5510
+ if (!references[c.name]) {
5511
+ references[c.name] = {};
5512
+ }
5513
+ if (!references[c.name][refId]) {
5514
+ references[c.name][refId] = [];
5515
+ }
5516
+ const referencePath = rawItem == null ? void 0 : rawItem[REFS_PATH_FIELD];
5517
+ if (referencePath) {
5518
+ references[c.name][refId].push(referencePath);
5519
+ }
5520
+ return refId;
5512
5521
  }
5513
- }
5522
+ );
5514
5523
  return references;
5515
5524
  };
5516
5525
  this.buildFieldMutations = async (fieldParams, template, existingData) => {
@@ -6234,7 +6243,7 @@ var Database = class {
6234
6243
  const contentObject = await level.sublevel(
6235
6244
  CONTENT_ROOT_PREFIX,
6236
6245
  SUBLEVEL_OPTIONS
6237
- ).get((0, import_schema_tools3.normalizePath)(filepath));
6246
+ ).get((0, import_schema_tools4.normalizePath)(filepath));
6238
6247
  if (!contentObject) {
6239
6248
  throw new NotFoundError(`Unable to find record ${filepath}`);
6240
6249
  }
@@ -6246,6 +6255,7 @@ var Database = class {
6246
6255
  }
6247
6256
  };
6248
6257
  this.addPendingDocument = async (filepath, data) => {
6258
+ var _a;
6249
6259
  await this.initLevel();
6250
6260
  const dataFields = await this.formatBodyOnPayload(filepath, data);
6251
6261
  const collection = await this.collectionForPath(filepath);
@@ -6259,7 +6269,8 @@ var Database = class {
6259
6269
  );
6260
6270
  const indexDefinitions = await this.getIndexDefinitions(this.contentLevel);
6261
6271
  const collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collection.name];
6262
- const normalizedPath = (0, import_schema_tools3.normalizePath)(filepath);
6272
+ const collectionReferences = (_a = await this.getCollectionReferences()) == null ? void 0 : _a[collection.name];
6273
+ const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
6263
6274
  if (!(collection == null ? void 0 : collection.isDetached)) {
6264
6275
  if (this.bridge) {
6265
6276
  await this.bridge.put(normalizedPath, stringifiedFile);
@@ -6287,6 +6298,14 @@ var Database = class {
6287
6298
  let delOps = [];
6288
6299
  if (!isGitKeep(normalizedPath, collection)) {
6289
6300
  putOps = [
6301
+ ...makeRefOpsForDocument(
6302
+ normalizedPath,
6303
+ collection == null ? void 0 : collection.name,
6304
+ collectionReferences,
6305
+ dataFields,
6306
+ "put",
6307
+ level
6308
+ ),
6290
6309
  ...makeIndexOpsForDocument(
6291
6310
  normalizedPath,
6292
6311
  collection == null ? void 0 : collection.name,
@@ -6310,6 +6329,14 @@ var Database = class {
6310
6329
  SUBLEVEL_OPTIONS
6311
6330
  ).get(normalizedPath);
6312
6331
  delOps = existingItem ? [
6332
+ ...makeRefOpsForDocument(
6333
+ normalizedPath,
6334
+ collection == null ? void 0 : collection.name,
6335
+ collectionReferences,
6336
+ existingItem,
6337
+ "del",
6338
+ level
6339
+ ),
6313
6340
  ...makeIndexOpsForDocument(
6314
6341
  normalizedPath,
6315
6342
  collection == null ? void 0 : collection.name,
@@ -6345,7 +6372,7 @@ var Database = class {
6345
6372
  await level.batch(ops);
6346
6373
  };
6347
6374
  this.put = async (filepath, data, collectionName) => {
6348
- var _a, _b;
6375
+ var _a, _b, _c;
6349
6376
  await this.initLevel();
6350
6377
  try {
6351
6378
  if (SYSTEM_FILES.includes(filepath)) {
@@ -6358,13 +6385,14 @@ var Database = class {
6358
6385
  );
6359
6386
  collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collectionName];
6360
6387
  }
6361
- const normalizedPath = (0, import_schema_tools3.normalizePath)(filepath);
6388
+ const collectionReferences = (_a = await this.getCollectionReferences()) == null ? void 0 : _a[collectionName];
6389
+ const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
6362
6390
  const dataFields = await this.formatBodyOnPayload(filepath, data);
6363
6391
  const collection = await this.collectionForPath(filepath);
6364
6392
  if (!collection) {
6365
6393
  throw new import_graphql6.GraphQLError(`Unable to find collection for ${filepath}.`);
6366
6394
  }
6367
- if (((_a = collection.match) == null ? void 0 : _a.exclude) || ((_b = collection.match) == null ? void 0 : _b.include)) {
6395
+ if (((_b = collection.match) == null ? void 0 : _b.exclude) || ((_c = collection.match) == null ? void 0 : _c.include)) {
6368
6396
  const matches = this.tinaSchema.getMatches({ collection });
6369
6397
  const match = import_micromatch2.default.isMatch(filepath, matches);
6370
6398
  if (!match) {
@@ -6405,6 +6433,14 @@ var Database = class {
6405
6433
  let delOps = [];
6406
6434
  if (!isGitKeep(normalizedPath, collection)) {
6407
6435
  putOps = [
6436
+ ...makeRefOpsForDocument(
6437
+ normalizedPath,
6438
+ collectionName,
6439
+ collectionReferences,
6440
+ dataFields,
6441
+ "put",
6442
+ level
6443
+ ),
6408
6444
  ...makeIndexOpsForDocument(
6409
6445
  normalizedPath,
6410
6446
  collectionName,
@@ -6428,6 +6464,14 @@ var Database = class {
6428
6464
  SUBLEVEL_OPTIONS
6429
6465
  ).get(normalizedPath);
6430
6466
  delOps = existingItem ? [
6467
+ ...makeRefOpsForDocument(
6468
+ normalizedPath,
6469
+ collectionName,
6470
+ collectionReferences,
6471
+ existingItem,
6472
+ "del",
6473
+ level
6474
+ ),
6431
6475
  ...makeIndexOpsForDocument(
6432
6476
  normalizedPath,
6433
6477
  collectionName,
@@ -6532,7 +6576,7 @@ var Database = class {
6532
6576
  };
6533
6577
  this.getLookup = async (returnType) => {
6534
6578
  await this.initLevel();
6535
- const lookupPath = (0, import_schema_tools3.normalizePath)(
6579
+ const lookupPath = (0, import_schema_tools4.normalizePath)(
6536
6580
  import_node_path.default.join(this.getGeneratedFolder(), `_lookup.json`)
6537
6581
  );
6538
6582
  if (!this._lookup) {
@@ -6545,7 +6589,7 @@ var Database = class {
6545
6589
  };
6546
6590
  this.getGraphQLSchema = async () => {
6547
6591
  await this.initLevel();
6548
- const graphqlPath = (0, import_schema_tools3.normalizePath)(
6592
+ const graphqlPath = (0, import_schema_tools4.normalizePath)(
6549
6593
  import_node_path.default.join(this.getGeneratedFolder(), `_graphql.json`)
6550
6594
  );
6551
6595
  return await this.contentLevel.sublevel(
@@ -6558,7 +6602,7 @@ var Database = class {
6558
6602
  if (!this.bridge) {
6559
6603
  throw new Error(`No bridge configured`);
6560
6604
  }
6561
- const graphqlPath = (0, import_schema_tools3.normalizePath)(
6605
+ const graphqlPath = (0, import_schema_tools4.normalizePath)(
6562
6606
  import_node_path.default.join(this.getGeneratedFolder(), `_graphql.json`)
6563
6607
  );
6564
6608
  const _graphql = await this.bridge.get(graphqlPath);
@@ -6566,7 +6610,7 @@ var Database = class {
6566
6610
  };
6567
6611
  this.getTinaSchema = async (level) => {
6568
6612
  await this.initLevel();
6569
- const schemaPath = (0, import_schema_tools3.normalizePath)(
6613
+ const schemaPath = (0, import_schema_tools4.normalizePath)(
6570
6614
  import_node_path.default.join(this.getGeneratedFolder(), `_schema.json`)
6571
6615
  );
6572
6616
  return await (level || this.contentLevel).sublevel(
@@ -6582,7 +6626,7 @@ var Database = class {
6582
6626
  const schema = existingSchema || await this.getTinaSchema(level || this.contentLevel);
6583
6627
  if (!schema) {
6584
6628
  throw new Error(
6585
- `Unable to get schema from level db: ${(0, import_schema_tools3.normalizePath)(
6629
+ `Unable to get schema from level db: ${(0, import_schema_tools4.normalizePath)(
6586
6630
  import_node_path.default.join(this.getGeneratedFolder(), `_schema.json`)
6587
6631
  )}`
6588
6632
  );
@@ -6590,6 +6634,22 @@ var Database = class {
6590
6634
  this.tinaSchema = await createSchema({ schema });
6591
6635
  return this.tinaSchema;
6592
6636
  };
6637
+ this.getCollectionReferences = async (level) => {
6638
+ if (this.collectionReferences) {
6639
+ return this.collectionReferences;
6640
+ }
6641
+ const result = {};
6642
+ const schema = await this.getSchema(level || this.contentLevel);
6643
+ const collections = schema.getCollections();
6644
+ for (const collection of collections) {
6645
+ const collectionReferences = this.tinaSchema.findReferencesFromCollection(
6646
+ collection.name
6647
+ );
6648
+ result[collection.name] = collectionReferences;
6649
+ }
6650
+ this.collectionReferences = result;
6651
+ return result;
6652
+ };
6593
6653
  this.getIndexDefinitions = async (level) => {
6594
6654
  if (!this.collectionIndexDefinitions) {
6595
6655
  await new Promise(async (resolve2, reject) => {
@@ -6599,8 +6659,23 @@ var Database = class {
6599
6659
  const collections = schema.getCollections();
6600
6660
  for (const collection of collections) {
6601
6661
  const indexDefinitions = {
6602
- [DEFAULT_COLLECTION_SORT_KEY]: { fields: [] }
6662
+ [DEFAULT_COLLECTION_SORT_KEY]: { fields: [] },
6603
6663
  // provide a default sort key which is the file sort
6664
+ // pseudo-index for the collection's references
6665
+ [REFS_COLLECTIONS_SORT_KEY]: {
6666
+ fields: [
6667
+ {
6668
+ name: REFS_REFERENCE_FIELD,
6669
+ type: "string",
6670
+ list: false
6671
+ },
6672
+ {
6673
+ name: REFS_PATH_FIELD,
6674
+ type: "string",
6675
+ list: false
6676
+ }
6677
+ ]
6678
+ }
6604
6679
  };
6605
6680
  if (collection.fields) {
6606
6681
  for (const field of collection.fields) {
@@ -6752,29 +6827,36 @@ var Database = class {
6752
6827
  }
6753
6828
  startKey = startKey || key || "";
6754
6829
  endKey = key || "";
6755
- edges = [...edges, { cursor: key, path: filepath }];
6830
+ edges = [...edges, { cursor: key, path: filepath, value: itemRecord }];
6756
6831
  }
6757
6832
  return {
6758
- edges: await sequential(edges, async (edge) => {
6759
- try {
6760
- const node = await hydrator(edge.path);
6761
- return {
6762
- node,
6763
- cursor: btoa(edge.cursor)
6764
- };
6765
- } catch (error) {
6766
- console.log(error);
6767
- if (error instanceof Error && (!edge.path.includes(".tina/__generated__/_graphql.json") || !edge.path.includes("tina/__generated__/_graphql.json"))) {
6768
- throw new TinaQueryError({
6769
- originalError: error,
6770
- file: edge.path,
6771
- collection: collection.name,
6772
- stack: error.stack
6773
- });
6833
+ edges: await sequential(
6834
+ edges,
6835
+ async ({
6836
+ cursor,
6837
+ path: path7,
6838
+ value
6839
+ }) => {
6840
+ try {
6841
+ const node = await hydrator(path7, value);
6842
+ return {
6843
+ node,
6844
+ cursor: btoa(cursor)
6845
+ };
6846
+ } catch (error) {
6847
+ console.log(error);
6848
+ if (error instanceof Error && (!path7.includes(".tina/__generated__/_graphql.json") || !path7.includes("tina/__generated__/_graphql.json"))) {
6849
+ throw new TinaQueryError({
6850
+ originalError: error,
6851
+ file: path7,
6852
+ collection: collection.name,
6853
+ stack: error.stack
6854
+ });
6855
+ }
6856
+ throw error;
6774
6857
  }
6775
- throw error;
6776
6858
  }
6777
- }),
6859
+ ),
6778
6860
  pageInfo: {
6779
6861
  hasPreviousPage,
6780
6862
  hasNextPage,
@@ -6799,7 +6881,7 @@ var Database = class {
6799
6881
  try {
6800
6882
  lookup = lookupFromLockFile || JSON.parse(
6801
6883
  await this.bridge.get(
6802
- (0, import_schema_tools3.normalizePath)(
6884
+ (0, import_schema_tools4.normalizePath)(
6803
6885
  import_node_path.default.join(this.getGeneratedFolder(), "_lookup.json")
6804
6886
  )
6805
6887
  )
@@ -6824,15 +6906,15 @@ var Database = class {
6824
6906
  }
6825
6907
  const contentRootLevel = nextLevel.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS);
6826
6908
  await contentRootLevel.put(
6827
- (0, import_schema_tools3.normalizePath)(import_node_path.default.join(this.getGeneratedFolder(), "_graphql.json")),
6909
+ (0, import_schema_tools4.normalizePath)(import_node_path.default.join(this.getGeneratedFolder(), "_graphql.json")),
6828
6910
  graphQLSchema
6829
6911
  );
6830
6912
  await contentRootLevel.put(
6831
- (0, import_schema_tools3.normalizePath)(import_node_path.default.join(this.getGeneratedFolder(), "_schema.json")),
6913
+ (0, import_schema_tools4.normalizePath)(import_node_path.default.join(this.getGeneratedFolder(), "_schema.json")),
6832
6914
  tinaSchema.schema
6833
6915
  );
6834
6916
  await contentRootLevel.put(
6835
- (0, import_schema_tools3.normalizePath)(import_node_path.default.join(this.getGeneratedFolder(), "_lookup.json")),
6917
+ (0, import_schema_tools4.normalizePath)(import_node_path.default.join(this.getGeneratedFolder(), "_lookup.json")),
6836
6918
  lookup
6837
6919
  );
6838
6920
  const result = await this._indexAllContent(
@@ -6914,18 +6996,20 @@ var Database = class {
6914
6996
  }
6915
6997
  };
6916
6998
  this.delete = async (filepath) => {
6999
+ var _a;
6917
7000
  await this.initLevel();
6918
7001
  const collection = await this.collectionForPath(filepath);
6919
7002
  if (!collection) {
6920
7003
  throw new Error(`No collection found for path: ${filepath}`);
6921
7004
  }
6922
7005
  const indexDefinitions = await this.getIndexDefinitions(this.contentLevel);
7006
+ const collectionReferences = (_a = await this.getCollectionReferences()) == null ? void 0 : _a[collection.name];
6923
7007
  const collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collection.name];
6924
7008
  let level = this.contentLevel;
6925
7009
  if (collection == null ? void 0 : collection.isDetached) {
6926
7010
  level = this.appLevel.sublevel(collection == null ? void 0 : collection.name, SUBLEVEL_OPTIONS);
6927
7011
  }
6928
- const normalizedPath = (0, import_schema_tools3.normalizePath)(filepath);
7012
+ const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
6929
7013
  const rootSublevel = level.sublevel(
6930
7014
  CONTENT_ROOT_PREFIX,
6931
7015
  SUBLEVEL_OPTIONS
@@ -6938,6 +7022,14 @@ var Database = class {
6938
7022
  collection.path || ""
6939
7023
  );
6940
7024
  await this.contentLevel.batch([
7025
+ ...makeRefOpsForDocument(
7026
+ normalizedPath,
7027
+ collection.name,
7028
+ collectionReferences,
7029
+ item,
7030
+ "del",
7031
+ level
7032
+ ),
6941
7033
  ...makeIndexOpsForDocument(
6942
7034
  normalizedPath,
6943
7035
  collection.name,
@@ -7155,6 +7247,7 @@ var hashPasswordValues = async (data, passwordFields) => Promise.all(
7155
7247
  );
7156
7248
  var isGitKeep = (filepath, collection) => filepath.endsWith(`.gitkeep.${(collection == null ? void 0 : collection.format) || "md"}`);
7157
7249
  var _indexContent = async (database, level, documentPaths, enqueueOps, collection, passwordFields) => {
7250
+ var _a;
7158
7251
  let collectionIndexDefinitions;
7159
7252
  let collectionPath;
7160
7253
  if (collection) {
@@ -7165,6 +7258,7 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7165
7258
  }
7166
7259
  collectionPath = collection.path;
7167
7260
  }
7261
+ const collectionReferences = (_a = await database.getCollectionReferences()) == null ? void 0 : _a[collection == null ? void 0 : collection.name];
7168
7262
  const tinaSchema = await database.getSchema();
7169
7263
  let templateInfo = null;
7170
7264
  if (collection) {
@@ -7185,13 +7279,60 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7185
7279
  if (passwordFields == null ? void 0 : passwordFields.length) {
7186
7280
  await hashPasswordValues(aliasedData, passwordFields);
7187
7281
  }
7188
- const normalizedPath = (0, import_schema_tools3.normalizePath)(filepath);
7282
+ const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
7283
+ const rootSublevel = level.sublevel(
7284
+ CONTENT_ROOT_PREFIX,
7285
+ SUBLEVEL_OPTIONS
7286
+ );
7189
7287
  const folderKey = folderTreeBuilder.update(
7190
7288
  normalizedPath,
7191
7289
  collectionPath || ""
7192
7290
  );
7291
+ const item = await rootSublevel.get(normalizedPath);
7292
+ if (item) {
7293
+ await database.contentLevel.batch([
7294
+ ...makeRefOpsForDocument(
7295
+ normalizedPath,
7296
+ collection == null ? void 0 : collection.name,
7297
+ collectionReferences,
7298
+ item,
7299
+ "del",
7300
+ level
7301
+ ),
7302
+ ...makeIndexOpsForDocument(
7303
+ normalizedPath,
7304
+ collection.name,
7305
+ collectionIndexDefinitions,
7306
+ item,
7307
+ "del",
7308
+ level
7309
+ ),
7310
+ // folder indices
7311
+ ...makeIndexOpsForDocument(
7312
+ normalizedPath,
7313
+ `${collection.name}_${folderKey}`,
7314
+ collectionIndexDefinitions,
7315
+ item,
7316
+ "del",
7317
+ level
7318
+ ),
7319
+ {
7320
+ type: "del",
7321
+ key: normalizedPath,
7322
+ sublevel: rootSublevel
7323
+ }
7324
+ ]);
7325
+ }
7193
7326
  if (!isGitKeep(filepath, collection)) {
7194
7327
  await enqueueOps([
7328
+ ...makeRefOpsForDocument(
7329
+ normalizedPath,
7330
+ collection == null ? void 0 : collection.name,
7331
+ collectionReferences,
7332
+ aliasedData,
7333
+ "put",
7334
+ level
7335
+ ),
7195
7336
  ...makeIndexOpsForDocument(
7196
7337
  normalizedPath,
7197
7338
  collection == null ? void 0 : collection.name,
@@ -7242,6 +7383,7 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7242
7383
  }
7243
7384
  };
7244
7385
  var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection) => {
7386
+ var _a;
7245
7387
  if (!documentPaths.length) {
7246
7388
  return;
7247
7389
  }
@@ -7255,6 +7397,7 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7255
7397
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
7256
7398
  }
7257
7399
  }
7400
+ const collectionReferences = (_a = await database.getCollectionReferences()) == null ? void 0 : _a[collection == null ? void 0 : collection.name];
7258
7401
  const tinaSchema = await database.getSchema();
7259
7402
  let templateInfo = null;
7260
7403
  if (collection) {
@@ -7266,7 +7409,7 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7266
7409
  );
7267
7410
  const folderTreeBuilder = new FolderTreeBuilder();
7268
7411
  await sequential(documentPaths, async (filepath) => {
7269
- const itemKey = (0, import_schema_tools3.normalizePath)(filepath);
7412
+ const itemKey = (0, import_schema_tools4.normalizePath)(filepath);
7270
7413
  const item = await rootLevel.get(itemKey);
7271
7414
  if (item) {
7272
7415
  const folderKey = folderTreeBuilder.update(
@@ -7278,6 +7421,14 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7278
7421
  item
7279
7422
  ) : item;
7280
7423
  await enqueueOps([
7424
+ ...makeRefOpsForDocument(
7425
+ itemKey,
7426
+ collection == null ? void 0 : collection.name,
7427
+ collectionReferences,
7428
+ aliasedData,
7429
+ "del",
7430
+ database.contentLevel
7431
+ ),
7281
7432
  ...makeIndexOpsForDocument(
7282
7433
  itemKey,
7283
7434
  collection.name,
@@ -7353,14 +7504,14 @@ var getChangedFiles = async ({
7353
7504
  const rootDir = await findGitRoot(dir);
7354
7505
  let pathPrefix = "";
7355
7506
  if (rootDir !== dir) {
7356
- pathPrefix = (0, import_schema_tools3.normalizePath)(dir.substring(rootDir.length + 1));
7507
+ pathPrefix = (0, import_schema_tools4.normalizePath)(dir.substring(rootDir.length + 1));
7357
7508
  }
7358
7509
  await import_isomorphic_git.default.walk({
7359
7510
  fs: fs4,
7360
7511
  dir: rootDir,
7361
7512
  trees: [import_isomorphic_git.default.TREE({ ref: from }), import_isomorphic_git.default.TREE({ ref: to })],
7362
7513
  map: async function(filename, [A, B]) {
7363
- const relativePath = (0, import_schema_tools3.normalizePath)(filename).substring(pathPrefix.length);
7514
+ const relativePath = (0, import_schema_tools4.normalizePath)(filename).substring(pathPrefix.length);
7364
7515
  let matches = false;
7365
7516
  for (const [key, matcher] of Object.entries(pathFilter)) {
7366
7517
  if (relativePath.startsWith(key)) {