@wp-typia/project-tools 0.20.1 → 0.21.0

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 (48) hide show
  1. package/dist/runtime/cli-add-block.js +1 -1
  2. package/dist/runtime/cli-add-shared.d.ts +73 -5
  3. package/dist/runtime/cli-add-shared.js +58 -11
  4. package/dist/runtime/cli-add-workspace-ability.js +11 -57
  5. package/dist/runtime/cli-add-workspace-admin-view.d.ts +23 -0
  6. package/dist/runtime/cli-add-workspace-admin-view.js +872 -0
  7. package/dist/runtime/cli-add-workspace-ai-anchors.js +2 -5
  8. package/dist/runtime/cli-add-workspace-ai-source-emitters.d.ts +0 -4
  9. package/dist/runtime/cli-add-workspace-ai-source-emitters.js +7 -17
  10. package/dist/runtime/cli-add-workspace-ai.js +4 -6
  11. package/dist/runtime/cli-add-workspace-assets.d.ts +13 -5
  12. package/dist/runtime/cli-add-workspace-assets.js +290 -106
  13. package/dist/runtime/cli-add-workspace-rest-anchors.js +2 -5
  14. package/dist/runtime/cli-add-workspace-rest-source-emitters.d.ts +0 -1
  15. package/dist/runtime/cli-add-workspace-rest-source-emitters.js +7 -14
  16. package/dist/runtime/cli-add-workspace-rest.js +4 -6
  17. package/dist/runtime/cli-add-workspace.d.ts +58 -1
  18. package/dist/runtime/cli-add-workspace.js +588 -18
  19. package/dist/runtime/cli-add.d.ts +1 -1
  20. package/dist/runtime/cli-add.js +1 -1
  21. package/dist/runtime/cli-core.d.ts +8 -5
  22. package/dist/runtime/cli-core.js +7 -4
  23. package/dist/runtime/cli-diagnostics.d.ts +84 -1
  24. package/dist/runtime/cli-diagnostics.js +90 -3
  25. package/dist/runtime/cli-doctor-workspace.js +552 -13
  26. package/dist/runtime/cli-doctor.d.ts +4 -2
  27. package/dist/runtime/cli-doctor.js +2 -1
  28. package/dist/runtime/cli-help.js +19 -9
  29. package/dist/runtime/cli-init.d.ts +67 -3
  30. package/dist/runtime/cli-init.js +603 -64
  31. package/dist/runtime/cli-validation.js +4 -3
  32. package/dist/runtime/index.d.ts +9 -4
  33. package/dist/runtime/index.js +7 -3
  34. package/dist/runtime/package-json-types.d.ts +12 -0
  35. package/dist/runtime/package-json-types.js +1 -0
  36. package/dist/runtime/package-versions.d.ts +17 -2
  37. package/dist/runtime/package-versions.js +46 -1
  38. package/dist/runtime/php-utils.d.ts +16 -0
  39. package/dist/runtime/php-utils.js +59 -0
  40. package/dist/runtime/scaffold-answer-resolution.js +35 -10
  41. package/dist/runtime/scaffold-apply-utils.d.ts +2 -3
  42. package/dist/runtime/scaffold-apply-utils.js +3 -43
  43. package/dist/runtime/template-source-cache.d.ts +112 -0
  44. package/dist/runtime/template-source-cache.js +434 -0
  45. package/dist/runtime/template-source-seeds.js +333 -53
  46. package/dist/runtime/workspace-inventory.d.ts +43 -2
  47. package/dist/runtime/workspace-inventory.js +138 -5
  48. package/package.json +2 -2
@@ -0,0 +1,872 @@
1
+ import fs from "node:fs";
2
+ import { promises as fsp } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
5
+ import { resolveWorkspaceProject, } from "./workspace-project.js";
6
+ import { readWorkspaceInventory, appendWorkspaceInventoryEntries } from "./workspace-inventory.js";
7
+ import { PROJECT_TOOLS_PACKAGE_ROOT } from "./template-registry.js";
8
+ import { toPascalCase, toTitleCase } from "./string-case.js";
9
+ import { findPhpFunctionRange, hasPhpFunctionDefinition, quotePhpString, replacePhpFunctionDefinition, } from "./php-utils.js";
10
+ import { assertAdminViewDoesNotExist, assertValidGeneratedSlug, getWorkspaceBootstrapPath, normalizeBlockSlug, patchFile, quoteTsString, rollbackWorkspaceMutation, snapshotWorkspaceFiles, } from "./cli-add-shared.js";
11
+ const ADMIN_VIEW_SOURCE_KIND = "rest-resource";
12
+ const ADMIN_VIEWS_SCRIPT = "build/admin-views/index.js";
13
+ const ADMIN_VIEWS_ASSET = "build/admin-views/index.asset.php";
14
+ const ADMIN_VIEWS_STYLE = "build/admin-views/style-index.css";
15
+ const ADMIN_VIEWS_STYLE_RTL = "build/admin-views/style-index-rtl.css";
16
+ const ADMIN_VIEWS_PHP_GLOB = "/inc/admin-views/*.php";
17
+ const DEFAULT_WP_TYPIA_DATAVIEWS_VERSION = "^0.1.0";
18
+ const DEFAULT_WORDPRESS_DATAVIEWS_VERSION = "^14.1.0";
19
+ const require = createRequire(import.meta.url);
20
+ function toCamelCase(input) {
21
+ const pascalCase = toPascalCase(input);
22
+ return `${pascalCase.charAt(0).toLowerCase()}${pascalCase.slice(1)}`;
23
+ }
24
+ function normalizeVersionRange(value, fallback) {
25
+ const trimmed = value?.trim();
26
+ if (!trimmed || trimmed.startsWith("workspace:")) {
27
+ return fallback;
28
+ }
29
+ return /^[~^<>=]/u.test(trimmed) ? trimmed : `^${trimmed}`;
30
+ }
31
+ function readPackageManifestVersion(packageJsonPath) {
32
+ try {
33
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
34
+ return packageJson.version;
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ function detectJsonIndent(source) {
41
+ const indentMatch = /\n([ \t]+)"/u.exec(source);
42
+ return indentMatch?.[1] ?? 2;
43
+ }
44
+ function resolvePackageVersionRange(packageName, fallback, workspacePackageDirName) {
45
+ if (workspacePackageDirName) {
46
+ const workspaceVersion = readPackageManifestVersion(path.join(PROJECT_TOOLS_PACKAGE_ROOT, "..", workspacePackageDirName, "package.json"));
47
+ if (workspaceVersion) {
48
+ return normalizeVersionRange(workspaceVersion, fallback);
49
+ }
50
+ }
51
+ try {
52
+ return normalizeVersionRange(readPackageManifestVersion(require.resolve(`${packageName}/package.json`)), fallback);
53
+ }
54
+ catch {
55
+ return fallback;
56
+ }
57
+ }
58
+ function getAdminViewRelativeModuleSpecifier(adminViewSlug, workspaceFile) {
59
+ const adminViewDir = `src/admin-views/${adminViewSlug}`;
60
+ const normalizedFile = workspaceFile.replace(/\\/gu, "/");
61
+ const modulePath = normalizedFile.replace(/\.[cm]?[jt]sx?$/u, "");
62
+ const relativeModulePath = path.posix.relative(adminViewDir, modulePath);
63
+ return relativeModulePath.startsWith(".") ? relativeModulePath : `./${relativeModulePath}`;
64
+ }
65
+ function parseAdminViewSource(source) {
66
+ const trimmed = source?.trim();
67
+ if (!trimmed) {
68
+ return undefined;
69
+ }
70
+ const [kind, slug, extra] = trimmed.split(":");
71
+ if (kind !== ADMIN_VIEW_SOURCE_KIND || !slug || extra !== undefined) {
72
+ throw new Error("Admin view source must use `rest-resource:<slug>` for now.");
73
+ }
74
+ return {
75
+ kind,
76
+ slug: assertValidGeneratedSlug("Admin view source slug", normalizeBlockSlug(slug), "wp-typia add admin-view <name> --source rest-resource:<slug>"),
77
+ };
78
+ }
79
+ function resolveRestResourceSource(restResources, source) {
80
+ if (!source) {
81
+ return undefined;
82
+ }
83
+ const restResource = restResources.find((entry) => entry.slug === source.slug);
84
+ if (!restResource) {
85
+ throw new Error(`Unknown REST resource source "${source.slug}". Choose one of: ${restResources
86
+ .map((entry) => entry.slug)
87
+ .join(", ") || "<none>"}.`);
88
+ }
89
+ if (!restResource.methods.includes("list")) {
90
+ throw new Error(`REST resource source "${source.slug}" must include the list method for DataViews pagination.`);
91
+ }
92
+ return restResource;
93
+ }
94
+ function buildAdminViewConfigEntry(adminViewSlug, source) {
95
+ return [
96
+ "\t{",
97
+ `\t\tfile: ${quoteTsString(`src/admin-views/${adminViewSlug}/index.tsx`)},`,
98
+ `\t\tphpFile: ${quoteTsString(`inc/admin-views/${adminViewSlug}.php`)},`,
99
+ `\t\tslug: ${quoteTsString(adminViewSlug)},`,
100
+ source ? `\t\tsource: ${quoteTsString(`${source.kind}:${source.slug}`)},` : null,
101
+ "\t},",
102
+ ]
103
+ .filter((line) => typeof line === "string")
104
+ .join("\n");
105
+ }
106
+ function buildAdminViewRegistrySource(adminViewSlugs) {
107
+ const importLines = adminViewSlugs
108
+ .map((adminViewSlug) => `import './${adminViewSlug}';`)
109
+ .join("\n");
110
+ return `${importLines}${importLines ? "\n\n" : ""}// wp-typia add admin-view entries\n`;
111
+ }
112
+ function buildAdminViewTypesSource(adminViewSlug, restResource) {
113
+ const pascalName = toPascalCase(adminViewSlug);
114
+ const itemTypeName = `${pascalName}AdminViewItem`;
115
+ const dataSetTypeName = `${pascalName}AdminViewDataSet`;
116
+ if (restResource) {
117
+ const restPascalName = toPascalCase(restResource.slug);
118
+ const restTypesModule = getAdminViewRelativeModuleSpecifier(adminViewSlug, restResource.typesFile);
119
+ return `import type { ${restPascalName}Record } from ${quoteTsString(restTypesModule)};
120
+
121
+ export type ${itemTypeName} = ${restPascalName}Record;
122
+
123
+ export interface ${dataSetTypeName} {
124
+ \titems: ${itemTypeName}[];
125
+ \tpaginationInfo: {
126
+ \t\ttotalItems: number;
127
+ \t\ttotalPages: number;
128
+ \t};
129
+ }
130
+ `;
131
+ }
132
+ return `export type ${pascalName}AdminViewStatus = 'draft' | 'published';
133
+
134
+ export interface ${itemTypeName} {
135
+ \tid: number;
136
+ \towner: string;
137
+ \tstatus: ${pascalName}AdminViewStatus;
138
+ \ttitle: string;
139
+ \tupdatedAt: string;
140
+ }
141
+
142
+ export interface ${dataSetTypeName} {
143
+ \titems: ${itemTypeName}[];
144
+ \tpaginationInfo: {
145
+ \t\ttotalItems: number;
146
+ \t\ttotalPages: number;
147
+ \t};
148
+ }
149
+ `;
150
+ }
151
+ function buildAdminViewConfigSource(adminViewSlug, textDomain, restResource) {
152
+ const pascalName = toPascalCase(adminViewSlug);
153
+ const camelName = toCamelCase(adminViewSlug);
154
+ const itemTypeName = `${pascalName}AdminViewItem`;
155
+ const dataViewsName = `${camelName}AdminDataViews`;
156
+ const defaultViewFields = restResource
157
+ ? "['id']"
158
+ : "['title', 'status', 'updatedAt']";
159
+ const searchEnabled = restResource ? "false" : "true";
160
+ const titleFieldSource = restResource ? "" : "\ttitleField: 'title',\n";
161
+ const defaultViewEnhancementsSource = restResource
162
+ ? ""
163
+ : `\t\tsort: {
164
+ \t\t\tdirection: 'desc',
165
+ \t\t\tfield: 'updatedAt',
166
+ \t\t},
167
+ \t\ttitleField: 'title',
168
+ `;
169
+ const additionalFieldsSource = restResource
170
+ ? "\t\t// REST-backed screens start with the guaranteed ID column. Add project-owned fields here once they are declared on the REST record type."
171
+ : `\t\towner: {
172
+ \t\t\tlabel: __( 'Owner', ${quoteTsString(textDomain)} ),
173
+ \t\t\tschema: { type: 'string' },
174
+ \t\t},
175
+ \t\tstatus: {
176
+ \t\t\tfilterBy: { operators: ['isAny', 'isNone'] },
177
+ \t\t\tlabel: __( 'Status', ${quoteTsString(textDomain)} ),
178
+ \t\t\tschema: {
179
+ \t\t\t\tenum: ['draft', 'published'],
180
+ \t\t\t\tenumLabels: {
181
+ \t\t\t\t\tdraft: __( 'Draft', ${quoteTsString(textDomain)} ),
182
+ \t\t\t\t\tpublished: __( 'Published', ${quoteTsString(textDomain)} ),
183
+ \t\t\t\t},
184
+ \t\t\t\ttype: 'string',
185
+ \t\t\t},
186
+ \t\t},
187
+ \t\ttitle: {
188
+ \t\t\tenableGlobalSearch: true,
189
+ \t\t\tenableSorting: true,
190
+ \t\t\tlabel: __( 'Title', ${quoteTsString(textDomain)} ),
191
+ \t\t\tschema: { type: 'string' },
192
+ \t\t},
193
+ \t\tupdatedAt: {
194
+ \t\t\tenableSorting: true,
195
+ \t\t\tlabel: __( 'Updated', ${quoteTsString(textDomain)} ),
196
+ \t\t\tschema: { format: 'date-time', type: 'string' },
197
+ \t\t\ttype: 'datetime',
198
+ \t\t},`;
199
+ return `import { defineDataViews } from '@wp-typia/dataviews';
200
+ import { __ } from '@wordpress/i18n';
201
+
202
+ import type { ${itemTypeName} } from './types';
203
+
204
+ export const ${dataViewsName} = defineDataViews<${itemTypeName}>({
205
+ \tidField: 'id',
206
+ \tsearch: ${searchEnabled},
207
+ \tsearchLabel: __( 'Search records', ${quoteTsString(textDomain)} ),
208
+ ${titleFieldSource}
209
+ \tdefaultView: {
210
+ \t\tfields: ${defaultViewFields},
211
+ \t\tpage: 1,
212
+ \t\tperPage: 10,
213
+ ${defaultViewEnhancementsSource}
214
+ \t\ttype: 'table',
215
+ \t},
216
+ \tfields: {
217
+ \t\tid: {
218
+ \t\t\tenableHiding: false,
219
+ \t\t\tlabel: __( 'ID', ${quoteTsString(textDomain)} ),
220
+ \t\t\treadOnly: true,
221
+ \t\t\tschema: { type: 'integer' },
222
+ \t\t},
223
+ ${additionalFieldsSource}
224
+ \t},
225
+ });
226
+ `;
227
+ }
228
+ function buildDefaultAdminViewDataSource(adminViewSlug) {
229
+ const pascalName = toPascalCase(adminViewSlug);
230
+ const camelName = toCamelCase(adminViewSlug);
231
+ const title = toTitleCase(adminViewSlug);
232
+ const itemTypeName = `${pascalName}AdminViewItem`;
233
+ const dataSetTypeName = `${pascalName}AdminViewDataSet`;
234
+ const queryTypeName = `${pascalName}AdminViewQuery`;
235
+ const dataViewsName = `${camelName}AdminDataViews`;
236
+ const fetchName = `fetch${pascalName}AdminViewData`;
237
+ return `import type { DataViewsView } from '@wp-typia/dataviews';
238
+
239
+ import { ${dataViewsName} } from './config';
240
+ import type { ${dataSetTypeName}, ${itemTypeName} } from './types';
241
+
242
+ export interface ${queryTypeName} {
243
+ \tpage?: number;
244
+ \tperPage?: number;
245
+ \tsearch?: string;
246
+ }
247
+
248
+ const STARTER_ITEMS: ${itemTypeName}[] = [
249
+ \t{
250
+ \t\tid: 1,
251
+ \t\towner: 'Editorial',
252
+ \t\tstatus: 'published',
253
+ \t\ttitle: ${quoteTsString(`${title} launch checklist`)},
254
+ \t\tupdatedAt: '2026-04-01T10:30:00Z',
255
+ \t},
256
+ \t{
257
+ \t\tid: 2,
258
+ \t\towner: 'Design',
259
+ \t\tstatus: 'draft',
260
+ \t\ttitle: ${quoteTsString(`${title} content refresh`)},
261
+ \t\tupdatedAt: '2026-04-03T14:15:00Z',
262
+ \t},
263
+ \t{
264
+ \t\tid: 3,
265
+ \t\towner: 'Operations',
266
+ \t\tstatus: 'published',
267
+ \t\ttitle: ${quoteTsString(`${title} support handoff`)},
268
+ \t\tupdatedAt: '2026-04-08T08:45:00Z',
269
+ \t},
270
+ ];
271
+
272
+ function matchesSearch(item: ${itemTypeName}, search: string | undefined): boolean {
273
+ \tif (!search) {
274
+ \t\treturn true;
275
+ \t}
276
+
277
+ \tconst needle = search.toLowerCase();
278
+ \treturn [item.title, item.owner, item.status].some((value) =>
279
+ \t\tvalue.toLowerCase().includes(needle),
280
+ \t);
281
+ }
282
+
283
+ export async function ${fetchName}(
284
+ \tview: DataViewsView<${itemTypeName}>,
285
+ ): Promise<${dataSetTypeName}> {
286
+ \tconst query = ${dataViewsName}.toQueryArgs<${queryTypeName}>(view, {
287
+ \t\tperPageParam: 'perPage',
288
+ \t});
289
+ \tconst requestedPage = query.page ?? 1;
290
+ \tconst page = requestedPage > 0 ? requestedPage : 1;
291
+ \tconst requestedPerPage = query.perPage ?? view.perPage ?? 10;
292
+ \tconst perPage = requestedPerPage > 0 ? requestedPerPage : 10;
293
+ \tconst filteredItems = STARTER_ITEMS.filter((item) =>
294
+ \t\tmatchesSearch(item, query.search),
295
+ \t);
296
+ \tconst offset = (page - 1) * perPage;
297
+ \tconst items = filteredItems.slice(offset, offset + perPage);
298
+
299
+ \treturn {
300
+ \t\titems,
301
+ \t\tpaginationInfo: {
302
+ \t\t\ttotalItems: filteredItems.length,
303
+ \t\t\ttotalPages: Math.max(1, Math.ceil(filteredItems.length / perPage)),
304
+ \t\t},
305
+ \t};
306
+ }
307
+ `;
308
+ }
309
+ function buildRestAdminViewDataSource(adminViewSlug, restResource) {
310
+ const pascalName = toPascalCase(adminViewSlug);
311
+ const restPascalName = toPascalCase(restResource.slug);
312
+ const camelName = toCamelCase(adminViewSlug);
313
+ const itemTypeName = `${pascalName}AdminViewItem`;
314
+ const dataSetTypeName = `${pascalName}AdminViewDataSet`;
315
+ const dataViewsName = `${camelName}AdminDataViews`;
316
+ const fetchName = `fetch${pascalName}AdminViewData`;
317
+ const restApiModule = getAdminViewRelativeModuleSpecifier(adminViewSlug, restResource.apiFile);
318
+ const restTypesModule = getAdminViewRelativeModuleSpecifier(adminViewSlug, restResource.typesFile);
319
+ return `import type { DataViewsView } from '@wp-typia/dataviews';
320
+
321
+ import { listResource } from ${quoteTsString(restApiModule)};
322
+ import type { ${restPascalName}ListQuery } from ${quoteTsString(restTypesModule)};
323
+ import { ${dataViewsName} } from './config';
324
+ import type { ${dataSetTypeName}, ${itemTypeName} } from './types';
325
+
326
+ function resolveTotalPages(total: number, perPage: number | undefined): number {
327
+ \tconst resolvedPerPage = perPage && perPage > 0 ? perPage : 1;
328
+ \treturn Math.max(1, Math.ceil(total / resolvedPerPage));
329
+ }
330
+
331
+ export async function ${fetchName}(
332
+ \tview: DataViewsView<${itemTypeName}>,
333
+ ): Promise<${dataSetTypeName}> {
334
+ \tconst query = ${dataViewsName}.toQueryArgs<${restPascalName}ListQuery>(view, {
335
+ \t\tperPageParam: 'perPage',
336
+ \t\tsearchParam: false,
337
+ \t});
338
+ \tconst result = await listResource({
339
+ \t\tpage: query.page,
340
+ \t\tperPage: query.perPage,
341
+ \t});
342
+ \tif (!result.isValid || !result.data) {
343
+ \t\tthrow new Error('Unable to load REST resource records.');
344
+ \t}
345
+
346
+ \tconst response = result.data;
347
+
348
+ \treturn {
349
+ \t\titems: response.items,
350
+ \t\tpaginationInfo: {
351
+ \t\t\ttotalItems: response.total,
352
+ \t\t\ttotalPages: resolveTotalPages(response.total, response.perPage ?? query.perPage),
353
+ \t\t},
354
+ \t};
355
+ }
356
+ `;
357
+ }
358
+ function buildAdminViewScreenSource(adminViewSlug, textDomain) {
359
+ const pascalName = toPascalCase(adminViewSlug);
360
+ const camelName = toCamelCase(adminViewSlug);
361
+ const itemTypeName = `${pascalName}AdminViewItem`;
362
+ const dataSetTypeName = `${pascalName}AdminViewDataSet`;
363
+ const componentName = `${pascalName}AdminViewScreen`;
364
+ const dataViewsName = `${camelName}AdminDataViews`;
365
+ const fetchName = `fetch${pascalName}AdminViewData`;
366
+ const title = toTitleCase(adminViewSlug);
367
+ return `import type { DataViewsConfig, DataViewsView } from '@wp-typia/dataviews';
368
+ import { Button, Notice, Spinner } from '@wordpress/components';
369
+ import { useEffect, useState } from '@wordpress/element';
370
+ import { __ } from '@wordpress/i18n';
371
+ import { DataViews } from '@wordpress/dataviews/wp';
372
+
373
+ import { ${dataViewsName} } from './config';
374
+ import { ${fetchName} } from './data';
375
+ import type { ${dataSetTypeName}, ${itemTypeName} } from './types';
376
+
377
+ const TypedDataViews = DataViews as unknown as <TItem extends object>(
378
+ \tprops: DataViewsConfig<TItem>,
379
+ ) => ReturnType<typeof DataViews>;
380
+
381
+ const EMPTY_DATA_SET: ${dataSetTypeName} = {
382
+ \titems: [],
383
+ \tpaginationInfo: {
384
+ \t\ttotalItems: 0,
385
+ \t\ttotalPages: 1,
386
+ \t},
387
+ };
388
+
389
+ export function ${componentName}() {
390
+ \tconst [view, setView] = useState<DataViewsView<${itemTypeName}>>(
391
+ \t\t${dataViewsName}.defaultView,
392
+ \t);
393
+ \tconst [dataSet, setDataSet] = useState<${dataSetTypeName}>(EMPTY_DATA_SET);
394
+ \tconst [error, setError] = useState<string | null>(null);
395
+ \tconst [isLoading, setIsLoading] = useState(true);
396
+ \tconst [reloadToken, setReloadToken] = useState(0);
397
+
398
+ \tuseEffect(() => {
399
+ \t\tlet isCurrentRequest = true;
400
+ \t\tsetIsLoading(true);
401
+ \t\tsetError(null);
402
+
403
+ \t\tvoid ${fetchName}(view)
404
+ \t\t\t.then((nextDataSet) => {
405
+ \t\t\t\tif (isCurrentRequest) {
406
+ \t\t\t\t\tsetDataSet(nextDataSet);
407
+ \t\t\t\t}
408
+ \t\t\t})
409
+ \t\t\t.catch((nextError: unknown) => {
410
+ \t\t\t\tif (isCurrentRequest) {
411
+ \t\t\t\t\tsetError(
412
+ \t\t\t\t\t\tnextError instanceof Error
413
+ \t\t\t\t\t\t\t? nextError.message
414
+ \t\t\t\t\t\t\t: __( 'Unable to load records.', ${quoteTsString(textDomain)} ),
415
+ \t\t\t\t\t);
416
+ \t\t\t\t}
417
+ \t\t\t})
418
+ \t\t\t.finally(() => {
419
+ \t\t\t\tif (isCurrentRequest) {
420
+ \t\t\t\t\tsetIsLoading(false);
421
+ \t\t\t\t}
422
+ \t\t\t});
423
+
424
+ \t\treturn () => {
425
+ \t\t\tisCurrentRequest = false;
426
+ \t\t};
427
+ \t}, [reloadToken, view]);
428
+
429
+ \tconst config = ${dataViewsName}.createConfig({
430
+ \t\tdata: dataSet.items,
431
+ \t\tisLoading,
432
+ \t\tonChangeView: setView,
433
+ \t\tpaginationInfo: dataSet.paginationInfo,
434
+ \t\tview,
435
+ \t});
436
+
437
+ \treturn (
438
+ \t\t<div className="wp-typia-admin-view-screen">
439
+ \t\t\t<header className="wp-typia-admin-view-screen__header">
440
+ \t\t\t\t<div>
441
+ \t\t\t\t\t<p className="wp-typia-admin-view-screen__eyebrow">
442
+ \t\t\t\t\t\t{ __( 'DataViews admin screen', ${quoteTsString(textDomain)} ) }
443
+ \t\t\t\t\t</p>
444
+ \t\t\t\t\t<h1>{ __( ${quoteTsString(title)}, ${quoteTsString(textDomain)} ) }</h1>
445
+ \t\t\t\t\t<p>
446
+ \t\t\t\t\t\t{ __( 'Replace the fetcher in data.ts with your project data source when this screen graduates from scaffold to product UI.', ${quoteTsString(textDomain)} ) }
447
+ \t\t\t\t\t</p>
448
+ \t\t\t\t</div>
449
+ \t\t\t\t<div className="wp-typia-admin-view-screen__actions">
450
+ \t\t\t\t\t{ isLoading ? <Spinner /> : null }
451
+ \t\t\t\t\t<Button
452
+ \t\t\t\t\t\tisBusy={ isLoading }
453
+ \t\t\t\t\t\tonClick={ () => setReloadToken((token) => token + 1) }
454
+ \t\t\t\t\t\tvariant="secondary"
455
+ \t\t\t\t\t>
456
+ \t\t\t\t\t\t{ __( 'Reload', ${quoteTsString(textDomain)} ) }
457
+ \t\t\t\t\t</Button>
458
+ \t\t\t\t</div>
459
+ \t\t\t</header>
460
+ \t\t\t{ error ? (
461
+ \t\t\t\t<Notice isDismissible={ false } status="error">
462
+ \t\t\t\t\t{ error }
463
+ \t\t\t\t</Notice>
464
+ \t\t\t) : null }
465
+ \t\t\t<TypedDataViews<${itemTypeName}> { ...config } />
466
+ \t\t</div>
467
+ \t);
468
+ }
469
+ `;
470
+ }
471
+ function buildAdminViewEntrySource(adminViewSlug) {
472
+ const pascalName = toPascalCase(adminViewSlug);
473
+ const componentName = `${pascalName}AdminViewScreen`;
474
+ const rootId = `wp-typia-admin-view-${adminViewSlug}`;
475
+ return `import { createRoot } from '@wordpress/element';
476
+
477
+ import '@wordpress/dataviews/build-style/style.css';
478
+ import { ${componentName} } from './Screen';
479
+ import './style.scss';
480
+
481
+ const ROOT_ELEMENT_ID = ${quoteTsString(rootId)};
482
+
483
+ function mountAdminView() {
484
+ \tconst rootElement = document.getElementById(ROOT_ELEMENT_ID);
485
+ \tif (!rootElement) {
486
+ \t\treturn;
487
+ \t}
488
+
489
+ \tcreateRoot(rootElement).render(<${componentName} />);
490
+ }
491
+
492
+ if (document.readyState === 'loading') {
493
+ \tdocument.addEventListener('DOMContentLoaded', mountAdminView);
494
+ } else {
495
+ \tmountAdminView();
496
+ }
497
+ `;
498
+ }
499
+ function buildAdminViewStyleSource() {
500
+ return `.wp-typia-admin-view-screen {
501
+ \tbox-sizing: border-box;
502
+ \tmax-width: 1180px;
503
+ \tpadding: 24px 24px 48px 0;
504
+ }
505
+
506
+ .wp-typia-admin-view-screen__header {
507
+ \talign-items: flex-start;
508
+ \tdisplay: flex;
509
+ \tgap: 24px;
510
+ \tjustify-content: space-between;
511
+ \tmargin-bottom: 24px;
512
+ }
513
+
514
+ .wp-typia-admin-view-screen__header h1 {
515
+ \tfont-size: 28px;
516
+ \tline-height: 1.2;
517
+ \tmargin: 0 0 8px;
518
+ }
519
+
520
+ .wp-typia-admin-view-screen__header p {
521
+ \tmax-width: 680px;
522
+ }
523
+
524
+ .wp-typia-admin-view-screen__eyebrow {
525
+ \tcolor: #3858e9;
526
+ \tfont-size: 11px;
527
+ \tfont-weight: 600;
528
+ \tletter-spacing: 0.08em;
529
+ \tmargin: 0 0 8px;
530
+ \ttext-transform: uppercase;
531
+ }
532
+
533
+ .wp-typia-admin-view-screen__actions {
534
+ \talign-items: center;
535
+ \tdisplay: flex;
536
+ \tgap: 12px;
537
+ }
538
+ `;
539
+ }
540
+ function buildAdminViewPhpSource(adminViewSlug, workspace) {
541
+ const workspaceBaseName = workspace.packageName.split("/").pop() ?? workspace.packageName;
542
+ const phpSlug = adminViewSlug.replace(/-/g, "_");
543
+ const functionPrefix = `${workspace.workspace.phpPrefix}_${phpSlug}`;
544
+ const menuSlugFunctionName = `${functionPrefix}_admin_view_menu_slug`;
545
+ const renderFunctionName = `${functionPrefix}_render_admin_view`;
546
+ const registerFunctionName = `${functionPrefix}_register_admin_view`;
547
+ const enqueueFunctionName = `${functionPrefix}_enqueue_admin_view`;
548
+ const hookGlobalName = `${functionPrefix}_admin_view_hook`;
549
+ const rootId = `wp-typia-admin-view-${adminViewSlug}`;
550
+ const title = toTitleCase(adminViewSlug);
551
+ return `<?php
552
+ if ( ! defined( 'ABSPATH' ) ) {
553
+ \treturn;
554
+ }
555
+
556
+ if ( ! function_exists( '${menuSlugFunctionName}' ) ) {
557
+ \tfunction ${menuSlugFunctionName}() : string {
558
+ \t\treturn '${workspaceBaseName}-${adminViewSlug}';
559
+ \t}
560
+ }
561
+
562
+ if ( ! function_exists( '${renderFunctionName}' ) ) {
563
+ \tfunction ${renderFunctionName}() : void {
564
+ \t\t?>
565
+ \t\t<div class="wrap">
566
+ \t\t\t<div id="${rootId}"></div>
567
+ \t\t</div>
568
+ \t\t<?php
569
+ \t}
570
+ }
571
+
572
+ if ( ! function_exists( '${registerFunctionName}' ) ) {
573
+ \tfunction ${registerFunctionName}() : void {
574
+ \t\t$GLOBALS['${hookGlobalName}'] = add_submenu_page(
575
+ \t\t\t'tools.php',
576
+ \t\t\t__( ${quotePhpString(title)}, ${quotePhpString(workspace.workspace.textDomain)} ),
577
+ \t\t\t__( ${quotePhpString(title)}, ${quotePhpString(workspace.workspace.textDomain)} ),
578
+ \t\t\t'edit_posts',
579
+ \t\t\t${menuSlugFunctionName}(),
580
+ \t\t\t'${renderFunctionName}'
581
+ \t\t);
582
+ \t}
583
+ }
584
+
585
+ if ( ! function_exists( '${enqueueFunctionName}' ) ) {
586
+ \tfunction ${enqueueFunctionName}( string $hook_suffix ) : void {
587
+ \t\t$page_hook = isset( $GLOBALS['${hookGlobalName}'] ) && is_string( $GLOBALS['${hookGlobalName}'] )
588
+ \t\t\t? $GLOBALS['${hookGlobalName}']
589
+ \t\t\t: '';
590
+
591
+ \t\tif ( $page_hook !== $hook_suffix ) {
592
+ \t\t\treturn;
593
+ \t\t}
594
+
595
+ \t\t$plugin_file = dirname( __DIR__, 2 ) . '/${workspaceBaseName}.php';
596
+ \t\t$script_path = dirname( __DIR__, 2 ) . '/${ADMIN_VIEWS_SCRIPT}';
597
+ \t\t$asset_path = dirname( __DIR__, 2 ) . '/${ADMIN_VIEWS_ASSET}';
598
+ \t\t$style_path = dirname( __DIR__, 2 ) . '/${ADMIN_VIEWS_STYLE}';
599
+ \t\t$style_rtl_path = dirname( __DIR__, 2 ) . '/${ADMIN_VIEWS_STYLE_RTL}';
600
+
601
+ \t\tif ( ! file_exists( $script_path ) || ! file_exists( $asset_path ) ) {
602
+ \t\t\treturn;
603
+ \t\t}
604
+
605
+ \t\t$asset = require $asset_path;
606
+ \t\tif ( ! is_array( $asset ) ) {
607
+ \t\t\t$asset = array();
608
+ \t\t}
609
+
610
+ \t\t$dependencies = isset( $asset['dependencies'] ) && is_array( $asset['dependencies'] )
611
+ \t\t\t? $asset['dependencies']
612
+ \t\t\t: array();
613
+
614
+ \t\twp_enqueue_script(
615
+ \t\t\t'${workspaceBaseName}-${adminViewSlug}-admin-view',
616
+ \t\t\tplugins_url( '${ADMIN_VIEWS_SCRIPT}', $plugin_file ),
617
+ \t\t\t$dependencies,
618
+ \t\t\tisset( $asset['version'] ) ? $asset['version'] : filemtime( $script_path ),
619
+ \t\t\ttrue
620
+ \t\t);
621
+
622
+ \t\tif ( file_exists( $style_path ) ) {
623
+ \t\t\twp_enqueue_style(
624
+ \t\t\t\t'${workspaceBaseName}-${adminViewSlug}-admin-view',
625
+ \t\t\t\tplugins_url( '${ADMIN_VIEWS_STYLE}', $plugin_file ),
626
+ \t\t\t\tarray( 'wp-components' ),
627
+ \t\t\t\tisset( $asset['version'] ) ? $asset['version'] : filemtime( $style_path )
628
+ \t\t\t);
629
+ \t\t\tif ( file_exists( $style_rtl_path ) ) {
630
+ \t\t\t\twp_style_add_data( '${workspaceBaseName}-${adminViewSlug}-admin-view', 'rtl', 'replace' );
631
+ \t\t\t}
632
+ \t\t}
633
+ \t}
634
+ }
635
+
636
+ add_action( 'admin_menu', '${registerFunctionName}' );
637
+ add_action( 'admin_enqueue_scripts', '${enqueueFunctionName}' );
638
+ `;
639
+ }
640
+ async function ensureAdminViewPackageDependencies(workspace) {
641
+ const packageJsonPath = path.join(workspace.projectDir, "package.json");
642
+ const wpTypiaDataViewsVersion = resolvePackageVersionRange("@wp-typia/dataviews", DEFAULT_WP_TYPIA_DATAVIEWS_VERSION, "wp-typia-dataviews");
643
+ const wordpressDataViewsVersion = resolvePackageVersionRange("@wordpress/dataviews", DEFAULT_WORDPRESS_DATAVIEWS_VERSION);
644
+ await patchFile(packageJsonPath, (source) => {
645
+ const packageJson = JSON.parse(source);
646
+ const nextDependencies = {
647
+ ...(packageJson.dependencies ?? {}),
648
+ "@wordpress/dataviews": packageJson.dependencies?.["@wordpress/dataviews"] ?? wordpressDataViewsVersion,
649
+ };
650
+ const nextDevDependencies = {
651
+ ...(packageJson.devDependencies ?? {}),
652
+ "@wp-typia/dataviews": packageJson.devDependencies?.["@wp-typia/dataviews"] ??
653
+ wpTypiaDataViewsVersion,
654
+ };
655
+ if (JSON.stringify(nextDependencies) === JSON.stringify(packageJson.dependencies ?? {}) &&
656
+ JSON.stringify(nextDevDependencies) ===
657
+ JSON.stringify(packageJson.devDependencies ?? {})) {
658
+ return source;
659
+ }
660
+ packageJson.dependencies = nextDependencies;
661
+ packageJson.devDependencies = nextDevDependencies;
662
+ return `${JSON.stringify(packageJson, null, detectJsonIndent(source))}\n`;
663
+ });
664
+ }
665
+ async function ensureAdminViewBootstrapAnchors(workspace) {
666
+ const bootstrapPath = getWorkspaceBootstrapPath(workspace);
667
+ await patchFile(bootstrapPath, (source) => {
668
+ let nextSource = source;
669
+ const loadFunctionName = `${workspace.workspace.phpPrefix}_load_admin_views`;
670
+ const loadHook = `add_action( 'plugins_loaded', '${loadFunctionName}' );`;
671
+ const loadFunction = `
672
+
673
+ function ${loadFunctionName}() {
674
+ \tforeach ( glob( __DIR__ . '${ADMIN_VIEWS_PHP_GLOB}' ) ?: array() as $admin_view_module ) {
675
+ \t\trequire_once $admin_view_module;
676
+ \t}
677
+ }
678
+ `;
679
+ const insertionAnchors = [
680
+ /add_action\(\s*["']init["']\s*,\s*["'][^"']+_load_textdomain["']\s*\);\s*\n/u,
681
+ /\?>\s*$/u,
682
+ ];
683
+ const insertPhpSnippet = (snippet) => {
684
+ for (const anchor of insertionAnchors) {
685
+ const candidate = nextSource.replace(anchor, (match) => `${snippet}\n${match}`);
686
+ if (candidate !== nextSource) {
687
+ nextSource = candidate;
688
+ return;
689
+ }
690
+ }
691
+ nextSource = `${nextSource.trimEnd()}\n${snippet}\n`;
692
+ };
693
+ const appendPhpSnippet = (snippet) => {
694
+ const closingTagPattern = /\?>\s*$/u;
695
+ if (closingTagPattern.test(nextSource)) {
696
+ nextSource = nextSource.replace(closingTagPattern, `${snippet}\n?>`);
697
+ return;
698
+ }
699
+ nextSource = `${nextSource.trimEnd()}\n${snippet}\n`;
700
+ };
701
+ if (!hasPhpFunctionDefinition(nextSource, loadFunctionName)) {
702
+ insertPhpSnippet(loadFunction);
703
+ }
704
+ else {
705
+ const functionRange = findPhpFunctionRange(nextSource, loadFunctionName);
706
+ const functionSource = functionRange
707
+ ? nextSource.slice(functionRange.start, functionRange.end)
708
+ : "";
709
+ if (!functionSource.includes(ADMIN_VIEWS_PHP_GLOB)) {
710
+ const replacedSource = replacePhpFunctionDefinition(nextSource, loadFunctionName, loadFunction);
711
+ if (!replacedSource) {
712
+ throw new Error(`Unable to repair ${path.basename(bootstrapPath)} for ${loadFunctionName}.`);
713
+ }
714
+ nextSource = replacedSource;
715
+ }
716
+ }
717
+ if (!nextSource.includes(loadHook)) {
718
+ appendPhpSnippet(loadHook);
719
+ }
720
+ return nextSource;
721
+ });
722
+ }
723
+ async function ensureAdminViewBuildScriptAnchors(workspace) {
724
+ const buildScriptPath = path.join(workspace.projectDir, "scripts", "build-workspace.mjs");
725
+ await patchFile(buildScriptPath, (source) => {
726
+ if (/['"]src\/admin-views\/index\.(?:ts|js)['"]/u.test(source)) {
727
+ return source;
728
+ }
729
+ const currentSharedEntriesPattern = /(\r?\n\s*['"]src\/editor-plugins\/index\.js['"])\s*,?/u;
730
+ let nextSource = source.replace(currentSharedEntriesPattern, `$1,
731
+ \t\t'src/admin-views/index.ts',
732
+ \t\t'src/admin-views/index.js',`);
733
+ if (nextSource !== source) {
734
+ return nextSource;
735
+ }
736
+ const legacySharedEntriesPattern = /\[\s*['"]src\/bindings\/index\.ts['"]\s*,\s*['"]src\/bindings\/index\.js['"]\s*(?:,\s*)?\]/u;
737
+ nextSource = source.replace(legacySharedEntriesPattern, `[
738
+ \t\t'src/bindings/index.ts',
739
+ \t\t'src/bindings/index.js',
740
+ \t\t'src/editor-plugins/index.ts',
741
+ \t\t'src/editor-plugins/index.js',
742
+ \t\t'src/admin-views/index.ts',
743
+ \t\t'src/admin-views/index.js',
744
+ \t]`);
745
+ if (nextSource !== source) {
746
+ return nextSource;
747
+ }
748
+ throw new Error(`Unable to update ${path.relative(workspace.projectDir, buildScriptPath)} for admin view shared entries.`);
749
+ });
750
+ }
751
+ async function ensureAdminViewWebpackAnchors(workspace) {
752
+ const webpackConfigPath = path.join(workspace.projectDir, "webpack.config.js");
753
+ await patchFile(webpackConfigPath, (source) => {
754
+ if (/['"]admin-views\/index['"]/u.test(source)) {
755
+ return source;
756
+ }
757
+ const editorPluginEntryPattern = /(\n\s*\[\s*['"]editor-plugins\/index['"][\s\S]*?['"]src\/editor-plugins\/index\.js['"][\s\S]*?\]\s*\])\s*,?/u;
758
+ let nextSource = source.replace(editorPluginEntryPattern, `$1,
759
+ \t\t[
760
+ \t\t\t'admin-views/index',
761
+ \t\t\t[ 'src/admin-views/index.ts', 'src/admin-views/index.js' ],
762
+ \t\t],`);
763
+ if (nextSource !== source) {
764
+ return nextSource;
765
+ }
766
+ const legacySharedEntriesBlockPattern = /for\s*\(\s*const\s+relativePath\s+of\s+\[\s*['"]src\/bindings\/index\.ts['"]\s*,\s*['"]src\/bindings\/index\.js['"]\s*(?:,\s*)?\]\s*\)\s*\{[\s\S]*?entries\.push\(\s*\[\s*['"]bindings\/index['"]\s*,\s*entryPath\s*\]\s*\);\s*break;\s*\}/u;
767
+ const nextSharedEntriesBlock = `\tfor ( const [ entryName, candidates ] of [\n\t\t[\n\t\t\t'bindings/index',\n\t\t\t[ 'src/bindings/index.ts', 'src/bindings/index.js' ],\n\t\t],\n\t\t[\n\t\t\t'editor-plugins/index',\n\t\t\t[ 'src/editor-plugins/index.ts', 'src/editor-plugins/index.js' ],\n\t\t],\n\t\t[\n\t\t\t'admin-views/index',\n\t\t\t[ 'src/admin-views/index.ts', 'src/admin-views/index.js' ],\n\t\t],\n\t] ) {\n\t\tfor ( const relativePath of candidates ) {\n\t\t\tconst entryPath = path.resolve( process.cwd(), relativePath );\n\t\t\tif ( ! fs.existsSync( entryPath ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tentries.push( [ entryName, entryPath ] );\n\t\t\tbreak;\n\t\t}\n\t}`;
768
+ nextSource = source.replace(legacySharedEntriesBlockPattern, nextSharedEntriesBlock);
769
+ if (nextSource === source) {
770
+ throw new Error(`Unable to update ${path.relative(workspace.projectDir, webpackConfigPath)} for admin view shared entries.`);
771
+ }
772
+ return nextSource;
773
+ });
774
+ }
775
+ function resolveAdminViewRegistryPath(projectDir) {
776
+ const adminViewsDir = path.join(projectDir, "src", "admin-views");
777
+ return [
778
+ path.join(adminViewsDir, "index.ts"),
779
+ path.join(adminViewsDir, "index.js"),
780
+ ].find((candidatePath) => fs.existsSync(candidatePath)) ?? path.join(adminViewsDir, "index.ts");
781
+ }
782
+ function readAdminViewRegistrySlugs(registryPath) {
783
+ if (!fs.existsSync(registryPath)) {
784
+ return [];
785
+ }
786
+ const source = fs.readFileSync(registryPath, "utf8");
787
+ return Array.from(source.matchAll(/^\s*import\s+['"]\.\/([^/'"]+)(?:\/index(?:\.[cm]?[jt]sx?)?)?['"];?\s*$/gmu)).map((match) => match[1]);
788
+ }
789
+ async function writeAdminViewRegistry(projectDir, adminViewSlug) {
790
+ const adminViewsDir = path.join(projectDir, "src", "admin-views");
791
+ const registryPath = resolveAdminViewRegistryPath(projectDir);
792
+ await fsp.mkdir(adminViewsDir, { recursive: true });
793
+ const existingAdminViewSlugs = readWorkspaceInventory(projectDir).adminViews.map((entry) => entry.slug);
794
+ const existingRegistrySlugs = readAdminViewRegistrySlugs(registryPath);
795
+ const nextAdminViewSlugs = Array.from(new Set([...existingAdminViewSlugs, ...existingRegistrySlugs, adminViewSlug])).sort();
796
+ await fsp.writeFile(registryPath, buildAdminViewRegistrySource(nextAdminViewSlugs), "utf8");
797
+ }
798
+ /**
799
+ * Add one DataViews-powered WordPress admin screen scaffold to an official
800
+ * workspace project.
801
+ *
802
+ * @param options Command options for the admin-view scaffold workflow.
803
+ * @param options.adminViewName Human-entered admin screen name that will be
804
+ * normalized and validated before files are written.
805
+ * @param options.cwd Working directory used to resolve the nearest official workspace.
806
+ * Defaults to `process.cwd()`.
807
+ * @param options.source Optional data source locator. `rest-resource:<slug>`
808
+ * wires the screen to an existing list-capable REST resource.
809
+ * @returns A promise that resolves with the normalized `adminViewSlug`, optional
810
+ * `source`, and owning `projectDir` after scaffold files and inventory entries
811
+ * are written successfully.
812
+ * @throws {Error} When the command is run outside an official workspace, when
813
+ * the slug/source is invalid, or when a conflicting file or inventory entry exists.
814
+ */
815
+ export async function runAddAdminViewCommand({ adminViewName, cwd = process.cwd(), source, }) {
816
+ const workspace = resolveWorkspaceProject(cwd);
817
+ const adminViewSlug = assertValidGeneratedSlug("Admin view name", normalizeBlockSlug(adminViewName), "wp-typia add admin-view <name> [--source rest-resource:<slug>]");
818
+ const parsedSource = parseAdminViewSource(source);
819
+ const inventory = readWorkspaceInventory(workspace.projectDir);
820
+ const restResource = resolveRestResourceSource(inventory.restResources, parsedSource);
821
+ assertAdminViewDoesNotExist(workspace.projectDir, adminViewSlug, inventory);
822
+ const blockConfigPath = path.join(workspace.projectDir, "scripts", "block-config.ts");
823
+ const bootstrapPath = getWorkspaceBootstrapPath(workspace);
824
+ const buildScriptPath = path.join(workspace.projectDir, "scripts", "build-workspace.mjs");
825
+ const packageJsonPath = path.join(workspace.projectDir, "package.json");
826
+ const webpackConfigPath = path.join(workspace.projectDir, "webpack.config.js");
827
+ const adminViewsIndexPath = resolveAdminViewRegistryPath(workspace.projectDir);
828
+ const adminViewDir = path.join(workspace.projectDir, "src", "admin-views", adminViewSlug);
829
+ const adminViewPhpPath = path.join(workspace.projectDir, "inc", "admin-views", `${adminViewSlug}.php`);
830
+ const mutationSnapshot = {
831
+ fileSources: await snapshotWorkspaceFiles([
832
+ adminViewsIndexPath,
833
+ blockConfigPath,
834
+ bootstrapPath,
835
+ buildScriptPath,
836
+ packageJsonPath,
837
+ webpackConfigPath,
838
+ ]),
839
+ snapshotDirs: [],
840
+ targetPaths: [adminViewDir, adminViewPhpPath],
841
+ };
842
+ try {
843
+ await fsp.mkdir(adminViewDir, { recursive: true });
844
+ await fsp.mkdir(path.dirname(adminViewPhpPath), { recursive: true });
845
+ await ensureAdminViewPackageDependencies(workspace);
846
+ await ensureAdminViewBootstrapAnchors(workspace);
847
+ await ensureAdminViewBuildScriptAnchors(workspace);
848
+ await ensureAdminViewWebpackAnchors(workspace);
849
+ await fsp.writeFile(path.join(adminViewDir, "types.ts"), buildAdminViewTypesSource(adminViewSlug, restResource), "utf8");
850
+ await fsp.writeFile(path.join(adminViewDir, "config.ts"), buildAdminViewConfigSource(adminViewSlug, workspace.workspace.textDomain, restResource), "utf8");
851
+ await fsp.writeFile(path.join(adminViewDir, "data.ts"), restResource
852
+ ? buildRestAdminViewDataSource(adminViewSlug, restResource)
853
+ : buildDefaultAdminViewDataSource(adminViewSlug), "utf8");
854
+ await fsp.writeFile(path.join(adminViewDir, "Screen.tsx"), buildAdminViewScreenSource(adminViewSlug, workspace.workspace.textDomain), "utf8");
855
+ await fsp.writeFile(path.join(adminViewDir, "index.tsx"), buildAdminViewEntrySource(adminViewSlug), "utf8");
856
+ await fsp.writeFile(path.join(adminViewDir, "style.scss"), buildAdminViewStyleSource(), "utf8");
857
+ await fsp.writeFile(adminViewPhpPath, buildAdminViewPhpSource(adminViewSlug, workspace), "utf8");
858
+ await writeAdminViewRegistry(workspace.projectDir, adminViewSlug);
859
+ await appendWorkspaceInventoryEntries(workspace.projectDir, {
860
+ adminViewEntries: [buildAdminViewConfigEntry(adminViewSlug, parsedSource)],
861
+ });
862
+ return {
863
+ adminViewSlug,
864
+ projectDir: workspace.projectDir,
865
+ source: parsedSource ? `${parsedSource.kind}:${parsedSource.slug}` : undefined,
866
+ };
867
+ }
868
+ catch (error) {
869
+ await rollbackWorkspaceMutation(mutationSnapshot);
870
+ throw error;
871
+ }
872
+ }