prismic-ts-codegen 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +5 -5
  2. package/bin/prismic-ts-codegen.mjs +3 -0
  3. package/dist/cli/configSchema.cjs +38 -0
  4. package/dist/cli/configSchema.cjs.map +1 -0
  5. package/dist/cli/configSchema.d.ts +3 -0
  6. package/dist/cli/configSchema.js +38 -0
  7. package/dist/cli/configSchema.js.map +1 -0
  8. package/dist/cli/constants.cjs +5 -0
  9. package/dist/cli/constants.cjs.map +1 -0
  10. package/dist/cli/constants.d.ts +1 -0
  11. package/dist/cli/constants.js +5 -0
  12. package/dist/cli/constants.js.map +1 -0
  13. package/dist/cli/index.d.ts +1 -0
  14. package/dist/cli/loadConfig.cjs +32 -0
  15. package/dist/cli/loadConfig.cjs.map +1 -0
  16. package/dist/cli/loadConfig.d.ts +6 -0
  17. package/dist/cli/loadConfig.js +32 -0
  18. package/dist/cli/loadConfig.js.map +1 -0
  19. package/dist/cli/loadLocaleIDs.cjs +37 -0
  20. package/dist/cli/loadLocaleIDs.cjs.map +1 -0
  21. package/dist/cli/loadLocaleIDs.d.ts +10 -0
  22. package/dist/cli/loadLocaleIDs.js +20 -0
  23. package/dist/cli/loadLocaleIDs.js.map +1 -0
  24. package/dist/cli/loadModels.cjs +79 -0
  25. package/dist/cli/loadModels.cjs.map +1 -0
  26. package/dist/cli/loadModels.d.ts +15 -0
  27. package/dist/cli/loadModels.js +62 -0
  28. package/dist/cli/loadModels.js.map +1 -0
  29. package/dist/cli/types.d.ts +175 -0
  30. package/dist/cli.cjs +119 -0
  31. package/dist/cli.cjs.map +1 -0
  32. package/dist/cli.js +118 -0
  33. package/dist/cli.js.map +1 -0
  34. package/dist/constants.cjs +29 -0
  35. package/dist/constants.cjs.map +1 -0
  36. package/dist/constants.d.ts +5 -0
  37. package/dist/constants.js +29 -0
  38. package/dist/constants.js.map +1 -0
  39. package/dist/detectTypesProvider.cjs +16 -0
  40. package/dist/detectTypesProvider.cjs.map +1 -0
  41. package/dist/detectTypesProvider.d.ts +13 -0
  42. package/dist/detectTypesProvider.js +16 -0
  43. package/dist/detectTypesProvider.js.map +1 -0
  44. package/dist/generateTypes.cjs +109 -0
  45. package/dist/generateTypes.cjs.map +1 -0
  46. package/dist/generateTypes.d.ts +15 -0
  47. package/dist/generateTypes.js +109 -0
  48. package/dist/generateTypes.js.map +1 -0
  49. package/dist/index.cjs +6 -1086
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.ts +5 -192
  52. package/dist/index.js +5 -1081
  53. package/dist/index.js.map +1 -1
  54. package/dist/lib/addInterfacePropertiesForFields.cjs +490 -0
  55. package/dist/lib/addInterfacePropertiesForFields.cjs.map +1 -0
  56. package/dist/lib/addInterfacePropertiesForFields.d.ts +21 -0
  57. package/dist/lib/addInterfacePropertiesForFields.js +490 -0
  58. package/dist/lib/addInterfacePropertiesForFields.js.map +1 -0
  59. package/dist/lib/addTypeAliasForCustomType.cjs +81 -0
  60. package/dist/lib/addTypeAliasForCustomType.cjs.map +1 -0
  61. package/dist/lib/addTypeAliasForCustomType.d.ts +11 -0
  62. package/dist/lib/addTypeAliasForCustomType.js +81 -0
  63. package/dist/lib/addTypeAliasForCustomType.js.map +1 -0
  64. package/dist/lib/addTypeAliasForSharedSlice.cjs +149 -0
  65. package/dist/lib/addTypeAliasForSharedSlice.cjs.map +1 -0
  66. package/dist/lib/addTypeAliasForSharedSlice.d.ts +10 -0
  67. package/dist/lib/addTypeAliasForSharedSlice.js +149 -0
  68. package/dist/lib/addTypeAliasForSharedSlice.js.map +1 -0
  69. package/dist/lib/buildFieldDocs.cjs +43 -0
  70. package/dist/lib/buildFieldDocs.cjs.map +1 -0
  71. package/dist/lib/buildFieldDocs.d.ts +14 -0
  72. package/dist/lib/buildFieldDocs.js +43 -0
  73. package/dist/lib/buildFieldDocs.js.map +1 -0
  74. package/dist/lib/buildSharedSliceInterfaceNamePart.cjs +8 -0
  75. package/dist/lib/buildSharedSliceInterfaceNamePart.cjs.map +1 -0
  76. package/dist/lib/buildSharedSliceInterfaceNamePart.d.ts +5 -0
  77. package/dist/lib/buildSharedSliceInterfaceNamePart.js +8 -0
  78. package/dist/lib/buildSharedSliceInterfaceNamePart.js.map +1 -0
  79. package/dist/lib/buildTypeName.cjs +12 -0
  80. package/dist/lib/buildTypeName.cjs.map +1 -0
  81. package/dist/lib/buildTypeName.d.ts +1 -0
  82. package/dist/lib/buildTypeName.js +12 -0
  83. package/dist/lib/buildTypeName.js.map +1 -0
  84. package/dist/lib/getAPIIDPath.cjs +23 -0
  85. package/dist/lib/getAPIIDPath.cjs.map +1 -0
  86. package/dist/lib/getAPIIDPath.d.ts +10 -0
  87. package/dist/lib/getAPIIDPath.js +23 -0
  88. package/dist/lib/getAPIIDPath.js.map +1 -0
  89. package/dist/lib/getFieldDocumentationURL.cjs +8 -0
  90. package/dist/lib/getFieldDocumentationURL.cjs.map +1 -0
  91. package/dist/lib/getFieldDocumentationURL.d.ts +6 -0
  92. package/dist/lib/getFieldDocumentationURL.js +8 -0
  93. package/dist/lib/getFieldDocumentationURL.js.map +1 -0
  94. package/dist/lib/getHumanReadableFieldPath.cjs +19 -0
  95. package/dist/lib/getHumanReadableFieldPath.cjs.map +1 -0
  96. package/dist/lib/getHumanReadableFieldPath.d.ts +10 -0
  97. package/dist/lib/getHumanReadableFieldPath.js +19 -0
  98. package/dist/lib/getHumanReadableFieldPath.js.map +1 -0
  99. package/dist/lib/getHumanReadableFieldType.cjs +37 -0
  100. package/dist/lib/getHumanReadableFieldType.cjs.map +1 -0
  101. package/dist/lib/getHumanReadableFieldType.d.ts +6 -0
  102. package/dist/lib/getHumanReadableFieldType.js +37 -0
  103. package/dist/lib/getHumanReadableFieldType.js.map +1 -0
  104. package/dist/lib/getHumanReadableModelName.cjs +24 -0
  105. package/dist/lib/getHumanReadableModelName.cjs.map +1 -0
  106. package/dist/lib/getHumanReadableModelName.d.ts +7 -0
  107. package/dist/lib/getHumanReadableModelName.js +24 -0
  108. package/dist/lib/getHumanReadableModelName.js.map +1 -0
  109. package/dist/lib/getSourceFileText.cjs +9 -0
  110. package/dist/lib/getSourceFileText.cjs.map +1 -0
  111. package/dist/lib/getSourceFileText.d.ts +2 -0
  112. package/dist/lib/getSourceFileText.js +9 -0
  113. package/dist/lib/getSourceFileText.js.map +1 -0
  114. package/dist/lib/hasOwnProperty.cjs +7 -0
  115. package/dist/lib/hasOwnProperty.cjs.map +1 -0
  116. package/dist/lib/hasOwnProperty.d.ts +10 -0
  117. package/dist/lib/hasOwnProperty.js +7 -0
  118. package/dist/lib/hasOwnProperty.js.map +1 -0
  119. package/dist/lib/isCustomTypeModel.cjs +7 -0
  120. package/dist/lib/isCustomTypeModel.cjs.map +1 -0
  121. package/dist/lib/isCustomTypeModel.d.ts +2 -0
  122. package/dist/lib/isCustomTypeModel.js +7 -0
  123. package/dist/lib/isCustomTypeModel.js.map +1 -0
  124. package/dist/lib/isCustomTypeModelField.cjs +7 -0
  125. package/dist/lib/isCustomTypeModelField.cjs.map +1 -0
  126. package/dist/lib/isCustomTypeModelField.d.ts +2 -0
  127. package/dist/lib/isCustomTypeModelField.js +7 -0
  128. package/dist/lib/isCustomTypeModelField.js.map +1 -0
  129. package/dist/lib/isCustomTypeModelSlice.cjs +9 -0
  130. package/dist/lib/isCustomTypeModelSlice.cjs.map +1 -0
  131. package/dist/lib/isCustomTypeModelSlice.d.ts +2 -0
  132. package/dist/lib/isCustomTypeModelSlice.js +9 -0
  133. package/dist/lib/isCustomTypeModelSlice.js.map +1 -0
  134. package/dist/lib/isSharedSliceModel.cjs +9 -0
  135. package/dist/lib/isSharedSliceModel.cjs.map +1 -0
  136. package/dist/lib/isSharedSliceModel.d.ts +2 -0
  137. package/dist/lib/isSharedSliceModel.js +9 -0
  138. package/dist/lib/isSharedSliceModel.js.map +1 -0
  139. package/dist/lib/pascalCase.cjs +8 -0
  140. package/dist/lib/pascalCase.cjs.map +1 -0
  141. package/dist/lib/pascalCase.d.ts +1 -0
  142. package/dist/lib/pascalCase.js +8 -0
  143. package/dist/lib/pascalCase.js.map +1 -0
  144. package/dist/lib/writeFieldDocsDescription.cjs +29 -0
  145. package/dist/lib/writeFieldDocsDescription.cjs.map +1 -0
  146. package/dist/lib/writeFieldDocsDescription.d.ts +13 -0
  147. package/dist/lib/writeFieldDocsDescription.js +29 -0
  148. package/dist/lib/writeFieldDocsDescription.js.map +1 -0
  149. package/dist/types.d.ts +14 -0
  150. package/package.json +45 -36
  151. package/src/cli/configSchema.ts +2 -0
  152. package/src/cli/index.ts +9 -5
  153. package/src/cli/loadConfig.ts +4 -2
  154. package/src/cli/loadModels.ts +3 -3
  155. package/src/cli/types.ts +10 -0
  156. package/src/constants.ts +6 -3
  157. package/src/detectTypesProvider.ts +32 -0
  158. package/src/generateTypes.ts +11 -6
  159. package/src/index.ts +4 -1
  160. package/src/lib/addInterfacePropertiesForFields.ts +31 -28
  161. package/src/lib/addTypeAliasForCustomType.ts +7 -5
  162. package/src/lib/addTypeAliasForSharedSlice.ts +5 -4
  163. package/src/lib/buildFieldDocs.ts +2 -1
  164. package/src/lib/getAPIIDPath.ts +3 -2
  165. package/src/lib/getFieldDocumentationURL.ts +1 -1
  166. package/src/lib/getHumanReadableFieldPath.ts +2 -1
  167. package/src/lib/getHumanReadableFieldType.ts +2 -2
  168. package/src/lib/getHumanReadableModelName.ts +1 -1
  169. package/src/lib/getSourceFileText.ts +1 -1
  170. package/src/lib/isCustomTypeModel.ts +1 -1
  171. package/src/lib/isCustomTypeModelField.ts +1 -1
  172. package/src/lib/isCustomTypeModelSlice.ts +1 -1
  173. package/src/lib/isSharedSliceModel.ts +1 -1
  174. package/src/types.ts +1 -1
  175. package/bin/cli.mjs +0 -1342
package/bin/cli.mjs DELETED
@@ -1,1342 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { readFileSync, existsSync, writeFileSync } from 'fs';
4
- import { resolve } from 'path';
5
- import meow from 'meow';
6
- import { stripIndent } from 'common-tags';
7
- import { Project, ModuleDeclarationKind } from 'ts-morph';
8
- import { CustomTypeModelSliceType, CustomTypeModelFieldType, CustomTypeModelLinkSelectType } from '@prismicio/types';
9
- import { pascalCase as pascalCase$1, pascalCaseTransformMerge } from 'pascal-case';
10
- import Joi from 'joi';
11
- import * as prismic from '@prismicio/client';
12
- import fetch from 'node-fetch';
13
- import fg from 'fast-glob';
14
- import * as prismicCT from '@prismicio/custom-types-client';
15
- import _jiti from 'jiti';
16
-
17
- const BLANK_LINE_IDENTIFIER = "// ___BLANK_LINE_TO_BE_REPLACED___";
18
- const CUSTOM_TYPES_DOCUMENTATION_URL = "https://prismic.io/docs/core-concepts/custom-types";
19
- const SHARED_SLICES_DOCUMENTATION_URL = "https://prismic.io/docs/core-concepts/reusing-slices";
20
- const FIELD_DOCUMENTATION_URLS = {
21
- UID: "https://prismic.io/docs/core-concepts/uid",
22
- Boolean: "https://prismic.io/docs/core-concepts/boolean",
23
- Color: "https://prismic.io/docs/core-concepts/color",
24
- Date: "https://prismic.io/docs/core-concepts/date",
25
- Timestamp: "https://prismic.io/docs/core-concepts/timestamp",
26
- Number: "https://prismic.io/docs/core-concepts/number",
27
- Text: "https://prismic.io/docs/core-concepts/key-text",
28
- Select: "https://prismic.io/docs/core-concepts/select",
29
- StructuredText: "https://prismic.io/docs/core-concepts/rich-text-title",
30
- Image: "https://prismic.io/docs/core-concepts/image",
31
- Link: "https://prismic.io/docs/core-concepts/link-content-relationship",
32
- Embed: "https://prismic.io/docs/core-concepts/embed",
33
- GeoPoint: "https://prismic.io/docs/core-concepts/geopoint",
34
- Group: "https://prismic.io/docs/core-concepts/group",
35
- IntegrationFields: "https://prismic.io/docs/core-concepts/integration-fields",
36
- Slices: "https://prismic.io/docs/core-concepts/slices",
37
- LegacySlices: "https://prismic.io/docs/core-concepts/slices"
38
- };
39
-
40
- const isCustomTypeModelField = (model) => {
41
- return typeof model === "object" && model !== null && "type" in model;
42
- };
43
-
44
- const hasOwnProperty = (obj, prop) => {
45
- return obj.hasOwnProperty(prop);
46
- };
47
-
48
- const isCustomTypeModelSlice = (model) => {
49
- return typeof model === "object" && model !== null && hasOwnProperty(model, "type") && model.type === CustomTypeModelSliceType.Slice;
50
- };
51
-
52
- const isSharedSliceModel$1 = (model) => {
53
- return typeof model === "object" && model !== null && hasOwnProperty(model, "type") && model.type === CustomTypeModelSliceType.SharedSlice;
54
- };
55
-
56
- const getAPIIDPath = (config) => {
57
- return config.path.map((element, i) => {
58
- if (isCustomTypeModelField(element.model) && (element.model.type === CustomTypeModelFieldType.Group || element.model.type === CustomTypeModelFieldType.Slices)) {
59
- return `${element.id}[]`;
60
- } else {
61
- if (element.id === "items") {
62
- const previousElement = config.path[i - 1];
63
- if (isCustomTypeModelSlice(previousElement.model) || isSharedSliceModel$1(previousElement.model)) {
64
- return `${element.id}[]`;
65
- }
66
- }
67
- return element.id;
68
- }
69
- }).join(".");
70
- };
71
-
72
- const getFieldDocumentationURL = (config) => {
73
- return FIELD_DOCUMENTATION_URLS[config.model.type];
74
- };
75
-
76
- const isCustomTypeModel$1 = (model) => {
77
- return typeof model === "object" && model !== null && "json" in model;
78
- };
79
-
80
- const getHumanReadableModelName = (config) => {
81
- if (isCustomTypeModel$1(config.model)) {
82
- return config.model.label || config.model.id;
83
- } else if (isSharedSliceModel$1(config.model)) {
84
- return config.model.name;
85
- } else if (isCustomTypeModelField(config.model)) {
86
- if (config.model.config && "label" in config.model.config) {
87
- return config.model.config.label || config.id;
88
- } else if (config.model.config && "fieldset" in config.model) {
89
- return config.model.fieldset || config.id;
90
- }
91
- } else if (isCustomTypeModelSlice(config.model)) {
92
- return config.model.fieldset || config.id;
93
- }
94
- return `\`${config.id}\``;
95
- };
96
-
97
- const getHumanReadableFieldPath = (config) => {
98
- return config.path.map((element) => {
99
- if (element.label) {
100
- return element.label;
101
- } else if (element.model) {
102
- return getHumanReadableModelName({
103
- id: element.id,
104
- model: element.model
105
- });
106
- } else {
107
- return element.id;
108
- }
109
- }).join(" \u2192 ");
110
- };
111
-
112
- const getHumanReadableFieldType = (config) => {
113
- switch (config.model.type) {
114
- case "StructuredText": {
115
- const isTitleField = config.model.config && "single" in config.model.config && config.model.config.single && config.model.config.single.split(",").every((blockType) => /heading/.test(blockType));
116
- return isTitleField ? "Title" : "Rich Text";
117
- }
118
- case "IntegrationFields": {
119
- const catalog = config.model.config?.catalog;
120
- return `Integration Fields (Catalog: ${catalog ? `\`${catalog}\`` : "*unknown*"})`;
121
- }
122
- case "Link": {
123
- switch (config.model.config?.select) {
124
- case CustomTypeModelLinkSelectType.Document: {
125
- return "Content Relationship";
126
- }
127
- case CustomTypeModelLinkSelectType.Media: {
128
- return "Link to Media";
129
- }
130
- default: {
131
- return "Link";
132
- }
133
- }
134
- }
135
- case "Slices": {
136
- return "Slice Zone";
137
- }
138
- default: {
139
- return config.model.type;
140
- }
141
- }
142
- };
143
-
144
- const writeFieldDocsDescription = (config) => {
145
- if (config.description) {
146
- config.writer.writeLine(config.description);
147
- }
148
- config.writer.blankLineIfLastNot();
149
- if (config.fieldType) {
150
- config.writer.writeLine(`- **Field Type**: ${config.fieldType}`);
151
- }
152
- if (config.placeholder) {
153
- config.writer.writeLine(`- **Placeholder**: ${config.placeholder}`);
154
- }
155
- if (config.defaultValue !== void 0) {
156
- const stringifiedDefaultValue = typeof config.defaultValue === "boolean" ? `${config.defaultValue}` : config.defaultValue;
157
- config.writer.writeLine(`- **Default Value**: ${stringifiedDefaultValue}`);
158
- }
159
- if (config.apiIDPath) {
160
- config.writer.writeLine(`- **API ID Path**: ${config.apiIDPath}`);
161
- }
162
- if (config.tabName) {
163
- config.writer.writeLine(`- **Tab**: ${config.tabName}`);
164
- }
165
- if (config.documentationURL) {
166
- config.writer.writeLine(`- **Documentation**: ${config.documentationURL}`);
167
- }
168
- };
169
-
170
- const buildFieldDocs = (config) => {
171
- return [
172
- {
173
- description: (writer) => {
174
- const name = getHumanReadableModelName({
175
- id: config.id,
176
- model: config.model
177
- });
178
- const humanReadablePath = getHumanReadableFieldPath({
179
- path: config.path
180
- });
181
- const fieldType = getHumanReadableFieldType({
182
- model: config.model
183
- });
184
- const placeholder = config.model.config && "placeholder" in config.model.config && config.model.config.placeholder ? config.model.config.placeholder : `*None*`;
185
- const defaultValue = config.model.config && "default_value" in config.model.config ? config.model.config.default_value : void 0;
186
- const apiIDPath = getAPIIDPath({
187
- path: [...config.path, { id: config.id, model: config.model }]
188
- });
189
- writeFieldDocsDescription({
190
- writer,
191
- description: `${name} field in *${humanReadablePath}*`,
192
- fieldType,
193
- placeholder,
194
- defaultValue,
195
- apiIDPath,
196
- tabName: config.tabName,
197
- documentationURL: getFieldDocumentationURL({ model: config.model })
198
- });
199
- }
200
- }
201
- ];
202
- };
203
-
204
- const pascalCase = (input) => pascalCase$1(input, {
205
- transform: pascalCaseTransformMerge
206
- });
207
-
208
- const buildSharedSliceInterfaceNamePart = (config) => {
209
- return pascalCase(`${config.id} Slice`);
210
- };
211
-
212
- const buildTypeName = (...parts) => {
213
- let name = pascalCase(parts.filter(Boolean).join(" "));
214
- if (/^[0-9]/.test(name) ? "_" : "") {
215
- name = `_${name}`;
216
- }
217
- return name;
218
- };
219
-
220
- const addInterfacePropertyForField = (config) => {
221
- switch (config.model.type) {
222
- case "UID": {
223
- break;
224
- }
225
- case "Boolean": {
226
- config.interface.addProperty({
227
- name: config.id,
228
- type: "prismicT.BooleanField",
229
- docs: buildFieldDocs({
230
- id: config.id,
231
- model: config.model,
232
- path: config.path,
233
- tabName: config.tabName
234
- })
235
- });
236
- break;
237
- }
238
- case "Color": {
239
- config.interface.addProperty({
240
- name: config.id,
241
- type: "prismicT.ColorField",
242
- docs: buildFieldDocs({
243
- id: config.id,
244
- model: config.model,
245
- path: config.path,
246
- tabName: config.tabName
247
- })
248
- });
249
- break;
250
- }
251
- case "Date": {
252
- config.interface.addProperty({
253
- name: config.id,
254
- type: "prismicT.DateField",
255
- docs: buildFieldDocs({
256
- id: config.id,
257
- model: config.model,
258
- path: config.path,
259
- tabName: config.tabName
260
- })
261
- });
262
- break;
263
- }
264
- case "Embed": {
265
- const providerTypes = [];
266
- if (config.fieldConfigs.embed?.providerTypes) {
267
- for (const providerType in config.fieldConfigs.embed?.providerTypes) {
268
- const configuredProviderType = config.fieldConfigs.embed?.providerTypes[providerType];
269
- providerTypes.push(
270
- `({ provider_name: "${providerType}" } & ${configuredProviderType})`
271
- );
272
- }
273
- }
274
- config.interface.addProperty({
275
- name: config.id,
276
- type: providerTypes.length > 0 ? `prismicT.EmbedField<prismicT.AnyOEmbed & prismicT.OEmbedExtra & (${providerTypes.join(
277
- " | "
278
- )})>` : "prismicT.EmbedField",
279
- docs: buildFieldDocs({
280
- id: config.id,
281
- model: config.model,
282
- path: config.path,
283
- tabName: config.tabName
284
- })
285
- });
286
- break;
287
- }
288
- case "GeoPoint": {
289
- config.interface.addProperty({
290
- name: config.id,
291
- type: "prismicT.GeoPointField",
292
- docs: buildFieldDocs({
293
- id: config.id,
294
- model: config.model,
295
- path: config.path,
296
- tabName: config.tabName
297
- })
298
- });
299
- break;
300
- }
301
- case "Image": {
302
- if (config.model.config?.thumbnails && config.model.config.thumbnails.length > 0) {
303
- const thumbnailNames = config.model.config.thumbnails.map((thumbnail) => `"${thumbnail.name}"`).join(" | ");
304
- config.interface.addProperty({
305
- name: config.id,
306
- type: `prismicT.ImageField<${thumbnailNames}>`,
307
- docs: buildFieldDocs({
308
- id: config.id,
309
- model: config.model,
310
- path: config.path,
311
- tabName: config.tabName
312
- })
313
- });
314
- } else {
315
- config.interface.addProperty({
316
- name: config.id,
317
- type: "prismicT.ImageField<never>",
318
- docs: buildFieldDocs({
319
- id: config.id,
320
- model: config.model,
321
- path: config.path,
322
- tabName: config.tabName
323
- })
324
- });
325
- }
326
- break;
327
- }
328
- case "IntegrationFields": {
329
- const catalogType = config.model.config?.catalog ? config.fieldConfigs.integrationFields?.catalogTypes?.[config.model.config.catalog] : void 0;
330
- config.interface.addProperty({
331
- name: config.id,
332
- type: catalogType ? `prismicT.IntegrationFields<${catalogType}>` : "prismicT.IntegrationFields",
333
- docs: buildFieldDocs({
334
- id: config.id,
335
- model: config.model,
336
- path: config.path,
337
- tabName: config.tabName
338
- })
339
- });
340
- break;
341
- }
342
- case "Link": {
343
- switch (config.model.config?.select) {
344
- case CustomTypeModelLinkSelectType.Document: {
345
- config.model.config;
346
- config.interface.addProperty({
347
- name: config.id,
348
- type: "customtypes" in config.model.config && config.model.config.customtypes && config.model.config.customtypes.length > 0 ? `prismicT.RelationField<${config.model.config.customtypes.map((type) => `"${type}"`).join(" | ")}>` : "prismicT.RelationField",
349
- docs: buildFieldDocs({
350
- id: config.id,
351
- model: config.model,
352
- path: config.path,
353
- tabName: config.tabName
354
- })
355
- });
356
- break;
357
- }
358
- case CustomTypeModelLinkSelectType.Media: {
359
- config.interface.addProperty({
360
- name: config.id,
361
- type: "prismicT.LinkToMediaField",
362
- docs: buildFieldDocs({
363
- id: config.id,
364
- model: config.model,
365
- path: config.path,
366
- tabName: config.tabName
367
- })
368
- });
369
- break;
370
- }
371
- default: {
372
- config.interface.addProperty({
373
- name: config.id,
374
- type: "prismicT.LinkField",
375
- docs: buildFieldDocs({
376
- id: config.id,
377
- model: config.model,
378
- path: config.path,
379
- tabName: config.tabName
380
- })
381
- });
382
- }
383
- }
384
- break;
385
- }
386
- case "Number": {
387
- config.interface.addProperty({
388
- name: config.id,
389
- type: "prismicT.NumberField",
390
- docs: buildFieldDocs({
391
- id: config.id,
392
- model: config.model,
393
- path: config.path,
394
- tabName: config.tabName
395
- })
396
- });
397
- break;
398
- }
399
- case "StructuredText": {
400
- const isTitleField = config.model.config && "single" in config.model.config && config.model.config.single && config.model.config.single.split(",").every((blockType) => /heading/.test(blockType));
401
- if (isTitleField) {
402
- config.interface.addProperty({
403
- name: config.id,
404
- type: "prismicT.TitleField",
405
- docs: buildFieldDocs({
406
- id: config.id,
407
- model: config.model,
408
- path: config.path,
409
- tabName: config.tabName
410
- })
411
- });
412
- } else {
413
- config.interface.addProperty({
414
- name: config.id,
415
- type: "prismicT.RichTextField",
416
- docs: buildFieldDocs({
417
- id: config.id,
418
- model: config.model,
419
- path: config.path,
420
- tabName: config.tabName
421
- })
422
- });
423
- }
424
- break;
425
- }
426
- case "Select": {
427
- const options = config.model.config?.options?.map((option) => `"${option}"`).join(" | ");
428
- const hasDefault = Boolean(config.model.config?.default_value);
429
- if (hasDefault) {
430
- config.interface.addProperty({
431
- name: config.id,
432
- type: `prismicT.SelectField<${options || "string"}, "filled">`,
433
- docs: buildFieldDocs({
434
- id: config.id,
435
- model: config.model,
436
- path: config.path,
437
- tabName: config.tabName
438
- })
439
- });
440
- } else {
441
- config.interface.addProperty({
442
- name: config.id,
443
- type: `prismicT.SelectField<${options}>`,
444
- docs: buildFieldDocs({
445
- id: config.id,
446
- model: config.model,
447
- path: config.path,
448
- tabName: config.tabName
449
- })
450
- });
451
- }
452
- break;
453
- }
454
- case "Text": {
455
- config.interface.addProperty({
456
- name: config.id,
457
- type: "prismicT.KeyTextField",
458
- docs: buildFieldDocs({
459
- id: config.id,
460
- model: config.model,
461
- path: config.path,
462
- tabName: config.tabName
463
- })
464
- });
465
- break;
466
- }
467
- case "Timestamp": {
468
- config.interface.addProperty({
469
- name: config.id,
470
- type: "prismicT.TimestampField",
471
- docs: buildFieldDocs({
472
- id: config.id,
473
- model: config.model,
474
- path: config.path,
475
- tabName: config.tabName
476
- })
477
- });
478
- break;
479
- }
480
- case "Group": {
481
- const itemInterface = config.sourceFile.addInterface({
482
- name: buildTypeName(
483
- config.path[0].id,
484
- "Document",
485
- "Data",
486
- config.id,
487
- "Item"
488
- ),
489
- docs: [
490
- {
491
- description: (writer) => {
492
- const humanReadablePath = getHumanReadableFieldPath({
493
- path: [
494
- ...config.path,
495
- {
496
- id: config.id,
497
- model: config.model
498
- }
499
- ]
500
- });
501
- writer.writeLine(`Item in ${humanReadablePath}`);
502
- }
503
- }
504
- ],
505
- isExported: true
506
- });
507
- if (config.model.config?.fields) {
508
- addInterfacePropertiesForFields({
509
- interface: itemInterface,
510
- sourceFile: config.sourceFile,
511
- fields: config.model.config.fields,
512
- path: [
513
- ...config.path,
514
- {
515
- id: config.id,
516
- model: config.model
517
- }
518
- ],
519
- fieldConfigs: config.fieldConfigs
520
- });
521
- }
522
- config.interface.addProperty({
523
- name: config.id,
524
- type: `prismicT.GroupField<Simplify<${itemInterface.getName()}>>`,
525
- docs: buildFieldDocs({
526
- id: config.id,
527
- model: config.model,
528
- path: config.path,
529
- tabName: config.tabName
530
- })
531
- });
532
- break;
533
- }
534
- case "Slices": {
535
- const choiceInterfaceNames = [];
536
- if (config.model.config?.choices) {
537
- for (const choiceId in config.model.config.choices) {
538
- const choice = config.model.config.choices[choiceId];
539
- if (choice.type === CustomTypeModelSliceType.SharedSlice) {
540
- choiceInterfaceNames.push(
541
- buildSharedSliceInterfaceNamePart({ id: choiceId })
542
- );
543
- } else if (choice.type === CustomTypeModelSliceType.Slice) {
544
- let primaryInterface;
545
- if (choice["non-repeat"] && Object.keys(choice["non-repeat"]).length > 0) {
546
- primaryInterface = config.sourceFile.addInterface({
547
- name: buildTypeName(
548
- config.path[0].id,
549
- "Document",
550
- "Data",
551
- config.id,
552
- choiceId,
553
- "Slice",
554
- "Primary"
555
- ),
556
- docs: [
557
- {
558
- description: (writer) => {
559
- const humanReadablePath = getHumanReadableFieldPath({
560
- path: [
561
- ...config.path,
562
- {
563
- id: config.id,
564
- model: config.model
565
- },
566
- {
567
- id: choiceId,
568
- model: choice
569
- },
570
- {
571
- id: "primary",
572
- label: "Primary"
573
- }
574
- ]
575
- });
576
- writer.writeLine(
577
- `Primary content in ${humanReadablePath}`
578
- );
579
- }
580
- }
581
- ]
582
- });
583
- addInterfacePropertiesForFields({
584
- interface: primaryInterface,
585
- sourceFile: config.sourceFile,
586
- fields: choice["non-repeat"],
587
- path: [
588
- ...config.path,
589
- {
590
- id: config.id,
591
- model: config.model
592
- },
593
- {
594
- id: choiceId,
595
- model: choice
596
- },
597
- {
598
- id: "primary",
599
- label: "Primary"
600
- }
601
- ],
602
- fieldConfigs: config.fieldConfigs
603
- });
604
- }
605
- let itemInterface;
606
- if (choice.repeat && Object.keys(choice.repeat).length > 0) {
607
- itemInterface = config.sourceFile.addInterface({
608
- name: buildTypeName(
609
- config.path[0].id,
610
- "Document",
611
- "Data",
612
- config.id,
613
- choiceId,
614
- "Slice",
615
- "Item"
616
- ),
617
- docs: [
618
- {
619
- description: (writer) => {
620
- const humanReadablePath = getHumanReadableFieldPath({
621
- path: [
622
- ...config.path,
623
- {
624
- id: config.id,
625
- model: config.model
626
- },
627
- {
628
- id: choiceId,
629
- model: choice
630
- },
631
- {
632
- id: "items",
633
- label: "Items"
634
- }
635
- ]
636
- });
637
- writer.writeLine(`Item in ${humanReadablePath}`);
638
- }
639
- }
640
- ],
641
- isExported: true
642
- });
643
- addInterfacePropertiesForFields({
644
- interface: itemInterface,
645
- sourceFile: config.sourceFile,
646
- fields: choice.repeat,
647
- path: [
648
- ...config.path,
649
- {
650
- id: config.id,
651
- model: config.model
652
- },
653
- {
654
- id: choiceId,
655
- model: choice
656
- },
657
- {
658
- id: "items",
659
- label: "Items"
660
- }
661
- ],
662
- fieldConfigs: config.fieldConfigs
663
- });
664
- }
665
- const sliceType = config.sourceFile.addTypeAlias({
666
- name: buildTypeName(
667
- config.path[0].id,
668
- "Document",
669
- "Data",
670
- config.id,
671
- choiceId,
672
- "Slice"
673
- ),
674
- type: `prismicT.Slice<"${choiceId}", ${primaryInterface ? `Simplify<${primaryInterface.getName()}>` : "Record<string, never>"}, ${itemInterface ? `Simplify<${itemInterface.getName()}>` : "never"}>`,
675
- isExported: true
676
- });
677
- choiceInterfaceNames.push(sliceType.getName());
678
- }
679
- }
680
- }
681
- const slicesType = config.sourceFile.addTypeAlias({
682
- name: buildTypeName(
683
- config.path[0].id,
684
- "Document",
685
- "Data",
686
- config.id,
687
- "Slice"
688
- ),
689
- type: choiceInterfaceNames.length > 0 ? choiceInterfaceNames.join(" | ") : "never",
690
- docs: [
691
- {
692
- description: (writer) => {
693
- const humanReadablePath = getHumanReadableFieldPath({
694
- path: [
695
- ...config.path,
696
- {
697
- id: config.id,
698
- model: config.model
699
- }
700
- ]
701
- });
702
- writer.writeLine(`Slice for *${humanReadablePath}*`);
703
- }
704
- }
705
- ]
706
- });
707
- config.interface.addProperty({
708
- name: config.id,
709
- type: `prismicT.SliceZone<${slicesType.getName()}>`,
710
- docs: buildFieldDocs({
711
- id: config.id,
712
- model: config.model,
713
- path: config.path,
714
- tabName: config.tabName
715
- })
716
- });
717
- break;
718
- }
719
- default: {
720
- config.interface.addProperty({
721
- name: config.id,
722
- type: "unknown",
723
- docs: buildFieldDocs({
724
- id: config.id,
725
- model: config.model,
726
- path: config.path,
727
- tabName: config.tabName
728
- })
729
- });
730
- }
731
- }
732
- };
733
- const addInterfacePropertiesForFields = (config) => {
734
- for (const name in config.fields) {
735
- addInterfacePropertyForField({
736
- ...config,
737
- id: name.includes("-") || /^[0-9]/.test(name) ? `"${name}"` : name,
738
- model: config.fields[name],
739
- tabName: config.tabName
740
- });
741
- }
742
- };
743
-
744
- const collectCustomTypeFields = (model) => {
745
- return Object.assign({}, ...Object.values(model.json));
746
- };
747
- const addTypeAliasForCustomType = ({
748
- model,
749
- sourceFile,
750
- localeIDs,
751
- fieldConfigs
752
- }) => {
753
- const { uid: uidField, ...fields } = collectCustomTypeFields(model);
754
- const hasDataFields = Object.keys(fields).length > 0;
755
- const hasUIDField = Boolean(uidField);
756
- let dataInterface;
757
- if (hasDataFields) {
758
- dataInterface = sourceFile.addInterface({
759
- name: buildTypeName(model.id, "Document", "Data"),
760
- docs: [
761
- {
762
- description: `Content for ${model.label} documents`
763
- }
764
- ]
765
- });
766
- for (const tabName in model.json) {
767
- const { uid: _uidField, ...tabFields } = model.json[tabName];
768
- addInterfacePropertiesForFields({
769
- fields: tabFields,
770
- interface: dataInterface,
771
- sourceFile,
772
- path: [
773
- {
774
- id: model.id,
775
- model
776
- }
777
- ],
778
- fieldConfigs,
779
- tabName
780
- });
781
- }
782
- } else {
783
- dataInterface = sourceFile.addTypeAlias({
784
- name: buildTypeName(model.id, "Document", "Data"),
785
- type: `Record<string, never>`,
786
- docs: [
787
- {
788
- description: `Content for ${model.label} documents`
789
- }
790
- ]
791
- });
792
- }
793
- return sourceFile.addTypeAlias({
794
- name: buildTypeName(model.id, "Document"),
795
- typeParameters: [
796
- {
797
- name: "Lang",
798
- constraint: "string",
799
- default: localeIDs.length > 0 ? localeIDs.map((localeID) => `"${localeID}"`).join(" | ") : "string"
800
- }
801
- ],
802
- type: hasUIDField ? `prismicT.PrismicDocumentWithUID<Simplify<${dataInterface.getName()}>, "${model.id}", Lang>` : `prismicT.PrismicDocumentWithoutUID<Simplify<${dataInterface.getName()}>, "${model.id}", Lang>`,
803
- docs: [
804
- {
805
- description: (writer) => {
806
- writer.writeLine(`${model.label} document from Prismic`);
807
- writer.blankLine();
808
- writer.writeLine(`- **API ID**: \`${model.id}\``);
809
- writer.writeLine(`- **Repeatable**: \`${model.repeatable}\``);
810
- writer.writeLine(
811
- `- **Documentation**: ${CUSTOM_TYPES_DOCUMENTATION_URL}`
812
- );
813
- },
814
- tags: [
815
- {
816
- tagName: "typeParam",
817
- text: "Lang - Language API ID of the document."
818
- }
819
- ]
820
- }
821
- ],
822
- isExported: true
823
- });
824
- };
825
-
826
- const addTypeAliasForSharedSlice = (config) => {
827
- const variationTypeNames = [];
828
- for (const variation of config.model.variations) {
829
- let primaryInterface;
830
- if (variation.primary && Object.keys(variation.primary).length > 0) {
831
- primaryInterface = config.sourceFile.addInterface({
832
- name: buildTypeName(
833
- buildSharedSliceInterfaceNamePart({ id: config.model.id }),
834
- variation.id,
835
- "Primary"
836
- ),
837
- docs: [
838
- {
839
- description: (writer) => {
840
- const humanReadablePath = getHumanReadableFieldPath({
841
- path: [
842
- {
843
- id: config.model.id,
844
- model: config.model
845
- },
846
- {
847
- id: "primary",
848
- label: "Primary"
849
- }
850
- ]
851
- });
852
- writer.writeLine(`Primary content in ${humanReadablePath}`);
853
- }
854
- }
855
- ]
856
- });
857
- addInterfacePropertiesForFields({
858
- interface: primaryInterface,
859
- sourceFile: config.sourceFile,
860
- fields: variation.primary,
861
- path: [
862
- {
863
- id: config.model.id,
864
- model: config.model
865
- },
866
- {
867
- id: "primary",
868
- label: "Primary"
869
- }
870
- ],
871
- fieldConfigs: config.fieldConfigs
872
- });
873
- }
874
- let itemInterface;
875
- if (variation.items && Object.keys(variation.items).length > 0) {
876
- itemInterface = config.sourceFile.addInterface({
877
- name: buildTypeName(
878
- buildSharedSliceInterfaceNamePart({ id: config.model.id }),
879
- variation.id,
880
- "Item"
881
- ),
882
- docs: [
883
- {
884
- description: (writer) => {
885
- const humanReadablePath = getHumanReadableFieldPath({
886
- path: [
887
- {
888
- id: config.model.id,
889
- model: config.model
890
- },
891
- {
892
- id: "items",
893
- label: "Items"
894
- }
895
- ]
896
- });
897
- writer.writeLine(`Item in ${humanReadablePath}`);
898
- }
899
- }
900
- ],
901
- isExported: true
902
- });
903
- addInterfacePropertiesForFields({
904
- interface: itemInterface,
905
- sourceFile: config.sourceFile,
906
- fields: variation.items,
907
- path: [
908
- {
909
- id: config.model.id,
910
- model: config.model
911
- },
912
- {
913
- id: "items",
914
- label: "Items"
915
- }
916
- ],
917
- fieldConfigs: config.fieldConfigs
918
- });
919
- }
920
- const variationType = config.sourceFile.addTypeAlias({
921
- name: buildTypeName(
922
- buildSharedSliceInterfaceNamePart({ id: config.model.id }),
923
- variation.id
924
- ),
925
- type: `prismicT.SharedSliceVariation<"${variation.id}", ${primaryInterface ? `Simplify<${primaryInterface.getName()}>` : "Record<string, never>"}, ${itemInterface ? `Simplify<${itemInterface.getName()}>` : "never"}>`,
926
- docs: [
927
- {
928
- description: (writer) => {
929
- writer.writeLine(
930
- `${variation.name} variation for ${config.model.name} Slice`
931
- );
932
- writer.blankLine();
933
- writer.writeLine(`- **API ID**: \`${variation.id}\``);
934
- writer.writeLine(`- **Description**: \`${variation.description}\``);
935
- writer.writeLine(
936
- `- **Documentation**: ${SHARED_SLICES_DOCUMENTATION_URL}`
937
- );
938
- }
939
- }
940
- ],
941
- isExported: true
942
- });
943
- variationTypeNames.push(variationType.getName());
944
- }
945
- const variationsType = config.sourceFile.addTypeAlias({
946
- name: buildTypeName(config.model.id, "Slice", "Variation"),
947
- type: variationTypeNames.length > 0 ? variationTypeNames.join(" | ") : "never",
948
- docs: [
949
- {
950
- description: (writer) => {
951
- const humanReadablePath = getHumanReadableFieldPath({
952
- path: [
953
- {
954
- id: config.model.id,
955
- model: config.model
956
- }
957
- ]
958
- });
959
- writer.writeLine(`Slice variation for *${humanReadablePath}*`);
960
- }
961
- }
962
- ]
963
- });
964
- return config.sourceFile.addTypeAlias({
965
- name: buildTypeName(
966
- buildSharedSliceInterfaceNamePart({ id: config.model.id })
967
- ),
968
- type: `prismicT.SharedSlice<"${config.model.id}", ${variationsType.getName()}>`,
969
- docs: [
970
- {
971
- description: (writer) => {
972
- writer.writeLine(`${config.model.name} Shared Slice`);
973
- writer.blankLine();
974
- writer.writeLine(`- **API ID**: \`${config.model.id}\``);
975
- writer.writeLine(
976
- `- **Description**: \`${config.model.description}\``
977
- );
978
- writer.writeLine(
979
- `- **Documentation**: ${SHARED_SLICES_DOCUMENTATION_URL}`
980
- );
981
- }
982
- }
983
- ],
984
- isExported: true
985
- });
986
- };
987
-
988
- const getSourceFileText = (sourceFile) => {
989
- const text = sourceFile.print().replace(new RegExp(BLANK_LINE_IDENTIFIER, "g"), "");
990
- return text;
991
- };
992
-
993
- const generateTypes = (config = {}) => {
994
- const project = new Project({
995
- useInMemoryFileSystem: true
996
- });
997
- const sourceFile = project.createSourceFile("types.d.ts");
998
- sourceFile.addImportDeclaration({
999
- moduleSpecifier: "@prismicio/types",
1000
- namespaceImport: "prismicT",
1001
- isTypeOnly: true
1002
- });
1003
- sourceFile.addStatements(BLANK_LINE_IDENTIFIER);
1004
- const simplifyTypeAlias = sourceFile.addTypeAlias({
1005
- name: "Simplify",
1006
- typeParameters: [
1007
- {
1008
- name: "T"
1009
- }
1010
- ],
1011
- type: `{ [KeyType in keyof T]: T[KeyType] }`
1012
- });
1013
- if (config.customTypeModels) {
1014
- for (const model of config.customTypeModels) {
1015
- addTypeAliasForCustomType({
1016
- model,
1017
- sourceFile,
1018
- localeIDs: config.localeIDs || [],
1019
- fieldConfigs: config.fieldConfigs || {}
1020
- });
1021
- }
1022
- if (config.customTypeModels.length > 0) {
1023
- sourceFile.addTypeAlias({
1024
- name: "AllDocumentTypes",
1025
- type: config.customTypeModels.map(
1026
- (customTypeModel) => buildTypeName(customTypeModel.id, "Document")
1027
- ).join(" | "),
1028
- isExported: true
1029
- });
1030
- }
1031
- }
1032
- if (config.sharedSliceModels) {
1033
- for (const model of config.sharedSliceModels) {
1034
- addTypeAliasForSharedSlice({
1035
- model,
1036
- sourceFile,
1037
- fieldConfigs: config.fieldConfigs || {}
1038
- });
1039
- }
1040
- }
1041
- if (config.clientIntegration?.includeCreateClientInterface || config.clientIntegration?.includeContentNamespace) {
1042
- sourceFile.addImportDeclaration({
1043
- moduleSpecifier: "@prismicio/client",
1044
- namespaceImport: "prismic",
1045
- isTypeOnly: true
1046
- });
1047
- const clientModuleDeclaration = sourceFile.addModule({
1048
- name: '"@prismicio/client"',
1049
- hasDeclareKeyword: true,
1050
- declarationKind: ModuleDeclarationKind.Module
1051
- });
1052
- if (config.clientIntegration.includeCreateClientInterface) {
1053
- clientModuleDeclaration.addInterface({
1054
- name: "CreateClient",
1055
- callSignatures: [
1056
- {
1057
- parameters: [
1058
- {
1059
- name: "repositoryNameOrEndpoint",
1060
- type: "string"
1061
- },
1062
- {
1063
- name: "options",
1064
- type: "prismic.ClientConfig",
1065
- hasQuestionToken: true
1066
- }
1067
- ],
1068
- returnType: (config.customTypeModels?.length || 0) > 0 ? "prismic.Client<AllDocumentTypes>" : "prismic.Client"
1069
- }
1070
- ]
1071
- });
1072
- }
1073
- if (config.clientIntegration.includeContentNamespace) {
1074
- const contentNamespaceDeclaration = clientModuleDeclaration.addModule({
1075
- name: "Content",
1076
- declarationKind: ModuleDeclarationKind.Namespace
1077
- });
1078
- const exportSymbols = sourceFile.getExportSymbols().filter((exportSymbol) => {
1079
- return exportSymbol.getName() !== simplifyTypeAlias.getName();
1080
- });
1081
- contentNamespaceDeclaration.addExportDeclaration({
1082
- isTypeOnly: true,
1083
- namedExports: exportSymbols.map((exportSymbol) => {
1084
- return {
1085
- name: exportSymbol.getName()
1086
- };
1087
- })
1088
- });
1089
- }
1090
- }
1091
- return getSourceFileText(sourceFile);
1092
- };
1093
-
1094
- const configSchema = Joi.object({
1095
- repositoryName: Joi.string().when("locales.fetchFromRepository", {
1096
- is: true,
1097
- then: Joi.required()
1098
- }).when("models.fetchFromRepository", {
1099
- is: true,
1100
- then: Joi.required()
1101
- }),
1102
- accessToken: Joi.string(),
1103
- customTypesAPIToken: Joi.string(),
1104
- output: Joi.string(),
1105
- clientIntegration: Joi.object({
1106
- includeCreateClientInterface: Joi.boolean(),
1107
- includeContentNamespace: Joi.boolean()
1108
- }),
1109
- locales: Joi.alternatives(
1110
- Joi.array().items(Joi.string().required()),
1111
- Joi.object({
1112
- ids: Joi.array().items(Joi.string().required()),
1113
- fetchFromRepository: Joi.boolean()
1114
- })
1115
- ),
1116
- models: Joi.alternatives(
1117
- Joi.array().items(Joi.string()),
1118
- Joi.object({
1119
- files: Joi.array().items(Joi.string()),
1120
- fetchFromRepository: Joi.boolean()
1121
- })
1122
- ),
1123
- fields: Joi.object({
1124
- embed: Joi.object({
1125
- providerTypes: Joi.object().pattern(
1126
- Joi.string(),
1127
- Joi.string().required()
1128
- )
1129
- }),
1130
- integrationFields: Joi.object({
1131
- catalogTypes: Joi.object().pattern(Joi.string(), Joi.string().required())
1132
- })
1133
- })
1134
- });
1135
-
1136
- const loadLocaleIDs = async (config) => {
1137
- const localeIDs = new Set(config.localeIDs || []);
1138
- if ("repositoryName" in config && config.fetchFromRepository) {
1139
- const client = prismic.createClient(config.repositoryName, {
1140
- accessToken: config.accessToken,
1141
- fetch
1142
- });
1143
- const repository = await client.getRepository();
1144
- for (const language of repository.languages) {
1145
- localeIDs.add(language.id);
1146
- }
1147
- }
1148
- return [...localeIDs];
1149
- };
1150
-
1151
- const isCustomTypeModel = (input) => {
1152
- return typeof input === "object" && input !== null && "json" in input;
1153
- };
1154
- const isSharedSliceModel = (input) => {
1155
- return typeof input === "object" && input !== null && "variations" in input;
1156
- };
1157
- const readJSONFromGlob = async (globs) => {
1158
- const paths = await fg(globs.split(",").map((path) => path.trim()));
1159
- return paths.map((path) => {
1160
- const raw = readFileSync(path, "utf8");
1161
- return JSON.parse(raw);
1162
- });
1163
- };
1164
- const loadModels = async (config) => {
1165
- const customTypeModels = {};
1166
- const sharedSliceModels = {};
1167
- if ("customTypesAPIToken" in config) {
1168
- const customTypesClient = prismicCT.createClient({
1169
- repositoryName: config.repositoryName,
1170
- token: config.customTypesAPIToken,
1171
- fetch
1172
- });
1173
- if (config.fetchFromRepository) {
1174
- const [remoteCustomTypeModels, remoteSharedSliceModels] = await Promise.all([
1175
- customTypesClient.getAllCustomTypes(),
1176
- customTypesClient.getAllSharedSlices()
1177
- ]);
1178
- for (const customTypeModel of remoteCustomTypeModels) {
1179
- customTypeModels[customTypeModel.id] = customTypeModel;
1180
- }
1181
- for (const sharedSliceModel of remoteSharedSliceModels) {
1182
- sharedSliceModels[sharedSliceModel.id] = sharedSliceModel;
1183
- }
1184
- }
1185
- }
1186
- if (config.localPaths) {
1187
- const models = (await Promise.all(config.localPaths.map((glob) => readJSONFromGlob(glob)))).flat();
1188
- for (const model of models) {
1189
- if (isCustomTypeModel(model)) {
1190
- customTypeModels[model.id] = model;
1191
- } else if (isSharedSliceModel(model)) {
1192
- sharedSliceModels[model.id] = model;
1193
- }
1194
- }
1195
- }
1196
- return {
1197
- customTypeModels: Object.values(customTypeModels).sort((a, b) => {
1198
- return a.id.localeCompare(b.id);
1199
- }),
1200
- sharedSliceModels: Object.values(sharedSliceModels).sort((a, b) => {
1201
- return a.id.localeCompare(b.id);
1202
- })
1203
- };
1204
- };
1205
-
1206
- const jiti = _jiti(process.cwd());
1207
- const loadModuleWithJiti = (id) => {
1208
- const mod = jiti(id);
1209
- return "default" in mod ? mod.default : mod;
1210
- };
1211
- const DEFAULT_CONFIG_PATHS = [
1212
- "prismicCodegen.config.ts",
1213
- "prismicCodegen.config.js"
1214
- ];
1215
- const loadConfig = (config) => {
1216
- if (config.path) {
1217
- if (existsSync(config.path)) {
1218
- return loadModuleWithJiti(resolve(config.path));
1219
- } else {
1220
- throw new Error(`Config file does not exist: ${config.path}`);
1221
- }
1222
- } else {
1223
- for (const configPath of DEFAULT_CONFIG_PATHS) {
1224
- if (existsSync(configPath)) {
1225
- return loadModuleWithJiti(resolve(configPath));
1226
- }
1227
- }
1228
- }
1229
- return {};
1230
- };
1231
-
1232
- const NON_EDITABLE_FILE_HEADER = "// Code generated by prismic-ts-codegen. DO NOT EDIT.";
1233
-
1234
- const cli = meow(
1235
- `
1236
- Usage:
1237
- prismic-ts-codegen [options...]
1238
- prismic-ts-codegen init [options...]
1239
-
1240
- Commands:
1241
- init [options]
1242
-
1243
- Options:
1244
- -c, --config <path> Path to a prismic-ts-codegen configuration file.
1245
- `,
1246
- {
1247
- importMeta: import.meta,
1248
- flags: {
1249
- config: {
1250
- type: "string",
1251
- alias: "c",
1252
- isRequired: false
1253
- }
1254
- }
1255
- }
1256
- );
1257
- const main = async () => {
1258
- if (cli.input[0] === "init") {
1259
- const configPath = cli.flags.config || "prismicCodegen.config.ts";
1260
- if (existsSync(configPath)) {
1261
- console.info(`
1262
- ${configPath} already exists.`);
1263
- } else {
1264
- let contents = "";
1265
- if (existsSync("sm.json")) {
1266
- contents = stripIndent`
1267
- import type { Config } from "prismic-ts-codegen";
1268
-
1269
- const config: Config = {
1270
- output: "./types.generated.ts",
1271
- models: ["./customtypes/**/index.json", "./slices/**/model.json"],
1272
- };
1273
-
1274
- export default config;
1275
- `;
1276
- } else {
1277
- contents = stripIndent`
1278
- import type { Config } from "prismic-ts-codegen";
1279
-
1280
- const config: Config = {
1281
- output: "./types.generated.ts",
1282
- };
1283
-
1284
- export default config;
1285
- `;
1286
- }
1287
- writeFileSync(configPath, contents);
1288
- console.info(`
1289
- Created prismic-ts-codegen config file: ${configPath}`);
1290
- }
1291
- } else {
1292
- const unvalidatedConfig = loadConfig({ path: cli.flags.config });
1293
- const { value: config, error } = configSchema.validate(unvalidatedConfig);
1294
- if (config && !error) {
1295
- const { customTypeModels, sharedSliceModels } = await loadModels({
1296
- localPaths: Array.isArray(config.models) ? config.models : config.models?.files,
1297
- repositoryName: config.repositoryName,
1298
- customTypesAPIToken: config.customTypesAPIToken,
1299
- fetchFromRepository: config.models && "fetchFromRepository" in config.models && config.models.fetchFromRepository
1300
- });
1301
- const localeIDs = await loadLocaleIDs({
1302
- localeIDs: Array.isArray(config.locales) ? config.locales : config.locales?.ids,
1303
- repositoryName: config.repositoryName,
1304
- accessToken: config.accessToken,
1305
- fetchFromRepository: config.locales && "fetchFromRepository" in config.locales && config.locales.fetchFromRepository
1306
- });
1307
- const hasCustomTypeModels = customTypeModels.length > 0;
1308
- if (config.clientIntegration?.includeCreateClientInterface && !hasCustomTypeModels) {
1309
- console.info(
1310
- "[INFO]: prismic-ts-codegen was configured to automatically integrate with `@prismicio/client`, but the integration was not generated because no Custom Type models were found. Automatic integration requires at least one Custom Type model."
1311
- );
1312
- }
1313
- const types = generateTypes({
1314
- customTypeModels,
1315
- sharedSliceModels,
1316
- localeIDs,
1317
- fieldConfigs: config.fields,
1318
- clientIntegration: {
1319
- includeCreateClientInterface: hasCustomTypeModels ? config.clientIntegration?.includeCreateClientInterface ?? true : false,
1320
- includeContentNamespace: config.clientIntegration?.includeContentNamespace ?? true
1321
- }
1322
- });
1323
- const fileContents = `${NON_EDITABLE_FILE_HEADER}
1324
-
1325
- ${types}`;
1326
- if (config.output) {
1327
- writeFileSync(resolve(config.output), fileContents);
1328
- console.info(`
1329
- Generated types in: ${config.output}`);
1330
- } else {
1331
- process.stdout.write(types + "\n");
1332
- }
1333
- } else {
1334
- if (error) {
1335
- console.error(error.message);
1336
- return;
1337
- }
1338
- }
1339
- }
1340
- };
1341
- main().catch((error) => console.error(error));
1342
- //# sourceMappingURL=cli.mjs.map