@tinacms/graphql 1.3.1 → 1.3.3

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.
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import { Database } from '../database';
5
5
  import type { ObjectTypeDefinitionNode, InlineFragmentNode, FieldDefinitionNode } from 'graphql';
6
- import type { TinaCloudCollectionEnriched, Template } from '@tinacms/schema-tools';
6
+ import type { Collection, Template } from '@tinacms/schema-tools';
7
7
  import { TinaSchema } from '@tinacms/schema-tools';
8
8
  export declare const createBuilder: ({ database, tinaSchema, }: {
9
9
  database: Database;
@@ -39,7 +39,7 @@ export declare class Builder {
39
39
  *
40
40
  * @param collections
41
41
  */
42
- buildCollectionDefinition: (collections: TinaCloudCollectionEnriched[]) => Promise<FieldDefinitionNode>;
42
+ buildCollectionDefinition: (collections: Collection<true>[]) => Promise<FieldDefinitionNode>;
43
43
  /**
44
44
  * ```graphql
45
45
  * # ex.
@@ -53,7 +53,7 @@ export declare class Builder {
53
53
  *
54
54
  * @param collections
55
55
  */
56
- buildMultiCollectionDefinition: (collections: TinaCloudCollectionEnriched[]) => Promise<FieldDefinitionNode>;
56
+ buildMultiCollectionDefinition: (collections: Collection<true>[]) => Promise<FieldDefinitionNode>;
57
57
  /**
58
58
  * ```graphql
59
59
  * # ex.
@@ -79,7 +79,7 @@ export declare class Builder {
79
79
  *
80
80
  * @param collections
81
81
  */
82
- multiCollectionDocument: (collections: TinaCloudCollectionEnriched[]) => Promise<FieldDefinitionNode>;
82
+ multiCollectionDocument: (collections: Collection<true>[]) => Promise<FieldDefinitionNode>;
83
83
  /**
84
84
  * ```graphql
85
85
  * # ex.
@@ -107,7 +107,7 @@ export declare class Builder {
107
107
  *
108
108
  * @param collections
109
109
  */
110
- buildCreateCollectionDocumentMutation: (collections: TinaCloudCollectionEnriched[]) => Promise<FieldDefinitionNode>;
110
+ buildCreateCollectionDocumentMutation: (collections: Collection<true>[]) => Promise<FieldDefinitionNode>;
111
111
  /**
112
112
  * ```graphql
113
113
  * # ex.
@@ -121,7 +121,7 @@ export declare class Builder {
121
121
  *
122
122
  * @param collections
123
123
  */
124
- buildUpdateCollectionDocumentMutation: (collections: TinaCloudCollectionEnriched[]) => Promise<FieldDefinitionNode>;
124
+ buildUpdateCollectionDocumentMutation: (collections: Collection<true>[]) => Promise<FieldDefinitionNode>;
125
125
  /**
126
126
  * ```graphql
127
127
  * # ex.
@@ -135,7 +135,7 @@ export declare class Builder {
135
135
  *
136
136
  * @param collections
137
137
  */
138
- buildDeleteCollectionDocumentMutation: (collections: TinaCloudCollectionEnriched[]) => Promise<FieldDefinitionNode>;
138
+ buildDeleteCollectionDocumentMutation: (collections: Collection<true>[]) => Promise<FieldDefinitionNode>;
139
139
  /**
140
140
  * ```graphql
141
141
  * # ex.
@@ -149,7 +149,7 @@ export declare class Builder {
149
149
  *
150
150
  * @param collection
151
151
  */
152
- collectionDocument: (collection: TinaCloudCollectionEnriched) => Promise<FieldDefinitionNode>;
152
+ collectionDocument: (collection: Collection<true>) => Promise<FieldDefinitionNode>;
153
153
  /**
154
154
  * Turns a collection into a fragment that gets updated on build. This fragment does not resolve references
155
155
  * ```graphql
@@ -164,7 +164,7 @@ export declare class Builder {
164
164
  * @public
165
165
  * @param collection a Tina Cloud collection
166
166
  */
167
- collectionFragment: (collection: TinaCloudCollectionEnriched) => Promise<import("graphql").FragmentDefinitionNode>;
167
+ collectionFragment: (collection: Collection<true>) => Promise<import("graphql").FragmentDefinitionNode>;
168
168
  /**
169
169
  * Given a collection this function returns its selections set. For example for Post this would return
170
170
  *
@@ -195,7 +195,7 @@ export declare class Builder {
195
195
  *
196
196
  * @param collection
197
197
  */
198
- updateCollectionDocumentMutation: (collection: TinaCloudCollectionEnriched) => Promise<FieldDefinitionNode>;
198
+ updateCollectionDocumentMutation: (collection: Collection<true>) => Promise<FieldDefinitionNode>;
199
199
  /**
200
200
  * ```graphql
201
201
  * # ex.
@@ -209,7 +209,7 @@ export declare class Builder {
209
209
  *
210
210
  * @param collection
211
211
  */
212
- createCollectionDocumentMutation: (collection: TinaCloudCollectionEnriched) => Promise<FieldDefinitionNode>;
212
+ createCollectionDocumentMutation: (collection: Collection<true>) => Promise<FieldDefinitionNode>;
213
213
  /**
214
214
  * ```graphql
215
215
  * # ex.
@@ -226,7 +226,7 @@ export declare class Builder {
226
226
  *
227
227
  * @param collection
228
228
  */
229
- collectionDocumentList: (collection: TinaCloudCollectionEnriched) => Promise<FieldDefinitionNode>;
229
+ collectionDocumentList: (collection: Collection<true>) => Promise<FieldDefinitionNode>;
230
230
  /**
231
231
  * GraphQL type definitions which remain unchanged regardless
232
232
  * of the supplied Tina schema. Ex. "node" interface
@@ -0,0 +1,3 @@
1
+ import { Template } from '@tinacms/schema-tools/src';
2
+ export declare const replaceNameOverrides: (template: Template, obj: any) => object;
3
+ export declare const applyNameOverrides: (template: Template, obj: any) => object;
@@ -2,7 +2,7 @@
2
2
 
3
3
  */
4
4
  import type { DocumentNode } from 'graphql';
5
- import type { TinaCloudSchemaBase, TinaSchema } from '@tinacms/schema-tools';
5
+ import type { CollectionTemplateable, TinaCloudCollection, Schema, TinaSchema } from '@tinacms/schema-tools';
6
6
  import type { Bridge } from '../database/bridge';
7
7
  import { BinaryFilter, IndexDefinition, TernaryFilter } from './datalayer';
8
8
  import { Level } from './level';
@@ -59,16 +59,33 @@ export declare class Database {
59
59
  }) => Promise<void>;
60
60
  put: (filepath: string, data: {
61
61
  [key: string]: unknown;
62
- }, collection?: string) => Promise<boolean>;
63
- stringifyFile: (filepath: string, data: {
62
+ }, collectionName?: string) => Promise<boolean>;
63
+ getTemplateDetailsForFile(collection: TinaCloudCollection<true>, data: {
64
64
  [key: string]: unknown;
65
- }) => Promise<{
66
- stringifiedFile: string;
67
- payload: {
68
- [key: string]: unknown;
65
+ }): Promise<{
66
+ template: {
67
+ label?: string | boolean;
68
+ name: string;
69
+ ui?: {
70
+ itemProps?(item: Record<string, any>): {
71
+ key?: string;
72
+ label?: string | boolean;
73
+ };
74
+ defaultItem?: import("@tinacms/schema-tools").DefaultItem<Record<string, any>>;
75
+ previewSrc?: string;
76
+ };
77
+ fields: ((import("@tinacms/schema-tools").StringField | import("@tinacms/schema-tools").NumberField | import("@tinacms/schema-tools").BooleanField | import("@tinacms/schema-tools").DateTimeField | import("@tinacms/schema-tools").ImageField | import("@tinacms/schema-tools").ReferenceField | import("@tinacms/schema-tools").RichTextField<false> | import("@tinacms/schema-tools").ObjectField<false>) & {})[];
69
78
  };
70
- keepTemplateKey: boolean;
79
+ info: CollectionTemplateable;
80
+ }>;
81
+ formatBodyOnPayload: (filepath: string, data: {
82
+ [key: string]: unknown;
83
+ }) => Promise<{
84
+ [key: string]: unknown;
71
85
  }>;
86
+ stringifyFile: (filepath: string, payload: {
87
+ [key: string]: unknown;
88
+ }, collection: TinaCloudCollection<true>) => Promise<string>;
72
89
  /**
73
90
  * Clears the internal cache of the tinaSchema and the lookup file. This allows the state to be reset
74
91
  */
@@ -77,7 +94,7 @@ export declare class Database {
77
94
  getLookup: (returnType: string) => Promise<LookupMapType>;
78
95
  getGraphQLSchema: () => Promise<DocumentNode>;
79
96
  getGraphQLSchemaFromBridge: () => Promise<DocumentNode>;
80
- getTinaSchema: (level?: Level) => Promise<TinaCloudSchemaBase>;
97
+ getTinaSchema: (level?: Level) => Promise<Schema>;
81
98
  getSchema: (level?: Level) => Promise<TinaSchema>;
82
99
  getIndexDefinitions: (level?: Level) => Promise<Record<string, Record<string, IndexDefinition>>>;
83
100
  documentExists: (fullpath: unknown) => Promise<boolean>;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
 
3
3
  */
4
- import type { TinaCloudSchema as TinaCloudSchemaBase, TinaCloudCollection as TinaCloudCollectionBase, TinaCloudTemplateBase as TinaTemplate, TinaFieldBase } from '@tinacms/schema-tools';
4
+ import type { Schema, Collection, Template as TinaTemplate } from '@tinacms/schema-tools';
5
5
  import { buildDotTinaFiles } from './build';
6
6
  export { resolve } from './resolve';
7
7
  export * from './resolver/error';
@@ -19,12 +19,8 @@ export declare const buildSchema: (rootPath: string, database: Database, flags?:
19
19
  tinaSchema: import("@tinacms/schema-tools").TinaSchema;
20
20
  }>;
21
21
  export declare const getASTSchema: (database: Database) => Promise<import("graphql").GraphQLSchema>;
22
- export declare type TinaCloudSchema = TinaCloudSchemaBase<false>;
23
- export declare type TinaSchema = TinaCloudSchema;
24
- export declare type TinaCloudCollection = TinaCloudCollectionBase<false>;
25
- export declare type TinaCollection = TinaCloudCollectionBase<false>;
26
- export declare type TinaField = TinaFieldBase;
27
- export type { TinaTemplate };
22
+ export declare type TinaSchema = Schema;
23
+ export type { TinaTemplate, Schema, Collection };
28
24
  export { FilesystemBridge, AuditFileSystemBridge, } from './database/bridge/filesystem';
29
25
  export { IsomorphicBridge } from './database/bridge/isomorphic';
30
26
  export type { Bridge } from './database/bridge';
package/dist/index.es.js CHANGED
@@ -1515,7 +1515,7 @@ var Builder = class {
1515
1515
  };
1516
1516
  this._getCollectionFragmentSelections = async (collection, depth) => {
1517
1517
  const selections = [];
1518
- if (typeof collection.fields === "object") {
1518
+ if (collection.fields?.length > 0) {
1519
1519
  await sequential(collection.fields, async (x) => {
1520
1520
  const field = await this._buildFieldNodeForFragments(x, depth);
1521
1521
  selections.push(field);
@@ -1539,7 +1539,7 @@ var Builder = class {
1539
1539
  case "rich-text":
1540
1540
  return astBuilder.FieldNodeDefinition(field);
1541
1541
  case "object":
1542
- if (typeof field.fields === "object") {
1542
+ if (field.fields?.length > 0) {
1543
1543
  const selections2 = [];
1544
1544
  await sequential(field.fields, async (item) => {
1545
1545
  const field2 = await this._buildFieldNodeForFragments(item, depth);
@@ -1552,7 +1552,7 @@ var Builder = class {
1552
1552
  ...filterSelections(selections2)
1553
1553
  ]
1554
1554
  });
1555
- } else if (typeof field.templates === "object") {
1555
+ } else if (field.templates?.length > 0) {
1556
1556
  const selections2 = [];
1557
1557
  await sequential(field.templates, async (tem) => {
1558
1558
  if (typeof tem === "object") {
@@ -2387,9 +2387,6 @@ var validateCollection = async (collection) => {
2387
2387
  const validCollection = await collectionSchema.cast(collection);
2388
2388
  if (validCollection.templates) {
2389
2389
  templates = await sequential(validCollection.templates, async (template) => {
2390
- if (typeof template === "string") {
2391
- throw new Error(`Global templates are not yet supported`);
2392
- }
2393
2390
  const fields2 = await sequential(template.fields, async (field) => {
2394
2391
  return validateField(field);
2395
2392
  });
@@ -2422,12 +2419,13 @@ var validateField = async (field) => {
2422
2419
  type: string().oneOf(FIELD_TYPES, (obj) => `'type' must be one of: ${obj.values}, but got '${obj.value}' at ${messageName}`)
2423
2420
  });
2424
2421
  await schema.validate(field);
2425
- return field;
2422
+ const validField = await schema.cast(field);
2423
+ return validField;
2426
2424
  };
2427
2425
 
2428
2426
  // package.json
2429
2427
  var name = "@tinacms/graphql";
2430
- var version = "1.3.1";
2428
+ var version = "1.3.3";
2431
2429
  var main = "dist/index.js";
2432
2430
  var module = "dist/index.es.js";
2433
2431
  var typings = "dist/index.d.ts";
@@ -2793,16 +2791,7 @@ var resolveReferences = async (filter, fields, resolver) => {
2793
2791
  }
2794
2792
  } else if (fieldDefinition.type === "object") {
2795
2793
  if (fieldDefinition.templates) {
2796
- const globalTemplates = {};
2797
- for (const template of fieldDefinition.templates) {
2798
- if (typeof template === "string") {
2799
- globalTemplates[template] = 1;
2800
- }
2801
- }
2802
2794
  for (const templateName of Object.keys(filter[fieldKey])) {
2803
- if (templateName in globalTemplates) {
2804
- throw new Error("Global templates not yet supported for queries");
2805
- }
2806
2795
  const template = fieldDefinition.templates.find((template2) => !(typeof template2 === "string") && template2.name === templateName);
2807
2796
  if (template) {
2808
2797
  await resolveReferences(filter[fieldKey][templateName], template.fields, resolver);
@@ -2830,16 +2819,7 @@ var collectConditionsForChildFields = (filterNode, fields, pathExpression, colle
2830
2819
  };
2831
2820
  var collectConditionsForObjectField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
2832
2821
  if (field.list && field.templates) {
2833
- const globalTemplates = {};
2834
- for (const template of field.templates) {
2835
- if (typeof template === "string") {
2836
- globalTemplates[template] = 1;
2837
- }
2838
- }
2839
2822
  for (const [filterKey, childFilterNode] of Object.entries(filterNode)) {
2840
- if (filterKey in globalTemplates) {
2841
- throw new Error("Global templates not yet supported for queries");
2842
- }
2843
2823
  const template = field.templates.find((template2) => !(typeof template2 === "string") && template2.name === filterKey);
2844
2824
  const jsonPath = `${fieldName}[?(@._template=="${filterKey}")]`;
2845
2825
  const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : jsonPath;
@@ -3430,7 +3410,7 @@ var Resolver = class {
3430
3410
  };
3431
3411
  this.buildObjectMutations = (fieldValue, field) => {
3432
3412
  if (field.fields) {
3433
- const objectTemplate = typeof field.fields === "string" ? this.tinaSchema.getGlobalTemplate(field.fields) : field;
3413
+ const objectTemplate = field;
3434
3414
  if (Array.isArray(fieldValue)) {
3435
3415
  return fieldValue.map((item) => this.buildFieldMutations(item, objectTemplate));
3436
3416
  } else {
@@ -3444,9 +3424,6 @@ var Resolver = class {
3444
3424
  throw new Error(`Expected object for template value for field ${field.name}`);
3445
3425
  }
3446
3426
  const templates = field.templates.map((templateOrTemplateName) => {
3447
- if (typeof templateOrTemplateName === "string") {
3448
- return this.tinaSchema.getGlobalTemplate(templateOrTemplateName);
3449
- }
3450
3427
  return templateOrTemplateName;
3451
3428
  });
3452
3429
  const [templateName] = Object.entries(item)[0];
@@ -3464,9 +3441,6 @@ var Resolver = class {
3464
3441
  throw new Error(`Expected object for template value for field ${field.name}`);
3465
3442
  }
3466
3443
  const templates = field.templates.map((templateOrTemplateName) => {
3467
- if (typeof templateOrTemplateName === "string") {
3468
- return this.tinaSchema.getGlobalTemplate(templateOrTemplateName);
3469
- }
3470
3444
  return templateOrTemplateName;
3471
3445
  });
3472
3446
  const [templateName] = Object.entries(fieldValue)[0];
@@ -4176,6 +4150,62 @@ var parseFile = (content, format, yupSchema, markdownParseConfig) => {
4176
4150
  };
4177
4151
  var normalizePath = (filepath) => filepath.replace(/\\/g, "/");
4178
4152
 
4153
+ // src/database/alias-utils.ts
4154
+ var replaceNameOverrides = (template, obj) => {
4155
+ if (template.list) {
4156
+ return obj.map((item) => {
4157
+ return _replaceNameOverrides(getTemplateForData(template, item).fields, item);
4158
+ });
4159
+ } else {
4160
+ return _replaceNameOverrides(getTemplateForData(template, obj).fields, obj);
4161
+ }
4162
+ };
4163
+ var _replaceNameOverrides = (fields, obj) => {
4164
+ const output = {};
4165
+ Object.keys(obj).forEach((key) => {
4166
+ const field = fields.find((fieldWithMatchingAlias) => (fieldWithMatchingAlias?.nameOverride || fieldWithMatchingAlias?.name) === key);
4167
+ output[field?.name || key] = field?.type == "object" ? replaceNameOverrides(field, obj[key]) : obj[key];
4168
+ });
4169
+ return output;
4170
+ };
4171
+ var getTemplateKey = (field) => {
4172
+ const DEFAULT_TEMPLATE_KEY = "_template";
4173
+ if (field.templates?.length) {
4174
+ const templateField = field.templates[0]?.fields?.find((field2) => field2.name === DEFAULT_TEMPLATE_KEY);
4175
+ return templateField?.alias || DEFAULT_TEMPLATE_KEY;
4176
+ }
4177
+ return DEFAULT_TEMPLATE_KEY;
4178
+ };
4179
+ var getTemplateForData = (field, data) => {
4180
+ if (field.templates?.length) {
4181
+ const templateKey = getTemplateKey(field);
4182
+ if (data[templateKey]) {
4183
+ return field.templates.find((template) => template.name === data[templateKey]);
4184
+ }
4185
+ } else {
4186
+ return field;
4187
+ }
4188
+ throw new Error("No template found for field " + field.name);
4189
+ };
4190
+ var applyNameOverrides = (template, obj) => {
4191
+ if (template.list) {
4192
+ return obj.map((item) => {
4193
+ return _applyNameOverrides(getTemplateForData(template, item).fields, item);
4194
+ });
4195
+ } else {
4196
+ return _applyNameOverrides(getTemplateForData(template, obj).fields, obj);
4197
+ }
4198
+ };
4199
+ var _applyNameOverrides = (fields, obj) => {
4200
+ const output = {};
4201
+ Object.keys(obj).forEach((key) => {
4202
+ const field = fields.find((field2) => field2.name === key);
4203
+ const outputKey = field?.nameOverride || key;
4204
+ output[outputKey] = field?.type === "object" ? applyNameOverrides(field, obj[key]) : obj[key];
4205
+ });
4206
+ return output;
4207
+ };
4208
+
4179
4209
  // src/database/index.ts
4180
4210
  var createDatabase = (config) => {
4181
4211
  return new Database({
@@ -4237,8 +4267,9 @@ var Database = class {
4237
4267
  };
4238
4268
  this.addPendingDocument = async (filepath, data) => {
4239
4269
  await this.initLevel();
4240
- const { stringifiedFile, payload } = await this.stringifyFile(filepath, data);
4270
+ const dataFields = await this.formatBodyOnPayload(filepath, data);
4241
4271
  const collection = await this.collectionForPath(filepath);
4272
+ const stringifiedFile = await this.stringifyFile(filepath, dataFields, collection);
4242
4273
  let collectionIndexDefinitions;
4243
4274
  if (collection) {
4244
4275
  const indexDefinitions = await this.getIndexDefinitions(this.level);
@@ -4249,7 +4280,7 @@ var Database = class {
4249
4280
  await this.bridge.put(normalizedPath, stringifiedFile);
4250
4281
  }
4251
4282
  await this.onPut(normalizedPath, stringifiedFile);
4252
- const putOps = makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, payload, "put", this.level);
4283
+ const putOps = makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, dataFields, "put", this.level);
4253
4284
  const existingItem = await this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(normalizedPath);
4254
4285
  const delOps = existingItem ? makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, existingItem, "del", this.level) : [];
4255
4286
  const ops = [
@@ -4258,39 +4289,41 @@ var Database = class {
4258
4289
  {
4259
4290
  type: "put",
4260
4291
  key: normalizedPath,
4261
- value: payload,
4292
+ value: dataFields,
4262
4293
  sublevel: this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS)
4263
4294
  }
4264
4295
  ];
4265
4296
  await this.level.batch(ops);
4266
4297
  };
4267
- this.put = async (filepath, data, collection) => {
4298
+ this.put = async (filepath, data, collectionName) => {
4268
4299
  await this.initLevel();
4269
4300
  try {
4270
4301
  if (SYSTEM_FILES.includes(filepath)) {
4271
4302
  throw new Error(`Unexpected put for config file ${filepath}`);
4272
4303
  } else {
4273
4304
  let collectionIndexDefinitions;
4274
- if (collection) {
4305
+ if (collectionName) {
4275
4306
  const indexDefinitions = await this.getIndexDefinitions(this.level);
4276
- collectionIndexDefinitions = indexDefinitions?.[collection];
4307
+ collectionIndexDefinitions = indexDefinitions?.[collectionName];
4277
4308
  }
4278
4309
  const normalizedPath = normalizePath(filepath);
4279
- const { stringifiedFile, payload } = await this.stringifyFile(filepath, data);
4310
+ const dataFields = await this.formatBodyOnPayload(filepath, data);
4311
+ const collection = await this.collectionForPath(filepath);
4312
+ const stringifiedFile = await this.stringifyFile(filepath, dataFields, collection);
4280
4313
  if (this.bridge) {
4281
4314
  await this.bridge.put(normalizedPath, stringifiedFile);
4282
4315
  }
4283
4316
  await this.onPut(normalizedPath, stringifiedFile);
4284
- const putOps = makeIndexOpsForDocument(normalizedPath, collection, collectionIndexDefinitions, payload, "put", this.level);
4317
+ const putOps = makeIndexOpsForDocument(normalizedPath, collectionName, collectionIndexDefinitions, dataFields, "put", this.level);
4285
4318
  const existingItem = await this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(normalizedPath);
4286
- const delOps = existingItem ? makeIndexOpsForDocument(normalizedPath, collection, collectionIndexDefinitions, existingItem, "del", this.level) : [];
4319
+ const delOps = existingItem ? makeIndexOpsForDocument(normalizedPath, collectionName, collectionIndexDefinitions, existingItem, "del", this.level) : [];
4287
4320
  const ops = [
4288
4321
  ...delOps,
4289
4322
  ...putOps,
4290
4323
  {
4291
4324
  type: "put",
4292
4325
  key: normalizedPath,
4293
- value: payload,
4326
+ value: dataFields,
4294
4327
  sublevel: this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS)
4295
4328
  }
4296
4329
  ];
@@ -4301,66 +4334,52 @@ var Database = class {
4301
4334
  throw new TinaFetchError(`Error in PUT for ${filepath}`, {
4302
4335
  originalError: error,
4303
4336
  file: filepath,
4304
- collection,
4337
+ collection: collectionName,
4305
4338
  stack: error.stack
4306
4339
  });
4307
4340
  }
4308
4341
  };
4309
- this.stringifyFile = async (filepath, data) => {
4310
- if (SYSTEM_FILES.includes(filepath)) {
4311
- throw new Error(`Unexpected put for config file ${filepath}`);
4312
- } else {
4313
- const tinaSchema = await this.getSchema(this.level);
4314
- const collection = tinaSchema.getCollectionByFullPath(filepath);
4315
- const templateInfo = await tinaSchema.getTemplatesForCollectable(collection);
4316
- let template;
4317
- if (templateInfo.type === "object") {
4318
- template = templateInfo.template;
4319
- }
4320
- if (templateInfo.type === "union") {
4321
- if (hasOwnProperty(data, "_template")) {
4322
- template = templateInfo.templates.find((t) => lastItem(t.namespace) === data._template);
4323
- } else {
4324
- throw new Error(`Expected _template to be provided for document in an ambiguous collection`);
4342
+ this.formatBodyOnPayload = async (filepath, data) => {
4343
+ const tinaSchema = await this.getSchema(this.level);
4344
+ const collection = tinaSchema.getCollectionByFullPath(filepath);
4345
+ const { template } = await this.getTemplateDetailsForFile(collection, data);
4346
+ const bodyField = template.fields.find((field) => {
4347
+ if (field.type === "string" || field.type === "rich-text") {
4348
+ if (field.isBody) {
4349
+ return true;
4325
4350
  }
4326
4351
  }
4327
- if (!template) {
4328
- throw new Error(`Unable to determine template`);
4329
- }
4330
- const field = template.fields.find((field2) => {
4331
- if (field2.type === "string" || field2.type === "rich-text") {
4332
- if (field2.isBody) {
4333
- return true;
4334
- }
4352
+ return false;
4353
+ });
4354
+ let payload = {};
4355
+ if (["md", "mdx"].includes(collection.format) && bodyField) {
4356
+ Object.entries(data).forEach(([key, value]) => {
4357
+ if (key !== bodyField.name) {
4358
+ payload[key] = value;
4335
4359
  }
4336
- return false;
4337
4360
  });
4338
- let payload = {};
4339
- if (["md", "mdx"].includes(collection.format) && field) {
4340
- Object.entries(data).forEach(([key, value]) => {
4341
- if (key !== field.name) {
4342
- payload[key] = value;
4343
- }
4344
- });
4345
- payload["$_body"] = data[field.name];
4346
- } else {
4347
- payload = data;
4348
- }
4349
- const extension = path3.extname(filepath);
4350
- const stringifiedFile = stringifyFile(payload, extension, templateInfo.type === "union", {
4351
- frontmatterFormat: collection?.frontmatterFormat,
4352
- frontmatterDelimiters: collection?.frontmatterDelimiters
4353
- });
4354
- return {
4355
- stringifiedFile,
4356
- payload,
4357
- keepTemplateKey: templateInfo.type === "union"
4358
- };
4361
+ payload["$_body"] = data[bodyField.name];
4362
+ } else {
4363
+ payload = data;
4359
4364
  }
4365
+ return payload;
4366
+ };
4367
+ this.stringifyFile = async (filepath, payload, collection) => {
4368
+ const templateDetails = await this.getTemplateDetailsForFile(collection, payload);
4369
+ const writeTemplateKey = templateDetails.info.type === "union";
4370
+ const aliasedData = applyNameOverrides(templateDetails.template, payload);
4371
+ const extension = path3.extname(filepath);
4372
+ const stringifiedFile = stringifyFile(aliasedData, extension, writeTemplateKey, {
4373
+ frontmatterFormat: collection?.frontmatterFormat,
4374
+ frontmatterDelimiters: collection?.frontmatterDelimiters
4375
+ });
4376
+ return stringifiedFile;
4360
4377
  };
4361
4378
  this.flush = async (filepath) => {
4362
4379
  const data = await this.get(filepath);
4363
- const { stringifiedFile } = await this.stringifyFile(filepath, data);
4380
+ const dataFields = await this.formatBodyOnPayload(filepath, data);
4381
+ const collection = await this.collectionForPath(filepath);
4382
+ const stringifiedFile = await this.stringifyFile(filepath, dataFields, collection);
4364
4383
  return stringifiedFile;
4365
4384
  };
4366
4385
  this.getLookup = async (returnType) => {
@@ -4751,6 +4770,28 @@ var Database = class {
4751
4770
  throw new GraphQLError4("Error initializing LevelDB instance");
4752
4771
  }
4753
4772
  }
4773
+ async getTemplateDetailsForFile(collection, data) {
4774
+ const tinaSchema = await this.getSchema();
4775
+ const templateInfo = await tinaSchema.getTemplatesForCollectable(collection);
4776
+ let template;
4777
+ if (templateInfo.type === "object") {
4778
+ template = templateInfo.template;
4779
+ }
4780
+ if (templateInfo.type === "union") {
4781
+ if (hasOwnProperty(data, "_template")) {
4782
+ template = templateInfo.templates.find((t) => lastItem(t.namespace) === data._template);
4783
+ } else {
4784
+ throw new Error(`Expected _template to be provided for document in an ambiguous collection`);
4785
+ }
4786
+ }
4787
+ if (!template) {
4788
+ throw new Error(`Unable to determine template`);
4789
+ }
4790
+ return {
4791
+ template,
4792
+ info: templateInfo
4793
+ };
4794
+ }
4754
4795
  clearCache() {
4755
4796
  this.tinaSchema = null;
4756
4797
  this._lookup = null;
@@ -4778,6 +4819,11 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
4778
4819
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
4779
4820
  }
4780
4821
  }
4822
+ const tinaSchema = await database.getSchema();
4823
+ let templateInfo = null;
4824
+ if (collection) {
4825
+ templateInfo = await tinaSchema.getTemplatesForCollectable(collection);
4826
+ }
4781
4827
  await sequential(documentPaths, async (filepath) => {
4782
4828
  try {
4783
4829
  const dataString = await database.bridge.get(normalizePath(filepath));
@@ -4786,12 +4832,13 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
4786
4832
  frontmatterFormat: collection?.frontmatterFormat
4787
4833
  });
4788
4834
  const normalizedPath = normalizePath(filepath);
4835
+ const aliasedData = templateInfo ? replaceNameOverrides(getTemplateForFile(templateInfo, data), data) : data;
4789
4836
  await enqueueOps([
4790
- ...makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, data, "put", level),
4837
+ ...makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, aliasedData, "put", level),
4791
4838
  {
4792
4839
  type: "put",
4793
4840
  key: normalizedPath,
4794
- value: data,
4841
+ value: aliasedData,
4795
4842
  sublevel: level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS)
4796
4843
  }
4797
4844
  ]);
@@ -4826,6 +4873,19 @@ var _deleteIndexContent = async (database, documentPaths, enequeueOps, collectio
4826
4873
  }
4827
4874
  });
4828
4875
  };
4876
+ var getTemplateForFile = (templateInfo, data) => {
4877
+ if (templateInfo.type === "object") {
4878
+ return templateInfo.template;
4879
+ }
4880
+ if (templateInfo.type === "union") {
4881
+ if (hasOwnProperty(data, "_template")) {
4882
+ return templateInfo.templates.find((t) => lastItem(t.namespace) === data._template);
4883
+ } else {
4884
+ throw new Error(`Expected _template to be provided for document in an ambiguous collection`);
4885
+ }
4886
+ }
4887
+ throw new Error(`Unable to determine template`);
4888
+ };
4829
4889
 
4830
4890
  // src/level/tinaLevel.ts
4831
4891
  import { ManyLevelGuest } from "many-level";