@angeloashmore/prismic-cli-poc 0.0.0-canary.1143872

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 (139) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +98 -0
  3. package/dist/index.mjs +2508 -0
  4. package/package.json +53 -0
  5. package/src/codegen-types.ts +82 -0
  6. package/src/codegen.ts +45 -0
  7. package/src/custom-type-add-field-boolean.ts +222 -0
  8. package/src/custom-type-add-field-color.ts +205 -0
  9. package/src/custom-type-add-field-date.ts +208 -0
  10. package/src/custom-type-add-field-embed.ts +205 -0
  11. package/src/custom-type-add-field-geo-point.ts +202 -0
  12. package/src/custom-type-add-field-group.ts +179 -0
  13. package/src/custom-type-add-field-image.ts +205 -0
  14. package/src/custom-type-add-field-key-text.ts +205 -0
  15. package/src/custom-type-add-field-link.ts +228 -0
  16. package/src/custom-type-add-field-number.ts +237 -0
  17. package/src/custom-type-add-field-rich-text.ts +229 -0
  18. package/src/custom-type-add-field-select.ts +211 -0
  19. package/src/custom-type-add-field-timestamp.ts +208 -0
  20. package/src/custom-type-add-field-uid.ts +188 -0
  21. package/src/custom-type-add-field.ts +116 -0
  22. package/src/custom-type-connect-slice.ts +214 -0
  23. package/src/custom-type-create.ts +112 -0
  24. package/src/custom-type-disconnect-slice.ts +171 -0
  25. package/src/custom-type-list.ts +110 -0
  26. package/src/custom-type-remove-field.ts +171 -0
  27. package/src/custom-type-remove.ts +138 -0
  28. package/src/custom-type-set-name.ts +138 -0
  29. package/src/custom-type-view.ts +118 -0
  30. package/src/custom-type.ts +85 -0
  31. package/src/docs-fetch.ts +146 -0
  32. package/src/docs-list.ts +131 -0
  33. package/src/docs.ts +54 -0
  34. package/src/index.ts +132 -0
  35. package/src/init.ts +64 -0
  36. package/src/lib/auth.ts +83 -0
  37. package/src/lib/config.ts +111 -0
  38. package/src/lib/custom-types-api.ts +438 -0
  39. package/src/lib/field-path.ts +81 -0
  40. package/src/lib/file.ts +49 -0
  41. package/src/lib/framework.ts +143 -0
  42. package/src/lib/json.ts +3 -0
  43. package/src/lib/request.ts +116 -0
  44. package/src/lib/slice.ts +115 -0
  45. package/src/lib/string.ts +6 -0
  46. package/src/lib/url.ts +25 -0
  47. package/src/locale-add.ts +116 -0
  48. package/src/locale-list.ts +107 -0
  49. package/src/locale-remove.ts +88 -0
  50. package/src/locale-set-default.ts +131 -0
  51. package/src/locale.ts +60 -0
  52. package/src/login.ts +152 -0
  53. package/src/logout.ts +36 -0
  54. package/src/page-type-add-field-boolean.ts +238 -0
  55. package/src/page-type-add-field-color.ts +224 -0
  56. package/src/page-type-add-field-date.ts +227 -0
  57. package/src/page-type-add-field-embed.ts +224 -0
  58. package/src/page-type-add-field-geo-point.ts +221 -0
  59. package/src/page-type-add-field-group.ts +198 -0
  60. package/src/page-type-add-field-image.ts +224 -0
  61. package/src/page-type-add-field-key-text.ts +224 -0
  62. package/src/page-type-add-field-link.ts +247 -0
  63. package/src/page-type-add-field-number.ts +256 -0
  64. package/src/page-type-add-field-rich-text.ts +248 -0
  65. package/src/page-type-add-field-select.ts +230 -0
  66. package/src/page-type-add-field-timestamp.ts +227 -0
  67. package/src/page-type-add-field-uid.ts +207 -0
  68. package/src/page-type-add-field.ts +116 -0
  69. package/src/page-type-connect-slice.ts +214 -0
  70. package/src/page-type-create.ts +161 -0
  71. package/src/page-type-disconnect-slice.ts +171 -0
  72. package/src/page-type-list.ts +109 -0
  73. package/src/page-type-remove-field.ts +171 -0
  74. package/src/page-type-remove.ts +138 -0
  75. package/src/page-type-set-name.ts +138 -0
  76. package/src/page-type-set-repeatable.ts +147 -0
  77. package/src/page-type-view.ts +118 -0
  78. package/src/page-type.ts +90 -0
  79. package/src/preview-add.ts +126 -0
  80. package/src/preview-get-simulator.ts +104 -0
  81. package/src/preview-list.ts +106 -0
  82. package/src/preview-remove-simulator.ts +80 -0
  83. package/src/preview-remove.ts +109 -0
  84. package/src/preview-set-name.ts +137 -0
  85. package/src/preview-set-simulator.ts +116 -0
  86. package/src/preview.ts +75 -0
  87. package/src/pull.ts +242 -0
  88. package/src/push.ts +405 -0
  89. package/src/repo-create.ts +195 -0
  90. package/src/repo-get-access.ts +86 -0
  91. package/src/repo-list.ts +100 -0
  92. package/src/repo-set-access.ts +100 -0
  93. package/src/repo-set-name.ts +102 -0
  94. package/src/repo-view.ts +113 -0
  95. package/src/repo.ts +70 -0
  96. package/src/slice-add-field-boolean.ts +240 -0
  97. package/src/slice-add-field-color.ts +226 -0
  98. package/src/slice-add-field-date.ts +226 -0
  99. package/src/slice-add-field-embed.ts +226 -0
  100. package/src/slice-add-field-geo-point.ts +223 -0
  101. package/src/slice-add-field-group.ts +191 -0
  102. package/src/slice-add-field-image.ts +223 -0
  103. package/src/slice-add-field-key-text.ts +226 -0
  104. package/src/slice-add-field-link.ts +245 -0
  105. package/src/slice-add-field-number.ts +226 -0
  106. package/src/slice-add-field-rich-text.ts +250 -0
  107. package/src/slice-add-field-select.ts +232 -0
  108. package/src/slice-add-field-timestamp.ts +226 -0
  109. package/src/slice-add-field.ts +111 -0
  110. package/src/slice-add-variation.ts +139 -0
  111. package/src/slice-create.ts +203 -0
  112. package/src/slice-list-variations.ts +67 -0
  113. package/src/slice-list.ts +88 -0
  114. package/src/slice-remove-field.ts +122 -0
  115. package/src/slice-remove-variation.ts +112 -0
  116. package/src/slice-remove.ts +91 -0
  117. package/src/slice-rename.ts +122 -0
  118. package/src/slice-set-screenshot.ts +235 -0
  119. package/src/slice-view.ts +80 -0
  120. package/src/slice.ts +95 -0
  121. package/src/status.ts +873 -0
  122. package/src/token-create.ts +203 -0
  123. package/src/token-delete.ts +182 -0
  124. package/src/token-list.ts +223 -0
  125. package/src/token-set-name.ts +193 -0
  126. package/src/token.ts +60 -0
  127. package/src/webhook-add-header.ts +118 -0
  128. package/src/webhook-create.ts +152 -0
  129. package/src/webhook-disable.ts +109 -0
  130. package/src/webhook-enable.ts +132 -0
  131. package/src/webhook-list.ts +93 -0
  132. package/src/webhook-remove-header.ts +117 -0
  133. package/src/webhook-remove.ts +106 -0
  134. package/src/webhook-set-triggers.ts +148 -0
  135. package/src/webhook-status.ts +90 -0
  136. package/src/webhook-test.ts +106 -0
  137. package/src/webhook-view.ts +147 -0
  138. package/src/webhook.ts +95 -0
  139. package/src/whoami.ts +62 -0
@@ -0,0 +1,211 @@
1
+ import type { CustomType, Select } from "@prismicio/types-internal/lib/customtypes";
2
+
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import { parseArgs } from "node:util";
5
+ import * as v from "valibot";
6
+
7
+ import { buildTypes } from "./codegen-types";
8
+ import { findUpward } from "./lib/file";
9
+ import { findGroupInTab, isGroupField, parseFieldPath, validateNestedFieldPath } from "./lib/field-path";
10
+ import { stringify } from "./lib/json";
11
+ import { humanReadable } from "./lib/string";
12
+
13
+ const HELP = `
14
+ Add a select (dropdown) field to an existing custom type.
15
+
16
+ USAGE
17
+ prismic custom-type add-field select <type-id> <field-id> [flags]
18
+
19
+ ARGUMENTS
20
+ type-id Custom type identifier (required)
21
+ field-id Field identifier (required)
22
+
23
+ FLAGS
24
+ -t, --tab string Target tab (default: first existing tab, or "Main")
25
+ -l, --label string Display label for the field (inferred from field-id if omitted)
26
+ -p, --placeholder string Placeholder text
27
+ --option string Add an option (can be used multiple times)
28
+ --default string Default selected value
29
+ --types string Output file for generated types (default: "prismicio-types.d.ts")
30
+ -h, --help Show help for command
31
+
32
+ EXAMPLES
33
+ prismic custom-type add-field select homepage layout --option "full" --option "sidebar"
34
+ prismic custom-type add-field select product size --option "small" --option "medium" --option "large" --default "medium"
35
+ prismic custom-type add-field select article status --option "draft" --option "published" --label "Status"
36
+ `.trim();
37
+
38
+ const CustomTypeSchema = v.object({
39
+ id: v.string(),
40
+ label: v.string(),
41
+ repeatable: v.boolean(),
42
+ status: v.boolean(),
43
+ format: v.string(),
44
+ json: v.record(v.string(), v.record(v.string(), v.unknown())),
45
+ });
46
+
47
+ export async function customTypeAddFieldSelect(): Promise<void> {
48
+ const {
49
+ values: { help, tab, label, placeholder, option, default: defaultValue, types },
50
+ positionals: [typeId, fieldId],
51
+ } = parseArgs({
52
+ args: process.argv.slice(5), // skip: node, script, "custom-type", "add-field", "select"
53
+ options: {
54
+ tab: { type: "string", short: "t" },
55
+ label: { type: "string", short: "l" },
56
+ placeholder: { type: "string", short: "p" },
57
+ option: { type: "string", multiple: true },
58
+ default: { type: "string" },
59
+ types: { type: "string" },
60
+ help: { type: "boolean", short: "h" },
61
+ },
62
+ allowPositionals: true,
63
+ });
64
+
65
+ if (help) {
66
+ console.info(HELP);
67
+ return;
68
+ }
69
+
70
+ if (!typeId) {
71
+ console.error("Missing required argument: type-id\n");
72
+ console.error("Usage: prismic custom-type add-field select <type-id> <field-id>");
73
+ process.exitCode = 1;
74
+ return;
75
+ }
76
+
77
+ if (!fieldId) {
78
+ console.error("Missing required argument: field-id\n");
79
+ console.error("Usage: prismic custom-type add-field select <type-id> <field-id>");
80
+ process.exitCode = 1;
81
+ return;
82
+ }
83
+
84
+ // Parse and validate field path
85
+ const fieldPath = parseFieldPath(fieldId);
86
+ const pathValidation = validateNestedFieldPath(fieldPath);
87
+ if (!pathValidation.ok) {
88
+ console.error(pathValidation.error);
89
+ process.exitCode = 1;
90
+ return;
91
+ }
92
+
93
+ // Find the custom type file
94
+ const projectRoot = await findUpward("package.json");
95
+ if (!projectRoot) {
96
+ console.error("Could not find project root (no package.json found)");
97
+ process.exitCode = 1;
98
+ return;
99
+ }
100
+
101
+ const modelPath = new URL(`customtypes/${typeId}/index.json`, projectRoot);
102
+
103
+ // Read and parse the model
104
+ let model: CustomType;
105
+ try {
106
+ const contents = await readFile(modelPath, "utf8");
107
+ const result = v.safeParse(CustomTypeSchema, JSON.parse(contents));
108
+ if (!result.success) {
109
+ console.error(`Invalid custom type model: ${modelPath.href}`);
110
+ process.exitCode = 1;
111
+ return;
112
+ }
113
+ model = result.output as CustomType;
114
+ } catch (error) {
115
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
116
+ console.error(`Custom type not found: ${typeId}\n`);
117
+ console.error(`Create it first with: prismic custom-type create ${typeId}`);
118
+ process.exitCode = 1;
119
+ return;
120
+ }
121
+ if (error instanceof Error) {
122
+ console.error(`Failed to read custom type: ${error.message}`);
123
+ } else {
124
+ console.error("Failed to read custom type");
125
+ }
126
+ process.exitCode = 1;
127
+ return;
128
+ }
129
+
130
+ // Determine target tab
131
+ const existingTabs = Object.keys(model.json);
132
+ const targetTab = tab ?? existingTabs[0] ?? "Main";
133
+
134
+ // Initialize tab if it doesn't exist
135
+ if (!model.json[targetTab]) {
136
+ model.json[targetTab] = {};
137
+ }
138
+
139
+ // Build field definition
140
+ const fieldDefinition: Select = {
141
+ type: "Select",
142
+ config: {
143
+ label: label ?? humanReadable(fieldPath.type === "nested" ? fieldPath.nestedFieldId : fieldId),
144
+ ...(placeholder && { placeholder }),
145
+ ...(option && option.length > 0 && { options: option }),
146
+ ...(defaultValue && { default_value: defaultValue }),
147
+ },
148
+ };
149
+
150
+ // Add field to model
151
+ if (fieldPath.type === "nested") {
152
+ const groupResult = findGroupInTab(model.json[targetTab], fieldPath.groupId, targetTab);
153
+ if (!groupResult.ok) {
154
+ console.error(groupResult.error);
155
+ process.exitCode = 1;
156
+ return;
157
+ }
158
+ if (groupResult.group.config.fields[fieldPath.nestedFieldId]) {
159
+ console.error(`Field "${fieldPath.nestedFieldId}" already exists in group "${fieldPath.groupId}"`);
160
+ process.exitCode = 1;
161
+ return;
162
+ }
163
+ groupResult.group.config.fields[fieldPath.nestedFieldId] = fieldDefinition;
164
+ } else {
165
+ for (const [tabName, tabFields] of Object.entries(model.json)) {
166
+ if (tabFields[fieldId]) {
167
+ console.error(`Field "${fieldId}" already exists in tab "${tabName}"`);
168
+ process.exitCode = 1;
169
+ return;
170
+ }
171
+ for (const [groupFieldId, groupField] of Object.entries(tabFields)) {
172
+ if (isGroupField(groupField) && groupField.config.fields[fieldId]) {
173
+ console.error(`Field "${fieldId}" already exists in group "${groupFieldId}" in tab "${tabName}"`);
174
+ process.exitCode = 1;
175
+ return;
176
+ }
177
+ }
178
+ }
179
+ model.json[targetTab][fieldId] = fieldDefinition;
180
+ }
181
+
182
+ // Write updated model
183
+ try {
184
+ await writeFile(modelPath, stringify(model));
185
+ } catch (error) {
186
+ if (error instanceof Error) {
187
+ console.error(`Failed to update custom type: ${error.message}`);
188
+ } else {
189
+ console.error("Failed to update custom type");
190
+ }
191
+ process.exitCode = 1;
192
+ return;
193
+ }
194
+
195
+ if (fieldPath.type === "nested") {
196
+ console.info(`Added field "${fieldPath.nestedFieldId}" (Select) to group "${fieldPath.groupId}" in ${typeId}`);
197
+ } else {
198
+ console.info(`Added field "${fieldId}" (Select) to "${targetTab}" tab in ${typeId}`);
199
+ }
200
+
201
+ try {
202
+ await buildTypes({ output: types });
203
+ console.info(`Updated types in ${types ?? "prismicio-types.d.ts"}`);
204
+ } catch (error) {
205
+ console.warn(`Could not generate types: ${error instanceof Error ? error.message : error}`);
206
+ }
207
+
208
+ console.info();
209
+ console.info("Next: Add more fields with `prismic custom-type add-field`");
210
+ console.info(" Run `prismic status` when done to find next steps");
211
+ }
@@ -0,0 +1,208 @@
1
+ import type { CustomType, Timestamp } from "@prismicio/types-internal/lib/customtypes";
2
+
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import { parseArgs } from "node:util";
5
+ import * as v from "valibot";
6
+
7
+ import { buildTypes } from "./codegen-types";
8
+ import { findUpward } from "./lib/file";
9
+ import { findGroupInTab, isGroupField, parseFieldPath, validateNestedFieldPath } from "./lib/field-path";
10
+ import { stringify } from "./lib/json";
11
+ import { humanReadable } from "./lib/string";
12
+
13
+ const HELP = `
14
+ Add a timestamp (date and time) field to an existing custom type.
15
+
16
+ USAGE
17
+ prismic custom-type add-field timestamp <type-id> <field-id> [flags]
18
+
19
+ ARGUMENTS
20
+ type-id Custom type identifier (required)
21
+ field-id Field identifier (required)
22
+
23
+ FLAGS
24
+ -t, --tab string Target tab (default: first existing tab, or "Main")
25
+ -l, --label string Display label for the field (inferred from field-id if omitted)
26
+ -p, --placeholder string Placeholder text
27
+ --default string Default timestamp value (ISO 8601 format)
28
+ --types string Output file for generated types (default: "prismicio-types.d.ts")
29
+ -h, --help Show help for command
30
+
31
+ EXAMPLES
32
+ prismic custom-type add-field timestamp homepage event_time
33
+ prismic custom-type add-field timestamp event start --tab "Schedule"
34
+ prismic custom-type add-field timestamp article published_at --label "Published At"
35
+ `.trim();
36
+
37
+ const CustomTypeSchema = v.object({
38
+ id: v.string(),
39
+ label: v.string(),
40
+ repeatable: v.boolean(),
41
+ status: v.boolean(),
42
+ format: v.string(),
43
+ json: v.record(v.string(), v.record(v.string(), v.unknown())),
44
+ });
45
+
46
+ export async function customTypeAddFieldTimestamp(): Promise<void> {
47
+ const {
48
+ values: { help, tab, label, placeholder, default: defaultValue, types },
49
+ positionals: [typeId, fieldId],
50
+ } = parseArgs({
51
+ args: process.argv.slice(5), // skip: node, script, "custom-type", "add-field", "timestamp"
52
+ options: {
53
+ tab: { type: "string", short: "t" },
54
+ label: { type: "string", short: "l" },
55
+ placeholder: { type: "string", short: "p" },
56
+ default: { type: "string" },
57
+ types: { type: "string" },
58
+ help: { type: "boolean", short: "h" },
59
+ },
60
+ allowPositionals: true,
61
+ });
62
+
63
+ if (help) {
64
+ console.info(HELP);
65
+ return;
66
+ }
67
+
68
+ if (!typeId) {
69
+ console.error("Missing required argument: type-id\n");
70
+ console.error("Usage: prismic custom-type add-field timestamp <type-id> <field-id>");
71
+ process.exitCode = 1;
72
+ return;
73
+ }
74
+
75
+ if (!fieldId) {
76
+ console.error("Missing required argument: field-id\n");
77
+ console.error("Usage: prismic custom-type add-field timestamp <type-id> <field-id>");
78
+ process.exitCode = 1;
79
+ return;
80
+ }
81
+
82
+ // Parse and validate field path
83
+ const fieldPath = parseFieldPath(fieldId);
84
+ const pathValidation = validateNestedFieldPath(fieldPath);
85
+ if (!pathValidation.ok) {
86
+ console.error(pathValidation.error);
87
+ process.exitCode = 1;
88
+ return;
89
+ }
90
+
91
+ // Find the custom type file
92
+ const projectRoot = await findUpward("package.json");
93
+ if (!projectRoot) {
94
+ console.error("Could not find project root (no package.json found)");
95
+ process.exitCode = 1;
96
+ return;
97
+ }
98
+
99
+ const modelPath = new URL(`customtypes/${typeId}/index.json`, projectRoot);
100
+
101
+ // Read and parse the model
102
+ let model: CustomType;
103
+ try {
104
+ const contents = await readFile(modelPath, "utf8");
105
+ const result = v.safeParse(CustomTypeSchema, JSON.parse(contents));
106
+ if (!result.success) {
107
+ console.error(`Invalid custom type model: ${modelPath.href}`);
108
+ process.exitCode = 1;
109
+ return;
110
+ }
111
+ model = result.output as CustomType;
112
+ } catch (error) {
113
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
114
+ console.error(`Custom type not found: ${typeId}\n`);
115
+ console.error(`Create it first with: prismic custom-type create ${typeId}`);
116
+ process.exitCode = 1;
117
+ return;
118
+ }
119
+ if (error instanceof Error) {
120
+ console.error(`Failed to read custom type: ${error.message}`);
121
+ } else {
122
+ console.error("Failed to read custom type");
123
+ }
124
+ process.exitCode = 1;
125
+ return;
126
+ }
127
+
128
+ // Determine target tab
129
+ const existingTabs = Object.keys(model.json);
130
+ const targetTab = tab ?? existingTabs[0] ?? "Main";
131
+
132
+ // Initialize tab if it doesn't exist
133
+ if (!model.json[targetTab]) {
134
+ model.json[targetTab] = {};
135
+ }
136
+
137
+ // Build field definition
138
+ const fieldDefinition: Timestamp = {
139
+ type: "Timestamp",
140
+ config: {
141
+ label: label ?? humanReadable(fieldPath.type === "nested" ? fieldPath.nestedFieldId : fieldId),
142
+ ...(placeholder && { placeholder }),
143
+ ...(defaultValue && { default: defaultValue }),
144
+ },
145
+ };
146
+
147
+ // Add field to model
148
+ if (fieldPath.type === "nested") {
149
+ const groupResult = findGroupInTab(model.json[targetTab], fieldPath.groupId, targetTab);
150
+ if (!groupResult.ok) {
151
+ console.error(groupResult.error);
152
+ process.exitCode = 1;
153
+ return;
154
+ }
155
+ if (groupResult.group.config.fields[fieldPath.nestedFieldId]) {
156
+ console.error(`Field "${fieldPath.nestedFieldId}" already exists in group "${fieldPath.groupId}"`);
157
+ process.exitCode = 1;
158
+ return;
159
+ }
160
+ groupResult.group.config.fields[fieldPath.nestedFieldId] = fieldDefinition;
161
+ } else {
162
+ for (const [tabName, tabFields] of Object.entries(model.json)) {
163
+ if (tabFields[fieldId]) {
164
+ console.error(`Field "${fieldId}" already exists in tab "${tabName}"`);
165
+ process.exitCode = 1;
166
+ return;
167
+ }
168
+ for (const [groupFieldId, groupField] of Object.entries(tabFields)) {
169
+ if (isGroupField(groupField) && groupField.config.fields[fieldId]) {
170
+ console.error(`Field "${fieldId}" already exists in group "${groupFieldId}" in tab "${tabName}"`);
171
+ process.exitCode = 1;
172
+ return;
173
+ }
174
+ }
175
+ }
176
+ model.json[targetTab][fieldId] = fieldDefinition;
177
+ }
178
+
179
+ // Write updated model
180
+ try {
181
+ await writeFile(modelPath, stringify(model));
182
+ } catch (error) {
183
+ if (error instanceof Error) {
184
+ console.error(`Failed to update custom type: ${error.message}`);
185
+ } else {
186
+ console.error("Failed to update custom type");
187
+ }
188
+ process.exitCode = 1;
189
+ return;
190
+ }
191
+
192
+ if (fieldPath.type === "nested") {
193
+ console.info(`Added field "${fieldPath.nestedFieldId}" (Timestamp) to group "${fieldPath.groupId}" in ${typeId}`);
194
+ } else {
195
+ console.info(`Added field "${fieldId}" (Timestamp) to "${targetTab}" tab in ${typeId}`);
196
+ }
197
+
198
+ try {
199
+ await buildTypes({ output: types });
200
+ console.info(`Updated types in ${types ?? "prismicio-types.d.ts"}`);
201
+ } catch (error) {
202
+ console.warn(`Could not generate types: ${error instanceof Error ? error.message : error}`);
203
+ }
204
+
205
+ console.info();
206
+ console.info("Next: Add more fields with `prismic custom-type add-field`");
207
+ console.info(" Run `prismic status` when done to find next steps");
208
+ }
@@ -0,0 +1,188 @@
1
+ import type { CustomType, UID } from "@prismicio/types-internal/lib/customtypes";
2
+
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import { parseArgs } from "node:util";
5
+ import * as v from "valibot";
6
+
7
+ import { buildTypes } from "./codegen-types";
8
+ import { findUpward } from "./lib/file";
9
+ import { parseFieldPath, validateNestedFieldPath } from "./lib/field-path";
10
+ import { stringify } from "./lib/json";
11
+ import { humanReadable } from "./lib/string";
12
+
13
+ const HELP = `
14
+ Add a UID (unique identifier) field to an existing custom type.
15
+
16
+ USAGE
17
+ prismic custom-type add-field uid <type-id> <field-id> [flags]
18
+
19
+ ARGUMENTS
20
+ type-id Custom type identifier (required)
21
+ field-id Field identifier (required)
22
+
23
+ FLAGS
24
+ -t, --tab string Target tab (default: first existing tab, or "Main")
25
+ -l, --label string Display label for the field (inferred from field-id if omitted)
26
+ -p, --placeholder string Placeholder text
27
+ --types string Output file for generated types (default: "prismicio-types.d.ts")
28
+ -h, --help Show help for command
29
+
30
+ EXAMPLES
31
+ prismic custom-type add-field uid page uid
32
+ prismic custom-type add-field uid article slug --label "URL Slug"
33
+ prismic custom-type add-field uid product sku --placeholder "Enter unique SKU"
34
+ `.trim();
35
+
36
+ const CustomTypeSchema = v.object({
37
+ id: v.string(),
38
+ label: v.string(),
39
+ repeatable: v.boolean(),
40
+ status: v.boolean(),
41
+ format: v.string(),
42
+ json: v.record(v.string(), v.record(v.string(), v.unknown())),
43
+ });
44
+
45
+ export async function customTypeAddFieldUid(): Promise<void> {
46
+ const {
47
+ values: { help, tab, label, placeholder, types },
48
+ positionals: [typeId, fieldId],
49
+ } = parseArgs({
50
+ args: process.argv.slice(5), // skip: node, script, "custom-type", "add-field", "uid"
51
+ options: {
52
+ tab: { type: "string", short: "t" },
53
+ label: { type: "string", short: "l" },
54
+ placeholder: { type: "string", short: "p" },
55
+ types: { type: "string" },
56
+ help: { type: "boolean", short: "h" },
57
+ },
58
+ allowPositionals: true,
59
+ });
60
+
61
+ if (help) {
62
+ console.info(HELP);
63
+ return;
64
+ }
65
+
66
+ if (!typeId) {
67
+ console.error("Missing required argument: type-id\n");
68
+ console.error("Usage: prismic custom-type add-field uid <type-id> <field-id>");
69
+ process.exitCode = 1;
70
+ return;
71
+ }
72
+
73
+ if (!fieldId) {
74
+ console.error("Missing required argument: field-id\n");
75
+ console.error("Usage: prismic custom-type add-field uid <type-id> <field-id>");
76
+ process.exitCode = 1;
77
+ return;
78
+ }
79
+
80
+ // Parse and validate field path
81
+ const fieldPath = parseFieldPath(fieldId);
82
+ const pathValidation = validateNestedFieldPath(fieldPath);
83
+ if (!pathValidation.ok) {
84
+ console.error(pathValidation.error);
85
+ process.exitCode = 1;
86
+ return;
87
+ }
88
+
89
+ // UID fields cannot be nested in groups
90
+ if (fieldPath.type === "nested") {
91
+ console.error("UID fields cannot be nested inside groups");
92
+ process.exitCode = 1;
93
+ return;
94
+ }
95
+
96
+ // Find the custom type file
97
+ const projectRoot = await findUpward("package.json");
98
+ if (!projectRoot) {
99
+ console.error("Could not find project root (no package.json found)");
100
+ process.exitCode = 1;
101
+ return;
102
+ }
103
+
104
+ const modelPath = new URL(`customtypes/${typeId}/index.json`, projectRoot);
105
+
106
+ // Read and parse the model
107
+ let model: CustomType;
108
+ try {
109
+ const contents = await readFile(modelPath, "utf8");
110
+ const result = v.safeParse(CustomTypeSchema, JSON.parse(contents));
111
+ if (!result.success) {
112
+ console.error(`Invalid custom type model: ${modelPath.href}`);
113
+ process.exitCode = 1;
114
+ return;
115
+ }
116
+ model = result.output as CustomType;
117
+ } catch (error) {
118
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
119
+ console.error(`Custom type not found: ${typeId}\n`);
120
+ console.error(`Create it first with: prismic custom-type create ${typeId}`);
121
+ process.exitCode = 1;
122
+ return;
123
+ }
124
+ if (error instanceof Error) {
125
+ console.error(`Failed to read custom type: ${error.message}`);
126
+ } else {
127
+ console.error("Failed to read custom type");
128
+ }
129
+ process.exitCode = 1;
130
+ return;
131
+ }
132
+
133
+ // Determine target tab
134
+ const existingTabs = Object.keys(model.json);
135
+ const targetTab = tab ?? existingTabs[0] ?? "Main";
136
+
137
+ // Initialize tab if it doesn't exist
138
+ if (!model.json[targetTab]) {
139
+ model.json[targetTab] = {};
140
+ }
141
+
142
+ // Check if field already exists in any tab
143
+ for (const [tabName, tabFields] of Object.entries(model.json)) {
144
+ if (tabFields[fieldId]) {
145
+ console.error(`Field "${fieldId}" already exists in tab "${tabName}"`);
146
+ process.exitCode = 1;
147
+ return;
148
+ }
149
+ }
150
+
151
+ // Build field definition
152
+ const fieldDefinition: UID = {
153
+ type: "UID",
154
+ config: {
155
+ label: label ?? humanReadable(fieldId),
156
+ ...(placeholder && { placeholder }),
157
+ },
158
+ };
159
+
160
+ // Add field to model
161
+ model.json[targetTab][fieldId] = fieldDefinition;
162
+
163
+ // Write updated model
164
+ try {
165
+ await writeFile(modelPath, stringify(model));
166
+ } catch (error) {
167
+ if (error instanceof Error) {
168
+ console.error(`Failed to update custom type: ${error.message}`);
169
+ } else {
170
+ console.error("Failed to update custom type");
171
+ }
172
+ process.exitCode = 1;
173
+ return;
174
+ }
175
+
176
+ console.info(`Added field "${fieldId}" (UID) to "${targetTab}" tab in ${typeId}`);
177
+
178
+ try {
179
+ await buildTypes({ output: types });
180
+ console.info(`Updated types in ${types ?? "prismicio-types.d.ts"}`);
181
+ } catch (error) {
182
+ console.warn(`Could not generate types: ${error instanceof Error ? error.message : error}`);
183
+ }
184
+
185
+ console.info();
186
+ console.info("Next: Add more fields with `prismic custom-type add-field`");
187
+ console.info(" Run `prismic status` when done to find next steps");
188
+ }