@tinacms/graphql 0.0.0-ebe1b69-20250211022853 → 0.0.0-ec43c87-20250804021103

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.mjs CHANGED
@@ -1847,7 +1847,7 @@ var Builder = class {
1847
1847
  * ```
1848
1848
  *
1849
1849
  * @public
1850
- * @param collection a Tina Cloud collection
1850
+ * @param collection a TinaCloud collection
1851
1851
  */
1852
1852
  this.collectionFragment = async (collection) => {
1853
1853
  const name = NAMER.dataTypeName(collection.namespace);
@@ -3019,7 +3019,7 @@ var validateField = async (field) => {
3019
3019
  // package.json
3020
3020
  var package_default = {
3021
3021
  name: "@tinacms/graphql",
3022
- version: "1.5.11",
3022
+ version: "1.6.0",
3023
3023
  main: "dist/index.js",
3024
3024
  module: "dist/index.mjs",
3025
3025
  typings: "dist/index.d.ts",
@@ -3045,33 +3045,32 @@ var package_default = {
3045
3045
  types: "pnpm tsc",
3046
3046
  build: "tinacms-scripts build",
3047
3047
  docs: "pnpm typedoc",
3048
- serve: "pnpm nodemon dist/server.js",
3049
3048
  test: "vitest run",
3050
3049
  "test-watch": "vitest"
3051
3050
  },
3052
3051
  dependencies: {
3053
- "@iarna/toml": "^2.2.5",
3052
+ "@iarna/toml": "catalog:",
3054
3053
  "@tinacms/mdx": "workspace:*",
3055
3054
  "@tinacms/schema-tools": "workspace:*",
3056
- "abstract-level": "^1.0.4",
3055
+ "abstract-level": "catalog:",
3057
3056
  "date-fns": "^2.30.0",
3058
- "fast-glob": "^3.3.2",
3059
- "fs-extra": "^11.2.0",
3060
- "glob-parent": "^6.0.2",
3057
+ "fast-glob": "catalog:",
3058
+ "fs-extra": "catalog:",
3059
+ "glob-parent": "catalog:",
3061
3060
  graphql: "15.8.0",
3062
- "gray-matter": "^4.0.3",
3063
- "isomorphic-git": "^1.27.1",
3064
- "js-sha1": "^0.6.0",
3061
+ "gray-matter": "catalog:",
3062
+ "isomorphic-git": "catalog:",
3063
+ "js-sha1": "catalog:",
3065
3064
  "js-yaml": "^3.14.1",
3066
- "jsonpath-plus": "10.1.0",
3067
- "lodash.clonedeep": "^4.5.0",
3068
- "lodash.set": "^4.3.2",
3069
- "lodash.uniqby": "^4.7.0",
3070
- "many-level": "^2.0.0",
3071
- micromatch: "4.0.8",
3072
- "normalize-path": "^3.0.0",
3073
- "readable-stream": "^4.5.2",
3074
- scmp: "^2.1.0",
3065
+ "jsonpath-plus": "catalog:",
3066
+ "lodash.clonedeep": "catalog:",
3067
+ "lodash.set": "catalog:",
3068
+ "lodash.uniqby": "catalog:",
3069
+ "many-level": "catalog:",
3070
+ micromatch: "catalog:",
3071
+ "normalize-path": "catalog:",
3072
+ "readable-stream": "catalog:",
3073
+ scmp: "catalog:",
3075
3074
  yup: "^0.32.11"
3076
3075
  },
3077
3076
  publishConfig: {
@@ -3086,25 +3085,24 @@ var package_default = {
3086
3085
  "@tinacms/scripts": "workspace:*",
3087
3086
  "@types/cors": "^2.8.17",
3088
3087
  "@types/estree": "^0.0.50",
3089
- "@types/express": "^4.17.21",
3088
+ "@types/express": "catalog:",
3090
3089
  "@types/fs-extra": "^9.0.13",
3091
3090
  "@types/js-yaml": "^3.12.10",
3092
- "@types/lodash.camelcase": "^4.3.9",
3093
- "@types/lodash.upperfirst": "^4.3.9",
3094
- "@types/lru-cache": "^5.1.1",
3095
- "@types/mdast": "^3.0.15",
3096
- "@types/micromatch": "^4.0.9",
3097
- "@types/node": "^22.9.0",
3098
- "@types/normalize-path": "^3.0.2",
3099
- "@types/ws": "^7.4.7",
3091
+ "@types/lodash.camelcase": "catalog:",
3092
+ "@types/lodash.upperfirst": "catalog:",
3093
+ "@types/lru-cache": "catalog:",
3094
+ "@types/mdast": "catalog:",
3095
+ "@types/micromatch": "catalog:",
3096
+ "@types/node": "^22.13.1",
3097
+ "@types/normalize-path": "catalog:",
3098
+ "@types/ws": "catalog:",
3100
3099
  "@types/yup": "^0.29.14",
3101
3100
  "jest-file-snapshot": "^0.5.0",
3102
- "memory-level": "^1.0.0",
3103
- nodemon: "3.1.4",
3104
- typescript: "^5.6.3",
3105
- vite: "^4.3.9",
3106
- vitest: "^0.32.2",
3107
- zod: "^3.23.8"
3101
+ "memory-level": "catalog:",
3102
+ typescript: "^5.7.3",
3103
+ vite: "^4.5.9",
3104
+ vitest: "^0.32.4",
3105
+ zod: "^3.24.2"
3108
3106
  }
3109
3107
  };
3110
3108
 
@@ -3260,7 +3258,9 @@ var _buildSchema = async (builder, tinaSchema) => {
3260
3258
  await builder.buildCreateCollectionFolderMutation()
3261
3259
  );
3262
3260
  await sequential(collections, async (collection) => {
3263
- queryTypeDefinitionFields.push(await builder.collectionDocument(collection));
3261
+ queryTypeDefinitionFields.push(
3262
+ await builder.collectionDocument(collection)
3263
+ );
3264
3264
  if (collection.isAuthCollection) {
3265
3265
  queryTypeDefinitionFields.push(
3266
3266
  await builder.authenticationCollectionDocument(collection)
@@ -3310,249 +3310,10 @@ import { graphql, buildASTSchema, getNamedType, GraphQLError as GraphQLError4 }
3310
3310
  // src/resolver/index.ts
3311
3311
  import path3 from "path";
3312
3312
  import isValid from "date-fns/isValid/index.js";
3313
-
3314
- // src/mdx/index.ts
3315
- import { parseMDX, stringifyMDX } from "@tinacms/mdx";
3316
-
3317
- // src/resolver/index.ts
3318
3313
  import { JSONPath as JSONPath2 } from "jsonpath-plus";
3319
3314
 
3320
- // src/resolver/error.ts
3321
- var TinaGraphQLError = class extends Error {
3322
- constructor(message, extensions) {
3323
- super(message);
3324
- if (!this.name) {
3325
- Object.defineProperty(this, "name", { value: "TinaGraphQLError" });
3326
- }
3327
- this.extensions = { ...extensions };
3328
- }
3329
- };
3330
- var TinaFetchError = class extends Error {
3331
- constructor(message, args) {
3332
- super(message);
3333
- this.name = "TinaFetchError";
3334
- this.collection = args.collection;
3335
- this.stack = args.stack;
3336
- this.file = args.file;
3337
- this.originalError = args.originalError;
3338
- }
3339
- };
3340
- var TinaQueryError = class extends TinaFetchError {
3341
- constructor(args) {
3342
- super(
3343
- `Error querying file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
3344
- args
3345
- );
3346
- }
3347
- };
3348
- var TinaParseDocumentError = class extends TinaFetchError {
3349
- constructor(args) {
3350
- super(
3351
- `Error parsing file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
3352
- args
3353
- );
3354
- }
3355
- toString() {
3356
- return super.toString() + "\n OriginalError: \n" + this.originalError.toString();
3357
- }
3358
- };
3359
- var auditMessage = (includeAuditMessage = true) => includeAuditMessage ? `Please run "tinacms audit" or add the --verbose option for more info` : "";
3360
- var handleFetchErrorError = (e, verbose) => {
3361
- if (e instanceof Error) {
3362
- if (e instanceof TinaFetchError) {
3363
- if (verbose) {
3364
- console.log(e.toString());
3365
- console.log(e);
3366
- console.log(e.stack);
3367
- }
3368
- }
3369
- } else {
3370
- console.error(e);
3371
- }
3372
- throw e;
3373
- };
3374
-
3375
- // src/resolver/filter-utils.ts
3376
- var resolveReferences = async (filter, fields, resolver) => {
3377
- for (const fieldKey of Object.keys(filter)) {
3378
- const fieldDefinition = fields.find(
3379
- (f) => f.name === fieldKey
3380
- );
3381
- if (fieldDefinition) {
3382
- if (fieldDefinition.type === "reference") {
3383
- const { edges, values } = await resolver(filter, fieldDefinition);
3384
- if (edges.length === 1) {
3385
- filter[fieldKey] = {
3386
- eq: values[0]
3387
- };
3388
- } else if (edges.length > 1) {
3389
- filter[fieldKey] = {
3390
- in: values
3391
- };
3392
- } else {
3393
- filter[fieldKey] = {
3394
- eq: "___null___"
3395
- };
3396
- }
3397
- } else if (fieldDefinition.type === "object") {
3398
- if (fieldDefinition.templates) {
3399
- for (const templateName of Object.keys(filter[fieldKey])) {
3400
- const template = fieldDefinition.templates.find(
3401
- (template2) => !(typeof template2 === "string") && template2.name === templateName
3402
- );
3403
- if (template) {
3404
- await resolveReferences(
3405
- filter[fieldKey][templateName],
3406
- template.fields,
3407
- resolver
3408
- );
3409
- } else {
3410
- throw new Error(`Template ${templateName} not found`);
3411
- }
3412
- }
3413
- } else {
3414
- await resolveReferences(
3415
- filter[fieldKey],
3416
- fieldDefinition.fields,
3417
- resolver
3418
- );
3419
- }
3420
- }
3421
- } else {
3422
- throw new Error(`Unable to find field ${fieldKey}`);
3423
- }
3424
- }
3425
- };
3426
- var collectConditionsForChildFields = (filterNode, fields, pathExpression, collectCondition) => {
3427
- for (const childFieldName of Object.keys(filterNode)) {
3428
- const childField = fields.find((field) => field.name === childFieldName);
3429
- if (!childField) {
3430
- throw new Error(`Unable to find type for field ${childFieldName}`);
3431
- }
3432
- collectConditionsForField(
3433
- childFieldName,
3434
- childField,
3435
- filterNode[childFieldName],
3436
- pathExpression,
3437
- collectCondition
3438
- );
3439
- }
3440
- };
3441
- var collectConditionsForObjectField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
3442
- if (field.list && field.templates) {
3443
- for (const [filterKey, childFilterNode] of Object.entries(filterNode)) {
3444
- const template = field.templates.find(
3445
- (template2) => !(typeof template2 === "string") && template2.name === filterKey
3446
- );
3447
- const jsonPath = `${fieldName}[?(@._template=="${filterKey}")]`;
3448
- const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : jsonPath;
3449
- collectConditionsForChildFields(
3450
- childFilterNode,
3451
- template.fields,
3452
- filterPath,
3453
- collectCondition
3454
- );
3455
- }
3456
- } else {
3457
- const jsonPath = `${fieldName}${field.list ? "[*]" : ""}`;
3458
- const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : `${jsonPath}`;
3459
- collectConditionsForChildFields(
3460
- filterNode,
3461
- field.fields,
3462
- filterPath,
3463
- collectCondition
3464
- );
3465
- }
3466
- };
3467
- var collectConditionsForField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
3468
- if (field.type === "object") {
3469
- collectConditionsForObjectField(
3470
- fieldName,
3471
- field,
3472
- filterNode,
3473
- pathExpression,
3474
- collectCondition
3475
- );
3476
- } else {
3477
- collectCondition({
3478
- filterPath: pathExpression ? `${pathExpression}.${fieldName}` : fieldName,
3479
- filterExpression: {
3480
- _type: field.type,
3481
- _list: !!field.list,
3482
- ...filterNode
3483
- }
3484
- });
3485
- }
3486
- };
3487
-
3488
- // src/resolver/media-utils.ts
3489
- var resolveMediaCloudToRelative = (value, config = { useRelativeMedia: true }, schema) => {
3490
- if (config && value) {
3491
- if (config.useRelativeMedia === true) {
3492
- return value;
3493
- }
3494
- if (hasTinaMediaConfig(schema) === true) {
3495
- const assetsURL = `https://${config.assetsHost}/${config.clientId}`;
3496
- if (typeof value === "string" && value.includes(assetsURL)) {
3497
- const cleanMediaRoot = cleanUpSlashes(
3498
- schema.config.media.tina.mediaRoot
3499
- );
3500
- const strippedURL = value.replace(assetsURL, "");
3501
- return `${cleanMediaRoot}${strippedURL}`;
3502
- }
3503
- if (Array.isArray(value)) {
3504
- return value.map((v) => {
3505
- if (!v || typeof v !== "string") return v;
3506
- const cleanMediaRoot = cleanUpSlashes(
3507
- schema.config.media.tina.mediaRoot
3508
- );
3509
- const strippedURL = v.replace(assetsURL, "");
3510
- return `${cleanMediaRoot}${strippedURL}`;
3511
- });
3512
- }
3513
- return value;
3514
- }
3515
- return value;
3516
- } else {
3517
- return value;
3518
- }
3519
- };
3520
- var resolveMediaRelativeToCloud = (value, config = { useRelativeMedia: true }, schema) => {
3521
- if (config && value) {
3522
- if (config.useRelativeMedia === true) {
3523
- return value;
3524
- }
3525
- if (hasTinaMediaConfig(schema) === true) {
3526
- const cleanMediaRoot = cleanUpSlashes(schema.config.media.tina.mediaRoot);
3527
- if (typeof value === "string") {
3528
- const strippedValue = value.replace(cleanMediaRoot, "");
3529
- return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
3530
- }
3531
- if (Array.isArray(value)) {
3532
- return value.map((v) => {
3533
- if (!v || typeof v !== "string") return v;
3534
- const strippedValue = v.replace(cleanMediaRoot, "");
3535
- return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
3536
- });
3537
- }
3538
- }
3539
- return value;
3540
- } else {
3541
- return value;
3542
- }
3543
- };
3544
- var cleanUpSlashes = (path7) => {
3545
- if (path7) {
3546
- return `/${path7.replace(/^\/+|\/+$/gm, "")}`;
3547
- }
3548
- return "";
3549
- };
3550
- var hasTinaMediaConfig = (schema) => {
3551
- if (!schema.config?.media?.tina) return false;
3552
- if (typeof schema.config?.media?.tina?.publicFolder !== "string" && typeof schema.config?.media?.tina?.mediaRoot !== "string")
3553
- return false;
3554
- return true;
3555
- };
3315
+ // src/mdx/index.ts
3316
+ import { parseMDX, serializeMDX } from "@tinacms/mdx";
3556
3317
 
3557
3318
  // src/resolver/index.ts
3558
3319
  import { GraphQLError as GraphQLError2 } from "graphql";
@@ -3575,7 +3336,9 @@ var LevelProxyHandler = {
3575
3336
  throw new Error(`The property, ${property.toString()}, doesn't exist`);
3576
3337
  }
3577
3338
  if (typeof target[property] !== "function") {
3578
- throw new Error(`The property, ${property.toString()}, is not a function`);
3339
+ throw new Error(
3340
+ `The property, ${property.toString()}, is not a function`
3341
+ );
3579
3342
  }
3580
3343
  if (property === "get") {
3581
3344
  return async (...args) => {
@@ -3613,13 +3376,13 @@ import path2 from "path";
3613
3376
 
3614
3377
  // src/database/util.ts
3615
3378
  import toml from "@iarna/toml";
3616
- import yaml from "js-yaml";
3617
- import matter from "gray-matter";
3618
3379
  import {
3619
3380
  normalizePath
3620
3381
  } from "@tinacms/schema-tools";
3621
- import micromatch from "micromatch";
3382
+ import matter from "gray-matter";
3383
+ import yaml from "js-yaml";
3622
3384
  import path from "path";
3385
+ import micromatch from "micromatch";
3623
3386
 
3624
3387
  // src/database/alias-utils.ts
3625
3388
  var replaceBlockAliases = (template, item) => {
@@ -3960,6 +3723,9 @@ var loadAndParseWithAliases = async (bridge, filepath, collection, templateInfo)
3960
3723
 
3961
3724
  // src/database/datalayer.ts
3962
3725
  var DEFAULT_COLLECTION_SORT_KEY = "__filepath__";
3726
+ var REFS_COLLECTIONS_SORT_KEY = "__refs__";
3727
+ var REFS_REFERENCE_FIELD = "__tina_ref__";
3728
+ var REFS_PATH_FIELD = "__tina_ref_path__";
3963
3729
  var DEFAULT_NUMERIC_LPAD = 4;
3964
3730
  var applyPadding = (input, pad) => {
3965
3731
  if (pad) {
@@ -4503,55 +4269,343 @@ var makeFolderOpsForCollection = (folderTree, collection, indexDefinitions, opTy
4503
4269
  });
4504
4270
  }
4505
4271
  }
4506
- return result;
4272
+ return result;
4273
+ };
4274
+ var makeIndexOpsForDocument = (filepath, collection, indexDefinitions, data, opType, level, escapeStr = stringEscaper) => {
4275
+ const result = [];
4276
+ if (collection) {
4277
+ const collectionSublevel = level.sublevel(collection, SUBLEVEL_OPTIONS);
4278
+ for (const [sort, definition] of Object.entries(indexDefinitions)) {
4279
+ const indexedValue = makeKeyForField(definition, data, escapeStr);
4280
+ const indexSublevel = collectionSublevel.sublevel(sort, SUBLEVEL_OPTIONS);
4281
+ if (sort === DEFAULT_COLLECTION_SORT_KEY) {
4282
+ result.push({
4283
+ type: opType,
4284
+ key: filepath,
4285
+ sublevel: indexSublevel,
4286
+ value: opType === "put" ? {} : void 0
4287
+ });
4288
+ } else {
4289
+ if (indexedValue) {
4290
+ result.push({
4291
+ type: opType,
4292
+ key: `${indexedValue}${INDEX_KEY_FIELD_SEPARATOR}${filepath}`,
4293
+ sublevel: indexSublevel,
4294
+ value: opType === "put" ? {} : void 0
4295
+ });
4296
+ }
4297
+ }
4298
+ }
4299
+ }
4300
+ return result;
4301
+ };
4302
+ var makeRefOpsForDocument = (filepath, collection, references, data, opType, level) => {
4303
+ const result = [];
4304
+ if (collection) {
4305
+ for (const [c, referencePaths] of Object.entries(references || {})) {
4306
+ if (!referencePaths.length) {
4307
+ continue;
4308
+ }
4309
+ const collectionSublevel = level.sublevel(c, SUBLEVEL_OPTIONS);
4310
+ const refSublevel = collectionSublevel.sublevel(
4311
+ REFS_COLLECTIONS_SORT_KEY,
4312
+ SUBLEVEL_OPTIONS
4313
+ );
4314
+ const references2 = {};
4315
+ for (const path7 of referencePaths) {
4316
+ const ref = JSONPath({ path: path7, json: data });
4317
+ if (!ref) {
4318
+ continue;
4319
+ }
4320
+ if (Array.isArray(ref)) {
4321
+ for (const r of ref) {
4322
+ if (!r) {
4323
+ continue;
4324
+ }
4325
+ if (references2[r]) {
4326
+ references2[r].push(path7);
4327
+ } else {
4328
+ references2[r] = [path7];
4329
+ }
4330
+ }
4331
+ } else {
4332
+ if (references2[ref]) {
4333
+ references2[ref].push(path7);
4334
+ } else {
4335
+ references2[ref] = [path7];
4336
+ }
4337
+ }
4338
+ }
4339
+ for (const ref of Object.keys(references2)) {
4340
+ for (const path7 of references2[ref]) {
4341
+ result.push({
4342
+ type: opType,
4343
+ key: `${ref}${INDEX_KEY_FIELD_SEPARATOR}${path7}${INDEX_KEY_FIELD_SEPARATOR}${filepath}`,
4344
+ sublevel: refSublevel,
4345
+ value: opType === "put" ? {} : void 0
4346
+ });
4347
+ }
4348
+ }
4349
+ }
4350
+ }
4351
+ return result;
4352
+ };
4353
+ var makeStringEscaper = (regex, replacement) => {
4354
+ return (input) => {
4355
+ if (Array.isArray(input)) {
4356
+ return input.map(
4357
+ (val) => val.replace(regex, replacement)
4358
+ );
4359
+ } else {
4360
+ if (typeof input === "string") {
4361
+ return input.replace(regex, replacement);
4362
+ } else {
4363
+ return input;
4364
+ }
4365
+ }
4366
+ };
4367
+ };
4368
+ var stringEscaper = makeStringEscaper(
4369
+ new RegExp(INDEX_KEY_FIELD_SEPARATOR, "gm"),
4370
+ encodeURIComponent(INDEX_KEY_FIELD_SEPARATOR)
4371
+ );
4372
+
4373
+ // src/resolver/error.ts
4374
+ var TinaGraphQLError = class extends Error {
4375
+ constructor(message, extensions) {
4376
+ super(message);
4377
+ if (!this.name) {
4378
+ Object.defineProperty(this, "name", { value: "TinaGraphQLError" });
4379
+ }
4380
+ this.extensions = { ...extensions };
4381
+ }
4382
+ };
4383
+ var TinaFetchError = class extends Error {
4384
+ constructor(message, args) {
4385
+ super(message);
4386
+ this.name = "TinaFetchError";
4387
+ this.collection = args.collection;
4388
+ this.stack = args.stack;
4389
+ this.file = args.file;
4390
+ this.originalError = args.originalError;
4391
+ }
4392
+ };
4393
+ var TinaQueryError = class extends TinaFetchError {
4394
+ constructor(args) {
4395
+ super(
4396
+ `Error querying file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
4397
+ args
4398
+ );
4399
+ }
4400
+ };
4401
+ var TinaParseDocumentError = class extends TinaFetchError {
4402
+ constructor(args) {
4403
+ super(
4404
+ `Error parsing file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
4405
+ args
4406
+ );
4407
+ }
4408
+ toString() {
4409
+ return super.toString() + "\n OriginalError: \n" + this.originalError.toString();
4410
+ }
4411
+ };
4412
+ var auditMessage = (includeAuditMessage = true) => includeAuditMessage ? `Please run "tinacms audit" or add the --verbose option for more info` : "";
4413
+ var handleFetchErrorError = (e, verbose) => {
4414
+ if (e instanceof Error) {
4415
+ if (e instanceof TinaFetchError) {
4416
+ if (verbose) {
4417
+ console.log(e.toString());
4418
+ console.log(e);
4419
+ console.log(e.stack);
4420
+ }
4421
+ }
4422
+ } else {
4423
+ console.error(e);
4424
+ }
4425
+ throw e;
4426
+ };
4427
+
4428
+ // src/resolver/filter-utils.ts
4429
+ var resolveReferences = async (filter, fields, resolver) => {
4430
+ for (const fieldKey of Object.keys(filter)) {
4431
+ const fieldDefinition = fields.find(
4432
+ (f) => f.name === fieldKey
4433
+ );
4434
+ if (fieldDefinition) {
4435
+ if (fieldDefinition.type === "reference") {
4436
+ const { edges, values } = await resolver(filter, fieldDefinition);
4437
+ if (edges.length === 1) {
4438
+ filter[fieldKey] = {
4439
+ eq: values[0]
4440
+ };
4441
+ } else if (edges.length > 1) {
4442
+ filter[fieldKey] = {
4443
+ in: values
4444
+ };
4445
+ } else {
4446
+ filter[fieldKey] = {
4447
+ eq: "___null___"
4448
+ };
4449
+ }
4450
+ } else if (fieldDefinition.type === "object") {
4451
+ if (fieldDefinition.templates) {
4452
+ for (const templateName of Object.keys(filter[fieldKey])) {
4453
+ const template = fieldDefinition.templates.find(
4454
+ (template2) => !(typeof template2 === "string") && template2.name === templateName
4455
+ );
4456
+ if (template) {
4457
+ await resolveReferences(
4458
+ filter[fieldKey][templateName],
4459
+ template.fields,
4460
+ resolver
4461
+ );
4462
+ } else {
4463
+ throw new Error(`Template ${templateName} not found`);
4464
+ }
4465
+ }
4466
+ } else {
4467
+ await resolveReferences(
4468
+ filter[fieldKey],
4469
+ fieldDefinition.fields,
4470
+ resolver
4471
+ );
4472
+ }
4473
+ }
4474
+ } else {
4475
+ throw new Error(`Unable to find field ${fieldKey}`);
4476
+ }
4477
+ }
4478
+ };
4479
+ var collectConditionsForChildFields = (filterNode, fields, pathExpression, collectCondition) => {
4480
+ for (const childFieldName of Object.keys(filterNode)) {
4481
+ const childField = fields.find((field) => field.name === childFieldName);
4482
+ if (!childField) {
4483
+ throw new Error(`Unable to find type for field ${childFieldName}`);
4484
+ }
4485
+ collectConditionsForField(
4486
+ childFieldName,
4487
+ childField,
4488
+ filterNode[childFieldName],
4489
+ pathExpression,
4490
+ collectCondition
4491
+ );
4492
+ }
4493
+ };
4494
+ var collectConditionsForObjectField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
4495
+ if (field.list && field.templates) {
4496
+ for (const [filterKey, childFilterNode] of Object.entries(filterNode)) {
4497
+ const template = field.templates.find(
4498
+ (template2) => !(typeof template2 === "string") && template2.name === filterKey
4499
+ );
4500
+ const jsonPath = `${fieldName}[?(@._template=="${filterKey}")]`;
4501
+ const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : jsonPath;
4502
+ collectConditionsForChildFields(
4503
+ childFilterNode,
4504
+ template.fields,
4505
+ filterPath,
4506
+ collectCondition
4507
+ );
4508
+ }
4509
+ } else {
4510
+ const jsonPath = `${fieldName}${field.list ? "[*]" : ""}`;
4511
+ const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : `${jsonPath}`;
4512
+ collectConditionsForChildFields(
4513
+ filterNode,
4514
+ field.fields,
4515
+ filterPath,
4516
+ collectCondition
4517
+ );
4518
+ }
4519
+ };
4520
+ var collectConditionsForField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
4521
+ if (field.type === "object") {
4522
+ collectConditionsForObjectField(
4523
+ fieldName,
4524
+ field,
4525
+ filterNode,
4526
+ pathExpression,
4527
+ collectCondition
4528
+ );
4529
+ } else {
4530
+ collectCondition({
4531
+ filterPath: pathExpression ? `${pathExpression}.${fieldName}` : fieldName,
4532
+ filterExpression: {
4533
+ _type: field.type,
4534
+ _list: !!field.list,
4535
+ ...filterNode
4536
+ }
4537
+ });
4538
+ }
4539
+ };
4540
+
4541
+ // src/resolver/media-utils.ts
4542
+ var resolveMediaCloudToRelative = (value, config = { useRelativeMedia: true }, schema) => {
4543
+ if (config && value) {
4544
+ if (config.useRelativeMedia === true) {
4545
+ return value;
4546
+ }
4547
+ if (hasTinaMediaConfig(schema) === true) {
4548
+ const assetsURL = `https://${config.assetsHost}/${config.clientId}`;
4549
+ if (typeof value === "string" && value.includes(assetsURL)) {
4550
+ const cleanMediaRoot = cleanUpSlashes(
4551
+ schema.config.media.tina.mediaRoot
4552
+ );
4553
+ const strippedURL = value.replace(assetsURL, "");
4554
+ return `${cleanMediaRoot}${strippedURL}`;
4555
+ }
4556
+ if (Array.isArray(value)) {
4557
+ return value.map((v) => {
4558
+ if (!v || typeof v !== "string") return v;
4559
+ const cleanMediaRoot = cleanUpSlashes(
4560
+ schema.config.media.tina.mediaRoot
4561
+ );
4562
+ const strippedURL = v.replace(assetsURL, "");
4563
+ return `${cleanMediaRoot}${strippedURL}`;
4564
+ });
4565
+ }
4566
+ return value;
4567
+ }
4568
+ return value;
4569
+ } else {
4570
+ return value;
4571
+ }
4507
4572
  };
4508
- var makeIndexOpsForDocument = (filepath, collection, indexDefinitions, data, opType, level, escapeStr = stringEscaper) => {
4509
- const result = [];
4510
- if (collection) {
4511
- const collectionSublevel = level.sublevel(collection, SUBLEVEL_OPTIONS);
4512
- for (const [sort, definition] of Object.entries(indexDefinitions)) {
4513
- const indexedValue = makeKeyForField(definition, data, escapeStr);
4514
- const indexSublevel = collectionSublevel.sublevel(sort, SUBLEVEL_OPTIONS);
4515
- if (sort === DEFAULT_COLLECTION_SORT_KEY) {
4516
- result.push({
4517
- type: opType,
4518
- key: filepath,
4519
- sublevel: indexSublevel,
4520
- value: opType === "put" ? {} : void 0
4573
+ var resolveMediaRelativeToCloud = (value, config = { useRelativeMedia: true }, schema) => {
4574
+ if (config && value) {
4575
+ if (config.useRelativeMedia === true) {
4576
+ return value;
4577
+ }
4578
+ if (hasTinaMediaConfig(schema) === true) {
4579
+ const cleanMediaRoot = cleanUpSlashes(schema.config.media.tina.mediaRoot);
4580
+ if (typeof value === "string") {
4581
+ const strippedValue = value.replace(cleanMediaRoot, "");
4582
+ return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
4583
+ }
4584
+ if (Array.isArray(value)) {
4585
+ return value.map((v) => {
4586
+ if (!v || typeof v !== "string") return v;
4587
+ const strippedValue = v.replace(cleanMediaRoot, "");
4588
+ return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
4521
4589
  });
4522
- } else {
4523
- if (indexedValue) {
4524
- result.push({
4525
- type: opType,
4526
- key: `${indexedValue}${INDEX_KEY_FIELD_SEPARATOR}${filepath}`,
4527
- sublevel: indexSublevel,
4528
- value: opType === "put" ? {} : void 0
4529
- });
4530
- }
4531
4590
  }
4532
4591
  }
4592
+ return value;
4593
+ } else {
4594
+ return value;
4533
4595
  }
4534
- return result;
4535
4596
  };
4536
- var makeStringEscaper = (regex, replacement) => {
4537
- return (input) => {
4538
- if (Array.isArray(input)) {
4539
- return input.map(
4540
- (val) => val.replace(regex, replacement)
4541
- );
4542
- } else {
4543
- if (typeof input === "string") {
4544
- return input.replace(regex, replacement);
4545
- } else {
4546
- return input;
4547
- }
4548
- }
4549
- };
4597
+ var cleanUpSlashes = (path7) => {
4598
+ if (path7) {
4599
+ return `/${path7.replace(/^\/+|\/+$/gm, "")}`;
4600
+ }
4601
+ return "";
4602
+ };
4603
+ var hasTinaMediaConfig = (schema) => {
4604
+ if (!schema.config?.media?.tina) return false;
4605
+ if (typeof schema.config?.media?.tina?.publicFolder !== "string" && typeof schema.config?.media?.tina?.mediaRoot !== "string")
4606
+ return false;
4607
+ return true;
4550
4608
  };
4551
- var stringEscaper = makeStringEscaper(
4552
- new RegExp(INDEX_KEY_FIELD_SEPARATOR, "gm"),
4553
- encodeURIComponent(INDEX_KEY_FIELD_SEPARATOR)
4554
- );
4555
4609
 
4556
4610
  // src/resolver/index.ts
4557
4611
  var createResolver = (args) => {
@@ -4753,24 +4807,33 @@ var transformDocumentIntoPayload = async (fullPath, rawData, tinaSchema, config,
4753
4807
  throw e;
4754
4808
  }
4755
4809
  };
4756
- var updateObjectWithJsonPath = (obj, path7, newValue) => {
4810
+ var updateObjectWithJsonPath = (obj, path7, oldValue, newValue) => {
4811
+ let updated = false;
4757
4812
  if (!path7.includes(".") && !path7.includes("[")) {
4758
- if (path7 in obj) {
4813
+ if (path7 in obj && obj[path7] === oldValue) {
4759
4814
  obj[path7] = newValue;
4815
+ updated = true;
4760
4816
  }
4761
- return obj;
4762
- }
4763
- const parentPath = path7.replace(/\.[^.]+$/, "");
4764
- const keyToUpdate = path7.match(/[^.]+$/)[0];
4765
- const parents = JSONPath2({ path: parentPath, json: obj, resultType: "value" });
4817
+ return { object: obj, updated };
4818
+ }
4819
+ const parentPath = path7.replace(/\.[^.\[\]]+$/, "");
4820
+ const keyToUpdate = path7.match(/[^.\[\]]+$/)[0];
4821
+ const parents = JSONPath2({
4822
+ path: parentPath,
4823
+ json: obj,
4824
+ resultType: "value"
4825
+ });
4766
4826
  if (parents.length > 0) {
4767
4827
  parents.forEach((parent) => {
4768
4828
  if (parent && typeof parent === "object" && keyToUpdate in parent) {
4769
- parent[keyToUpdate] = newValue;
4829
+ if (parent[keyToUpdate] === oldValue) {
4830
+ parent[keyToUpdate] = newValue;
4831
+ updated = true;
4832
+ }
4770
4833
  }
4771
4834
  });
4772
4835
  }
4773
- return obj;
4836
+ return { object: obj, updated };
4774
4837
  };
4775
4838
  var Resolver = class {
4776
4839
  constructor(init) {
@@ -4787,7 +4850,9 @@ var Resolver = class {
4787
4850
  };
4788
4851
  this.getRaw = async (fullPath) => {
4789
4852
  if (typeof fullPath !== "string") {
4790
- throw new Error(`fullPath must be of type string for getDocument request`);
4853
+ throw new Error(
4854
+ `fullPath must be of type string for getDocument request`
4855
+ );
4791
4856
  }
4792
4857
  return this.database.get(fullPath);
4793
4858
  };
@@ -4816,7 +4881,9 @@ var Resolver = class {
4816
4881
  };
4817
4882
  this.getDocument = async (fullPath, opts = {}) => {
4818
4883
  if (typeof fullPath !== "string") {
4819
- throw new Error(`fullPath must be of type string for getDocument request`);
4884
+ throw new Error(
4885
+ `fullPath must be of type string for getDocument request`
4886
+ );
4820
4887
  }
4821
4888
  const rawData = await this.getRaw(fullPath);
4822
4889
  const hasReferences = opts?.checkReferences ? await this.hasReferences(fullPath, opts.collection) : void 0;
@@ -4831,7 +4898,9 @@ var Resolver = class {
4831
4898
  };
4832
4899
  this.deleteDocument = async (fullPath) => {
4833
4900
  if (typeof fullPath !== "string") {
4834
- throw new Error(`fullPath must be of type string for getDocument request`);
4901
+ throw new Error(
4902
+ `fullPath must be of type string for getDocument request`
4903
+ );
4835
4904
  }
4836
4905
  await this.database.delete(fullPath);
4837
4906
  };
@@ -5035,7 +5104,11 @@ var Resolver = class {
5035
5104
  collection,
5036
5105
  doc?._rawData
5037
5106
  );
5038
- await this.database.put(realPath, { ...oldDoc, ...params }, collection.name);
5107
+ await this.database.put(
5108
+ realPath,
5109
+ { ...oldDoc, ...params },
5110
+ collection.name
5111
+ );
5039
5112
  return this.getDocument(realPath);
5040
5113
  };
5041
5114
  /**
@@ -5148,17 +5221,35 @@ var Resolver = class {
5148
5221
  await this.deleteDocument(realPath);
5149
5222
  if (await this.hasReferences(realPath, collection)) {
5150
5223
  const collRefs = await this.findReferences(realPath, collection);
5151
- for (const [collection2, refFields] of Object.entries(collRefs)) {
5152
- for (const [refPath, refs] of Object.entries(refFields)) {
5153
- let refDoc = await this.getRaw(refPath);
5154
- for (const ref of refs) {
5155
- refDoc = updateObjectWithJsonPath(
5224
+ for (const [collection2, docsWithRefs] of Object.entries(collRefs)) {
5225
+ for (const [pathToDocWithRef, referencePaths] of Object.entries(
5226
+ docsWithRefs
5227
+ )) {
5228
+ let refDoc = await this.getRaw(pathToDocWithRef);
5229
+ let hasUpdate = false;
5230
+ for (const path7 of referencePaths) {
5231
+ const { object: object2, updated } = updateObjectWithJsonPath(
5156
5232
  refDoc,
5157
- ref.path.join("."),
5233
+ path7,
5234
+ realPath,
5158
5235
  null
5159
5236
  );
5237
+ refDoc = object2;
5238
+ hasUpdate = updated || hasUpdate;
5239
+ }
5240
+ if (hasUpdate) {
5241
+ const collectionWithRef = this.tinaSchema.getCollectionByFullPath(pathToDocWithRef);
5242
+ if (!collectionWithRef) {
5243
+ throw new Error(
5244
+ `Unable to find collection for ${pathToDocWithRef}`
5245
+ );
5246
+ }
5247
+ await this.database.put(
5248
+ pathToDocWithRef,
5249
+ refDoc,
5250
+ collectionWithRef.name
5251
+ );
5160
5252
  }
5161
- await this.database.put(refPath, refDoc, collection2);
5162
5253
  }
5163
5254
  }
5164
5255
  }
@@ -5178,26 +5269,49 @@ var Resolver = class {
5178
5269
  collection?.path,
5179
5270
  args.params.relativePath
5180
5271
  );
5272
+ if (newRealPath === realPath) {
5273
+ return doc;
5274
+ }
5181
5275
  await this.database.put(newRealPath, doc._rawData, collection.name);
5182
5276
  await this.deleteDocument(realPath);
5183
5277
  const collRefs = await this.findReferences(realPath, collection);
5184
- for (const [collection2, refFields] of Object.entries(collRefs)) {
5185
- for (const [refPath, refs] of Object.entries(refFields)) {
5186
- let refDoc = await this.getRaw(refPath);
5187
- for (const ref of refs) {
5188
- refDoc = updateObjectWithJsonPath(
5189
- refDoc,
5190
- ref.path.join("."),
5278
+ for (const [collection2, docsWithRefs] of Object.entries(collRefs)) {
5279
+ for (const [pathToDocWithRef, referencePaths] of Object.entries(
5280
+ docsWithRefs
5281
+ )) {
5282
+ let docWithRef = await this.getRaw(pathToDocWithRef);
5283
+ let hasUpdate = false;
5284
+ for (const path7 of referencePaths) {
5285
+ const { object: object2, updated } = updateObjectWithJsonPath(
5286
+ docWithRef,
5287
+ path7,
5288
+ realPath,
5191
5289
  newRealPath
5192
5290
  );
5291
+ docWithRef = object2;
5292
+ hasUpdate = updated || hasUpdate;
5293
+ }
5294
+ if (hasUpdate) {
5295
+ const collectionWithRef = this.tinaSchema.getCollectionByFullPath(pathToDocWithRef);
5296
+ if (!collectionWithRef) {
5297
+ throw new Error(
5298
+ `Unable to find collection for ${pathToDocWithRef}`
5299
+ );
5300
+ }
5301
+ await this.database.put(
5302
+ pathToDocWithRef,
5303
+ docWithRef,
5304
+ collectionWithRef.name
5305
+ );
5193
5306
  }
5194
- await this.database.put(refPath, refDoc, collection2);
5195
5307
  }
5196
5308
  }
5197
5309
  return this.getDocument(newRealPath);
5198
5310
  }
5199
5311
  if (alreadyExists === false) {
5200
- throw new Error(`Unable to update document, ${realPath} does not exist`);
5312
+ throw new Error(
5313
+ `Unable to update document, ${realPath} does not exist`
5314
+ );
5201
5315
  }
5202
5316
  return this.updateResolveDocument({
5203
5317
  collection,
@@ -5323,35 +5437,30 @@ var Resolver = class {
5323
5437
  */
5324
5438
  this.hasReferences = async (id, c) => {
5325
5439
  let count = 0;
5326
- const deepRefs = this.tinaSchema.findReferences(c.name);
5327
- for (const [collection, refs] of Object.entries(deepRefs)) {
5328
- for (const ref of refs) {
5329
- await this.database.query(
5330
- {
5331
- collection,
5332
- filterChain: makeFilterChain({
5333
- conditions: [
5334
- {
5335
- filterPath: ref.path.join("."),
5336
- filterExpression: {
5337
- _type: "reference",
5338
- _list: false,
5339
- eq: id
5340
- }
5341
- }
5342
- ]
5343
- }),
5344
- sort: ref.field.name
5345
- },
5346
- (refId) => {
5347
- count++;
5348
- return refId;
5349
- }
5350
- );
5351
- if (count) {
5352
- return true;
5353
- }
5440
+ await this.database.query(
5441
+ {
5442
+ collection: c.name,
5443
+ filterChain: makeFilterChain({
5444
+ conditions: [
5445
+ {
5446
+ filterPath: REFS_REFERENCE_FIELD,
5447
+ filterExpression: {
5448
+ _type: "string",
5449
+ _list: false,
5450
+ eq: id
5451
+ }
5452
+ }
5453
+ ]
5454
+ }),
5455
+ sort: REFS_COLLECTIONS_SORT_KEY
5456
+ },
5457
+ (refId) => {
5458
+ count++;
5459
+ return refId;
5354
5460
  }
5461
+ );
5462
+ if (count) {
5463
+ return true;
5355
5464
  }
5356
5465
  return false;
5357
5466
  };
@@ -5359,46 +5468,41 @@ var Resolver = class {
5359
5468
  * Finds references to a document
5360
5469
  * @param id the id of the document to find references to
5361
5470
  * @param c the collection to find references in
5362
- * @returns references to the document in the form of a map of collection names to a list of fields that reference the document
5471
+ * @returns a map of references to the document
5363
5472
  */
5364
5473
  this.findReferences = async (id, c) => {
5365
5474
  const references = {};
5366
- const deepRefs = this.tinaSchema.findReferences(c.name);
5367
- for (const [collection, refs] of Object.entries(deepRefs)) {
5368
- for (const ref of refs) {
5369
- await this.database.query(
5370
- {
5371
- collection,
5372
- filterChain: makeFilterChain({
5373
- conditions: [
5374
- {
5375
- filterPath: ref.path.join("."),
5376
- filterExpression: {
5377
- _type: "reference",
5378
- _list: false,
5379
- eq: id
5380
- }
5381
- }
5382
- ]
5383
- }),
5384
- sort: ref.field.name
5385
- },
5386
- (refId) => {
5387
- if (!references[collection]) {
5388
- references[collection] = {};
5389
- }
5390
- if (!references[collection][refId]) {
5391
- references[collection][refId] = [];
5475
+ await this.database.query(
5476
+ {
5477
+ collection: c.name,
5478
+ filterChain: makeFilterChain({
5479
+ conditions: [
5480
+ {
5481
+ filterPath: REFS_REFERENCE_FIELD,
5482
+ filterExpression: {
5483
+ _type: "string",
5484
+ _list: false,
5485
+ eq: id
5486
+ }
5392
5487
  }
5393
- references[collection][refId].push({
5394
- path: ref.path,
5395
- field: ref.field
5396
- });
5397
- return refId;
5398
- }
5399
- );
5488
+ ]
5489
+ }),
5490
+ sort: REFS_COLLECTIONS_SORT_KEY
5491
+ },
5492
+ (refId, rawItem) => {
5493
+ if (!references[c.name]) {
5494
+ references[c.name] = {};
5495
+ }
5496
+ if (!references[c.name][refId]) {
5497
+ references[c.name][refId] = [];
5498
+ }
5499
+ const referencePath = rawItem?.[REFS_PATH_FIELD];
5500
+ if (referencePath) {
5501
+ references[c.name][refId].push(referencePath);
5502
+ }
5503
+ return refId;
5400
5504
  }
5401
- }
5505
+ );
5402
5506
  return references;
5403
5507
  };
5404
5508
  this.buildFieldMutations = async (fieldParams, template, existingData) => {
@@ -5468,7 +5572,7 @@ var Resolver = class {
5468
5572
  }
5469
5573
  break;
5470
5574
  case "rich-text":
5471
- accum[fieldName] = stringifyMDX(
5575
+ accum[fieldName] = serializeMDX(
5472
5576
  fieldValue,
5473
5577
  field,
5474
5578
  (fieldValue2) => resolveMediaCloudToRelative(
@@ -6142,6 +6246,7 @@ var Database = class {
6142
6246
  );
6143
6247
  const indexDefinitions = await this.getIndexDefinitions(this.contentLevel);
6144
6248
  const collectionIndexDefinitions = indexDefinitions?.[collection.name];
6249
+ const collectionReferences = (await this.getCollectionReferences())?.[collection.name];
6145
6250
  const normalizedPath = normalizePath(filepath);
6146
6251
  if (!collection?.isDetached) {
6147
6252
  if (this.bridge) {
@@ -6170,6 +6275,14 @@ var Database = class {
6170
6275
  let delOps = [];
6171
6276
  if (!isGitKeep(normalizedPath, collection)) {
6172
6277
  putOps = [
6278
+ ...makeRefOpsForDocument(
6279
+ normalizedPath,
6280
+ collection?.name,
6281
+ collectionReferences,
6282
+ dataFields,
6283
+ "put",
6284
+ level
6285
+ ),
6173
6286
  ...makeIndexOpsForDocument(
6174
6287
  normalizedPath,
6175
6288
  collection?.name,
@@ -6193,6 +6306,14 @@ var Database = class {
6193
6306
  SUBLEVEL_OPTIONS
6194
6307
  ).get(normalizedPath);
6195
6308
  delOps = existingItem ? [
6309
+ ...makeRefOpsForDocument(
6310
+ normalizedPath,
6311
+ collection?.name,
6312
+ collectionReferences,
6313
+ existingItem,
6314
+ "del",
6315
+ level
6316
+ ),
6196
6317
  ...makeIndexOpsForDocument(
6197
6318
  normalizedPath,
6198
6319
  collection?.name,
@@ -6240,6 +6361,7 @@ var Database = class {
6240
6361
  );
6241
6362
  collectionIndexDefinitions = indexDefinitions?.[collectionName];
6242
6363
  }
6364
+ const collectionReferences = (await this.getCollectionReferences())?.[collectionName];
6243
6365
  const normalizedPath = normalizePath(filepath);
6244
6366
  const dataFields = await this.formatBodyOnPayload(filepath, data);
6245
6367
  const collection = await this.collectionForPath(filepath);
@@ -6287,6 +6409,14 @@ var Database = class {
6287
6409
  let delOps = [];
6288
6410
  if (!isGitKeep(normalizedPath, collection)) {
6289
6411
  putOps = [
6412
+ ...makeRefOpsForDocument(
6413
+ normalizedPath,
6414
+ collectionName,
6415
+ collectionReferences,
6416
+ dataFields,
6417
+ "put",
6418
+ level
6419
+ ),
6290
6420
  ...makeIndexOpsForDocument(
6291
6421
  normalizedPath,
6292
6422
  collectionName,
@@ -6310,6 +6440,14 @@ var Database = class {
6310
6440
  SUBLEVEL_OPTIONS
6311
6441
  ).get(normalizedPath);
6312
6442
  delOps = existingItem ? [
6443
+ ...makeRefOpsForDocument(
6444
+ normalizedPath,
6445
+ collectionName,
6446
+ collectionReferences,
6447
+ existingItem,
6448
+ "del",
6449
+ level
6450
+ ),
6313
6451
  ...makeIndexOpsForDocument(
6314
6452
  normalizedPath,
6315
6453
  collectionName,
@@ -6472,6 +6610,22 @@ var Database = class {
6472
6610
  this.tinaSchema = await createSchema({ schema });
6473
6611
  return this.tinaSchema;
6474
6612
  };
6613
+ this.getCollectionReferences = async (level) => {
6614
+ if (this.collectionReferences) {
6615
+ return this.collectionReferences;
6616
+ }
6617
+ const result = {};
6618
+ const schema = await this.getSchema(level || this.contentLevel);
6619
+ const collections = schema.getCollections();
6620
+ for (const collection of collections) {
6621
+ const collectionReferences = this.tinaSchema.findReferencesFromCollection(
6622
+ collection.name
6623
+ );
6624
+ result[collection.name] = collectionReferences;
6625
+ }
6626
+ this.collectionReferences = result;
6627
+ return result;
6628
+ };
6475
6629
  this.getIndexDefinitions = async (level) => {
6476
6630
  if (!this.collectionIndexDefinitions) {
6477
6631
  await new Promise(async (resolve2, reject) => {
@@ -6481,11 +6635,53 @@ var Database = class {
6481
6635
  const collections = schema.getCollections();
6482
6636
  for (const collection of collections) {
6483
6637
  const indexDefinitions = {
6484
- [DEFAULT_COLLECTION_SORT_KEY]: { fields: [] }
6638
+ [DEFAULT_COLLECTION_SORT_KEY]: { fields: [] },
6485
6639
  // provide a default sort key which is the file sort
6640
+ // pseudo-index for the collection's references
6641
+ [REFS_COLLECTIONS_SORT_KEY]: {
6642
+ fields: [
6643
+ {
6644
+ name: REFS_REFERENCE_FIELD,
6645
+ type: "string",
6646
+ list: false
6647
+ },
6648
+ {
6649
+ name: REFS_PATH_FIELD,
6650
+ type: "string",
6651
+ list: false
6652
+ }
6653
+ ]
6654
+ }
6486
6655
  };
6487
- if (collection.fields) {
6488
- for (const field of collection.fields) {
6656
+ let fields = [];
6657
+ if (collection.templates) {
6658
+ const templateFieldMap = {};
6659
+ const conflictedFields = /* @__PURE__ */ new Set();
6660
+ for (const template of collection.templates) {
6661
+ for (const field of template.fields) {
6662
+ if (!templateFieldMap[field.name]) {
6663
+ templateFieldMap[field.name] = field;
6664
+ } else {
6665
+ if (templateFieldMap[field.name].type !== field.type) {
6666
+ console.warn(
6667
+ `Field ${field.name} has conflicting types in templates - skipping index`
6668
+ );
6669
+ conflictedFields.add(field.name);
6670
+ }
6671
+ }
6672
+ }
6673
+ }
6674
+ for (const conflictedField in conflictedFields) {
6675
+ delete templateFieldMap[conflictedField];
6676
+ }
6677
+ for (const field of Object.values(templateFieldMap)) {
6678
+ fields.push(field);
6679
+ }
6680
+ } else if (collection.fields) {
6681
+ fields = collection.fields;
6682
+ }
6683
+ if (fields) {
6684
+ for (const field of fields) {
6489
6685
  if (field.indexed !== void 0 && field.indexed === false || field.type === "object") {
6490
6686
  continue;
6491
6687
  }
@@ -6633,29 +6829,36 @@ var Database = class {
6633
6829
  }
6634
6830
  startKey = startKey || key || "";
6635
6831
  endKey = key || "";
6636
- edges = [...edges, { cursor: key, path: filepath }];
6832
+ edges = [...edges, { cursor: key, path: filepath, value: itemRecord }];
6637
6833
  }
6638
6834
  return {
6639
- edges: await sequential(edges, async (edge) => {
6640
- try {
6641
- const node = await hydrator(edge.path);
6642
- return {
6643
- node,
6644
- cursor: btoa(edge.cursor)
6645
- };
6646
- } catch (error) {
6647
- console.log(error);
6648
- if (error instanceof Error && (!edge.path.includes(".tina/__generated__/_graphql.json") || !edge.path.includes("tina/__generated__/_graphql.json"))) {
6649
- throw new TinaQueryError({
6650
- originalError: error,
6651
- file: edge.path,
6652
- collection: collection.name,
6653
- stack: error.stack
6654
- });
6835
+ edges: await sequential(
6836
+ edges,
6837
+ async ({
6838
+ cursor,
6839
+ path: path7,
6840
+ value
6841
+ }) => {
6842
+ try {
6843
+ const node = await hydrator(path7, value);
6844
+ return {
6845
+ node,
6846
+ cursor: btoa(cursor)
6847
+ };
6848
+ } catch (error) {
6849
+ console.log(error);
6850
+ if (error instanceof Error && (!path7.includes(".tina/__generated__/_graphql.json") || !path7.includes("tina/__generated__/_graphql.json"))) {
6851
+ throw new TinaQueryError({
6852
+ originalError: error,
6853
+ file: path7,
6854
+ collection: collection.name,
6855
+ stack: error.stack
6856
+ });
6857
+ }
6858
+ throw error;
6655
6859
  }
6656
- throw error;
6657
6860
  }
6658
- }),
6861
+ ),
6659
6862
  pageInfo: {
6660
6863
  hasPreviousPage,
6661
6864
  hasNextPage,
@@ -6779,13 +6982,14 @@ var Database = class {
6779
6982
  documentPaths,
6780
6983
  async (collection, documentPaths2) => {
6781
6984
  if (collection && !collection.isDetached) {
6782
- await _indexContent(
6783
- this,
6784
- this.contentLevel,
6785
- documentPaths2,
6985
+ await _indexContent({
6986
+ database: this,
6987
+ level: this.contentLevel,
6988
+ documentPaths: documentPaths2,
6786
6989
  enqueueOps,
6787
- collection
6788
- );
6990
+ collection,
6991
+ isPartialReindex: true
6992
+ });
6789
6993
  }
6790
6994
  }
6791
6995
  );
@@ -6801,6 +7005,7 @@ var Database = class {
6801
7005
  throw new Error(`No collection found for path: ${filepath}`);
6802
7006
  }
6803
7007
  const indexDefinitions = await this.getIndexDefinitions(this.contentLevel);
7008
+ const collectionReferences = (await this.getCollectionReferences())?.[collection.name];
6804
7009
  const collectionIndexDefinitions = indexDefinitions?.[collection.name];
6805
7010
  let level = this.contentLevel;
6806
7011
  if (collection?.isDetached) {
@@ -6819,6 +7024,14 @@ var Database = class {
6819
7024
  collection.path || ""
6820
7025
  );
6821
7026
  await this.contentLevel.batch([
7027
+ ...makeRefOpsForDocument(
7028
+ normalizedPath,
7029
+ collection.name,
7030
+ collectionReferences,
7031
+ item,
7032
+ "del",
7033
+ level
7034
+ ),
6822
7035
  ...makeIndexOpsForDocument(
6823
7036
  normalizedPath,
6824
7037
  collection.name,
@@ -6883,20 +7096,26 @@ var Database = class {
6883
7096
  );
6884
7097
  const doc = await level2.keys({ limit: 1 }).next();
6885
7098
  if (!doc) {
6886
- await _indexContent(
6887
- this,
6888
- level2,
6889
- contentPaths,
7099
+ await _indexContent({
7100
+ database: this,
7101
+ level: level2,
7102
+ documentPaths: contentPaths,
6890
7103
  enqueueOps,
6891
7104
  collection,
6892
- userFields.map((field) => [
7105
+ passwordFields: userFields.map((field) => [
6893
7106
  ...field.path,
6894
7107
  field.passwordFieldName
6895
7108
  ])
6896
- );
7109
+ });
6897
7110
  }
6898
7111
  } else {
6899
- await _indexContent(this, level, contentPaths, enqueueOps, collection);
7112
+ await _indexContent({
7113
+ database: this,
7114
+ level,
7115
+ documentPaths: contentPaths,
7116
+ enqueueOps,
7117
+ collection
7118
+ });
6900
7119
  }
6901
7120
  }
6902
7121
  );
@@ -7035,7 +7254,15 @@ var hashPasswordValues = async (data, passwordFields) => Promise.all(
7035
7254
  )
7036
7255
  );
7037
7256
  var isGitKeep = (filepath, collection) => filepath.endsWith(`.gitkeep.${collection?.format || "md"}`);
7038
- var _indexContent = async (database, level, documentPaths, enqueueOps, collection, passwordFields) => {
7257
+ var _indexContent = async ({
7258
+ database,
7259
+ level,
7260
+ documentPaths,
7261
+ enqueueOps,
7262
+ collection,
7263
+ passwordFields,
7264
+ isPartialReindex
7265
+ }) => {
7039
7266
  let collectionIndexDefinitions;
7040
7267
  let collectionPath;
7041
7268
  if (collection) {
@@ -7046,6 +7273,7 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7046
7273
  }
7047
7274
  collectionPath = collection.path;
7048
7275
  }
7276
+ const collectionReferences = (await database.getCollectionReferences())?.[collection?.name];
7049
7277
  const tinaSchema = await database.getSchema();
7050
7278
  let templateInfo = null;
7051
7279
  if (collection) {
@@ -7075,35 +7303,53 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7075
7303
  normalizedPath,
7076
7304
  collectionPath || ""
7077
7305
  );
7078
- const item = await rootSublevel.get(normalizedPath);
7079
- if (item) {
7080
- await database.contentLevel.batch([
7081
- ...makeIndexOpsForDocument(
7082
- normalizedPath,
7083
- collection.name,
7084
- collectionIndexDefinitions,
7085
- item,
7086
- "del",
7087
- level
7088
- ),
7089
- // folder indices
7090
- ...makeIndexOpsForDocument(
7091
- normalizedPath,
7092
- `${collection.name}_${folderKey}`,
7093
- collectionIndexDefinitions,
7094
- item,
7095
- "del",
7096
- level
7097
- ),
7098
- {
7099
- type: "del",
7100
- key: normalizedPath,
7101
- sublevel: rootSublevel
7102
- }
7103
- ]);
7306
+ if (isPartialReindex) {
7307
+ const item = await rootSublevel.get(normalizedPath);
7308
+ if (item) {
7309
+ await database.contentLevel.batch([
7310
+ ...makeRefOpsForDocument(
7311
+ normalizedPath,
7312
+ collection?.name,
7313
+ collectionReferences,
7314
+ item,
7315
+ "del",
7316
+ level
7317
+ ),
7318
+ ...makeIndexOpsForDocument(
7319
+ normalizedPath,
7320
+ collection.name,
7321
+ collectionIndexDefinitions,
7322
+ item,
7323
+ "del",
7324
+ level
7325
+ ),
7326
+ // folder indices
7327
+ ...makeIndexOpsForDocument(
7328
+ normalizedPath,
7329
+ `${collection.name}_${folderKey}`,
7330
+ collectionIndexDefinitions,
7331
+ item,
7332
+ "del",
7333
+ level
7334
+ ),
7335
+ {
7336
+ type: "del",
7337
+ key: normalizedPath,
7338
+ sublevel: rootSublevel
7339
+ }
7340
+ ]);
7341
+ }
7104
7342
  }
7105
7343
  if (!isGitKeep(filepath, collection)) {
7106
7344
  await enqueueOps([
7345
+ ...makeRefOpsForDocument(
7346
+ normalizedPath,
7347
+ collection?.name,
7348
+ collectionReferences,
7349
+ aliasedData,
7350
+ "put",
7351
+ level
7352
+ ),
7107
7353
  ...makeIndexOpsForDocument(
7108
7354
  normalizedPath,
7109
7355
  collection?.name,
@@ -7167,6 +7413,7 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7167
7413
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
7168
7414
  }
7169
7415
  }
7416
+ const collectionReferences = (await database.getCollectionReferences())?.[collection?.name];
7170
7417
  const tinaSchema = await database.getSchema();
7171
7418
  let templateInfo = null;
7172
7419
  if (collection) {
@@ -7190,6 +7437,14 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7190
7437
  item
7191
7438
  ) : item;
7192
7439
  await enqueueOps([
7440
+ ...makeRefOpsForDocument(
7441
+ itemKey,
7442
+ collection?.name,
7443
+ collectionReferences,
7444
+ aliasedData,
7445
+ "del",
7446
+ database.contentLevel
7447
+ ),
7193
7448
  ...makeIndexOpsForDocument(
7194
7449
  itemKey,
7195
7450
  collection.name,
@@ -7319,8 +7574,8 @@ import path6 from "path";
7319
7574
  import normalize from "normalize-path";
7320
7575
  var FilesystemBridge = class {
7321
7576
  constructor(rootPath, outputPath) {
7322
- this.rootPath = rootPath || "";
7323
- this.outputPath = outputPath || rootPath;
7577
+ this.rootPath = path6.resolve(rootPath);
7578
+ this.outputPath = outputPath ? path6.resolve(outputPath) : this.rootPath;
7324
7579
  }
7325
7580
  async glob(pattern, extension) {
7326
7581
  const basePath = path6.join(this.outputPath, ...pattern.split("/"));
@@ -7332,19 +7587,19 @@ var FilesystemBridge = class {
7332
7587
  }
7333
7588
  );
7334
7589
  const posixRootPath = normalize(this.outputPath);
7335
- return items.map((item) => {
7336
- return item.replace(posixRootPath, "").replace(/^\/|\/$/g, "");
7337
- });
7590
+ return items.map(
7591
+ (item) => item.substring(posixRootPath.length).replace(/^\/|\/$/g, "")
7592
+ );
7338
7593
  }
7339
7594
  async delete(filepath) {
7340
7595
  await fs2.remove(path6.join(this.outputPath, filepath));
7341
7596
  }
7342
7597
  async get(filepath) {
7343
- return fs2.readFileSync(path6.join(this.outputPath, filepath)).toString();
7598
+ return (await fs2.readFile(path6.join(this.outputPath, filepath))).toString();
7344
7599
  }
7345
7600
  async put(filepath, data, basePathOverride) {
7346
7601
  const basePath = basePathOverride || this.outputPath;
7347
- await fs2.outputFileSync(path6.join(basePath, filepath), data);
7602
+ await fs2.outputFile(path6.join(basePath, filepath), data);
7348
7603
  }
7349
7604
  };
7350
7605
  var AuditFileSystemBridge = class extends FilesystemBridge {