@se-studio/contentful-cms 2.5.0 → 2.6.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 (131) hide show
  1. package/CHANGELOG.md +48 -11
  2. package/INSTALL.md +1 -1
  3. package/README.md +10 -17
  4. package/dist/audit/asset-usage.d.ts +15 -0
  5. package/dist/audit/asset-usage.d.ts.map +1 -0
  6. package/dist/audit/asset-usage.js +81 -0
  7. package/dist/audit/asset-usage.js.map +1 -0
  8. package/dist/audit/media-review.d.ts +2 -0
  9. package/dist/audit/media-review.d.ts.map +1 -1
  10. package/dist/audit/media-review.js.map +1 -1
  11. package/dist/cli/program.d.ts.map +1 -1
  12. package/dist/cli/program.js +4 -22
  13. package/dist/cli/program.js.map +1 -1
  14. package/dist/commands/add.js +1 -1
  15. package/dist/commands/add.js.map +1 -1
  16. package/dist/commands/asset.d.ts.map +1 -1
  17. package/dist/commands/asset.js +9 -0
  18. package/dist/commands/asset.js.map +1 -1
  19. package/dist/commands/batch.d.ts.map +1 -1
  20. package/dist/commands/batch.js +5 -2
  21. package/dist/commands/batch.js.map +1 -1
  22. package/dist/commands/create-from-json.d.ts.map +1 -1
  23. package/dist/commands/create-from-json.js +24 -2
  24. package/dist/commands/create-from-json.js.map +1 -1
  25. package/dist/commands/help.d.ts.map +1 -1
  26. package/dist/commands/help.js +3 -2
  27. package/dist/commands/help.js.map +1 -1
  28. package/dist/commands/run.d.ts +1 -1
  29. package/dist/commands/run.d.ts.map +1 -1
  30. package/dist/commands/run.js +3 -3
  31. package/dist/commands/run.js.map +1 -1
  32. package/dist/commands/schema.d.ts.map +1 -1
  33. package/dist/commands/schema.js +228 -85
  34. package/dist/commands/schema.js.map +1 -1
  35. package/dist/generated/hosted-guide.d.ts +1 -1
  36. package/dist/generated/hosted-guide.d.ts.map +1 -1
  37. package/dist/generated/hosted-guide.js +1 -1
  38. package/dist/generated/hosted-guide.js.map +1 -1
  39. package/dist/generated/version.d.ts +1 -1
  40. package/dist/generated/version.js +1 -1
  41. package/dist/mcp/guide.js +1 -1
  42. package/dist/mcp/guide.js.map +1 -1
  43. package/dist/mcp/prompts/onboarding.js +7 -7
  44. package/dist/mcp/prompts/onboarding.js.map +1 -1
  45. package/dist/mcp/tools/cms-edit.d.ts +1 -1
  46. package/dist/mcp/tools/cms-edit.d.ts.map +1 -1
  47. package/dist/mcp/tools/cms-edit.js +1 -1
  48. package/docs/FUNCTIONAL_SPEC.md +2 -2
  49. package/docs/SKILLS.md +3 -3
  50. package/docs/editor-tasks/article-tags.md +47 -0
  51. package/docs/editor-tasks/authors-import.md +53 -0
  52. package/docs/editor-tasks/bulk-find-replace.md +52 -0
  53. package/docs/editor-tasks/clone-page.md +39 -0
  54. package/docs/editor-tasks/create-article.md +46 -0
  55. package/docs/editor-tasks/create-from-document.md +45 -0
  56. package/docs/editor-tasks/create-page.md +41 -0
  57. package/docs/editor-tasks/edit-rich-text.md +44 -0
  58. package/docs/editor-tasks/edit-scalar-fields.md +47 -0
  59. package/docs/editor-tasks/featured-images.md +46 -0
  60. package/docs/editor-tasks/media-reuse-and-upload.md +51 -0
  61. package/docs/editor-tasks/navigation.md +39 -0
  62. package/docs/editor-tasks/preview-verify.md +38 -0
  63. package/docs/editor-tasks/publish-handoff.md +36 -0
  64. package/docs/editor-tasks/seo-descriptions.md +48 -0
  65. package/docs/editor-tasks/taxonomy.md +51 -0
  66. package/docs/help/asset-review.md +4 -0
  67. package/docs/help/{run.md → batch-run.md} +8 -8
  68. package/docs/help/create-from-json.md +3 -2
  69. package/docs/help/fields-article.md +2 -2
  70. package/docs/help/fields-component.md +3 -3
  71. package/docs/help/fields-taxonomy.md +6 -6
  72. package/docs/help/fields.md +2 -2
  73. package/docs/help/index-sync.md +1 -1
  74. package/docs/help/index.md +23 -18
  75. package/docs/help/lookup.md +1 -1
  76. package/docs/help/person-from-json.md +3 -3
  77. package/docs/help/taxonomy-from-json.md +3 -3
  78. package/docs/help/workflow.md +1 -1
  79. package/docs/mcp/hosted-guide.md +6 -6
  80. package/package.json +3 -3
  81. package/skills/README.md +2 -2
  82. package/skills/core/SKILL.md +33 -40
  83. package/skills/setup/SKILL.md +1 -1
  84. package/dist/bin/contentful-cms.d.ts +0 -3
  85. package/dist/bin/contentful-cms.d.ts.map +0 -1
  86. package/dist/bin/contentful-cms.js +0 -5
  87. package/dist/bin/contentful-cms.js.map +0 -1
  88. package/dist/commands/audit.d.ts +0 -4
  89. package/dist/commands/audit.d.ts.map +0 -1
  90. package/dist/commands/audit.js +0 -399
  91. package/dist/commands/audit.js.map +0 -1
  92. package/dist/commands/backup.d.ts +0 -3
  93. package/dist/commands/backup.d.ts.map +0 -1
  94. package/dist/commands/backup.js +0 -143
  95. package/dist/commands/backup.js.map +0 -1
  96. package/dist/commands/colours.d.ts +0 -4
  97. package/dist/commands/colours.d.ts.map +0 -1
  98. package/dist/commands/colours.js +0 -91
  99. package/dist/commands/colours.js.map +0 -1
  100. package/dist/commands/ensure.d.ts +0 -4
  101. package/dist/commands/ensure.d.ts.map +0 -1
  102. package/dist/commands/ensure.js +0 -152
  103. package/dist/commands/ensure.js.map +0 -1
  104. package/dist/commands/restore.d.ts +0 -4
  105. package/dist/commands/restore.d.ts.map +0 -1
  106. package/dist/commands/restore.js +0 -146
  107. package/dist/commands/restore.js.map +0 -1
  108. package/dist/commands/revert.d.ts +0 -4
  109. package/dist/commands/revert.d.ts.map +0 -1
  110. package/dist/commands/revert.js +0 -143
  111. package/dist/commands/revert.js.map +0 -1
  112. package/dist/commands/sitemap.d.ts +0 -4
  113. package/dist/commands/sitemap.d.ts.map +0 -1
  114. package/dist/commands/sitemap.js +0 -151
  115. package/dist/commands/sitemap.js.map +0 -1
  116. package/dist/commands/skill.d.ts +0 -4
  117. package/dist/commands/skill.d.ts.map +0 -1
  118. package/dist/commands/skill.js +0 -40
  119. package/dist/commands/skill.js.map +0 -1
  120. package/dist/commands/types.d.ts +0 -4
  121. package/dist/commands/types.d.ts.map +0 -1
  122. package/dist/commands/types.js +0 -78
  123. package/dist/commands/types.js.map +0 -1
  124. package/dist/session/backup.d.ts +0 -34
  125. package/dist/session/backup.d.ts.map +0 -1
  126. package/dist/session/backup.js +0 -64
  127. package/dist/session/backup.js.map +0 -1
  128. package/dist/skills/install.d.ts +0 -13
  129. package/dist/skills/install.d.ts.map +0 -1
  130. package/dist/skills/install.js +0 -37
  131. package/dist/skills/install.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@se-studio/contentful-cms",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "CLI tool for AI agents to read and edit Contentful draft content without publish permissions",
5
5
  "repository": {
6
6
  "type": "git",
@@ -49,11 +49,11 @@
49
49
  }
50
50
  },
51
51
  "bin": {
52
- "cms-edit": "./dist/bin/cms-edit.js",
53
- "contentful-cms": "./dist/bin/contentful-cms.js"
52
+ "cms-edit": "./dist/bin/cms-edit.js"
54
53
  },
55
54
  "files": [
56
55
  "dist",
56
+ "docs/editor-tasks",
57
57
  "docs/help",
58
58
  "docs/mcp",
59
59
  "skills",
package/skills/README.md CHANGED
@@ -18,13 +18,13 @@ pnpm --filter @se-studio/contentful-cms build
18
18
  |------|--------|
19
19
  | **Edit skill content** | `packages/skills/skills/contentful-cms-*/SKILL.md` |
20
20
  | **Bundled subset for npm** | This directory (`core`, `editor-tasks`, `templates`, `setup`) via `scripts/sync-cms-edit-skills.mjs` |
21
- | **Install into a project** | `cms-edit skill install` → `.agents/skills/contentful-cms-<name>/` |
21
+ | **Install into a project** | `npx skills add @se-studio/skills` → `.agents/skills/contentful-cms-<name>/` |
22
22
 
23
23
  Full monorepo skill sync (all marketing-site + CMS skills): `pnpm skills:sync` → `.agents/skills/` (gitignored).
24
24
 
25
25
  ## Agent skill directories
26
26
 
27
27
  - **In this monorepo:** use `.agents/skills/` (symlinked as `.cursor/skills/`). Never commit hand-edited copies under `.claude/skills/` — that tree is local/optional and untracked.
28
- - **External projects:** `npx skills add @se-studio/skills` or `cms-edit skill install`.
28
+ - **External projects:** `npx skills add @se-studio/skills`.
29
29
 
30
30
  See [docs/SKILLS.md](../docs/SKILLS.md) and [packages/skills/README.md](../../skills/README.md).
@@ -279,8 +279,8 @@ cms-edit add CTA --content-type component --existing-id 4xKj2abcDef
279
279
 
280
280
  Discover available types first:
281
281
  ```bash
282
- cms-edit types component
283
- cms-edit types collection
282
+ cms-edit schema types component
283
+ cms-edit schema types collection
284
284
  ```
285
285
 
286
286
  ### Remove a component
@@ -436,9 +436,9 @@ cms-edit create tag --json-file tag.json --tag-type presentation-type --if-not-e
436
436
  cms-edit create taxonomy-from-json --file taxonomy.json --if-not-exists
437
437
 
438
438
  # Idempotent single-entry creates
439
- cms-edit ensure tag-type --slug conference-venue --name "Conference Venue"
440
- cms-edit ensure tag --slug asco-2025 --name "ASCO 2025" --tag-type conference-venue \
441
- --description "Annual ASCO conference." --featured-image <logoAssetId>
439
+ cms-edit create tag-type --slug conference-venue --name "Conference Venue" --if-not-exists
440
+ cms-edit create tag --slug asco-2025 --name "ASCO 2025" --tag-type conference-venue \
441
+ --description "Annual ASCO conference." --featured-image <logoAssetId> --if-not-exists
442
442
  ```
443
443
 
444
444
  See `cms-edit help fields-taxonomy` and `cms-edit help taxonomy-from-json` for field reference and batch schema.
@@ -463,7 +463,7 @@ cms-edit read @c0 bio
463
463
 
464
464
  **Site/runtime:** Resolved **person links** (`IPersonLink` from the REST API — article authors, collection contents, `contentfulAllPersonLinks`, related-people helpers) include **`bio`** when set in CMS. Use for team cards, related-people collections, and markdown/search export — not only full person detail pages.
465
465
 
466
- **Idempotent taxonomy:** `--if-not-exists` / `ensure` are check-then-create — safe for sequential imports, not for parallel creates on the same slug.
466
+ **Idempotent taxonomy:** `--if-not-exists` is check-then-create — safe for sequential imports, not for parallel creates on the same slug.
467
467
 
468
468
  ```bash
469
469
  # Resolve taxonomy IDs without a session
@@ -481,8 +481,8 @@ cms-edit search "pricing page"
481
481
  cms-edit search "hero" --type component
482
482
 
483
483
  # List valid type values
484
- cms-edit types component
485
- cms-edit types collection
484
+ cms-edit schema types component
485
+ cms-edit schema types collection
486
486
 
487
487
  # List entries with filters
488
488
  cms-edit list --type article --sort date -n 10 # recent articles by publication date
@@ -491,7 +491,7 @@ cms-edit list --type article --slug my-article # article with a specific slug
491
491
  cms-edit list --type article --has-field tags # articles where tags field is non-empty
492
492
 
493
493
  # Find draft articles, then peek/open (both support drafts via CMA)
494
- cms-edit sitemap --include article --status draft
494
+ cms-edit list --type article --sort date
495
495
  cms-edit peek --article-slug resources/blog/my-post
496
496
  # Only list --published / resolve --published are published-only
497
497
 
@@ -566,7 +566,7 @@ cms-edit save
566
566
  ### Add a new section to a page
567
567
  ```bash
568
568
  cms-edit open --page-slug /products
569
- cms-edit types component # discover what's available
569
+ cms-edit schema types component # discover what's available
570
570
  cms-edit add CTA --after @c3
571
571
  cms-edit set @c4 heading "Ready to get started?"
572
572
  cms-edit rtf @c4 body --markdown "Join thousands of teams who trust us."
@@ -611,17 +611,11 @@ cms-edit preview showcase --collection CardGrid --param backgroundColour=Navy
611
611
 
612
612
  For CMS guidelines batch PNG capture, use `cms-capture-screenshots` from `@se-studio/project-build` (separate from cms-edit; requires agent-browser).
613
613
 
614
- ## Revert
614
+ ## Undo changes
615
615
 
616
- Field-level undo — restore fields to their original values from when the session was opened.
616
+ There is no field-level revert command. To abandon unsaved edits: `cms-edit diff` to review, then `cms-edit discard` (or `discard --all`). To roll back saved drafts, use the Contentful web app version history.
617
617
 
618
- ```bash
619
- cms-edit revert @c0 heading # Revert a single field to its original value
620
- cms-edit revert @c0 # Revert all fields on an entry
621
- cms-edit revert --all # Revert all modified entries (session stays open)
622
- ```
623
-
624
- Note: Entries created via `add` cannot be reverted — use `remove` instead.
618
+ Note: Entries created via `add` that you have not saved can be removed with `cms-edit remove <ref>`.
625
619
 
626
620
  ## Health Check
627
621
 
@@ -633,25 +627,27 @@ cms-edit health # Check config file, space config, Contentful connectivity
633
627
 
634
628
  ## Schema Inspection
635
629
 
636
- Inspect field definitions for a content type. Prefer this over `cms-edit types <ct>` when you need full field info.
630
+ Inspect field definitions for a content type. Use `cms-edit schema types <ct>` for type-discriminator values only.
637
631
 
638
632
  ```bash
639
633
  cms-edit schema component # Show all fields, types, enum values, link targets
640
634
  cms-edit schema component --json # Full JSON output
641
635
  ```
642
636
 
643
- ## Sitemap
637
+ ## Content catalog (`list`)
644
638
 
645
- Browse all pages in the space.
639
+ Browse entries by content type (index-backed for catalog types). Run `cms-edit index sync` once per space, or let commands auto-sync.
646
640
 
647
641
  ```bash
648
- cms-edit sitemap # All pages, sorted by slug
649
- cms-edit sitemap --prefix /blog # Filter by slug prefix
650
- cms-edit sitemap --status draft # Draft pages only
651
- cms-edit sitemap --sort updated # Most recently updated first
652
- cms-edit sitemap --include article --sort date # Articles by publication date
653
- cms-edit sitemap --tree # Tree rendering
654
- cms-edit sitemap --include page,article # Include articles too
642
+ cms-edit list --type page # All pages (label sort)
643
+ cms-edit list --type page --sort updated # Most recently updated first
644
+ cms-edit list --type article --sort date # Articles by publication date
645
+ cms-edit list --type pageVariant # A/B or variant pages
646
+ cms-edit list --type tag --tag-type-name "Topic" # Tags under a tag type
647
+ cms-edit list --type tagType # Tag types
648
+ cms-edit list --type articleType # Article types
649
+ cms-edit list --type navigation # Navigations
650
+ cms-edit list --type person --force-cma # People (not in catalog index)
655
651
  ```
656
652
 
657
653
  ## Peek
@@ -663,14 +659,14 @@ cms-edit peek --page-slug /pricing # Show snapshot of /pricing; your active se
663
659
  cms-edit peek --id <entryId> # Look up by entry ID
664
660
  ```
665
661
 
666
- ## Batch Operations (run)
662
+ ## Batch Operations (batch run)
667
663
 
668
664
  Run a sequence of operations from a JSON file or stdin.
669
665
 
670
666
  ```bash
671
- cms-edit run --file ops.json # Run batch ops from file
672
- echo '[...]' | cms-edit run # Pipe from stdin
673
- cms-edit run --file ops.json --dry-run # Validate without saving
667
+ cms-edit batch run --file ops.json # Run batch ops from file
668
+ echo '[...]' | cms-edit batch run # Pipe from stdin
669
+ cms-edit batch run --file ops.json --dry-run # Validate without saving
674
670
  ```
675
671
 
676
672
  Supported ops: `open`, `set`, `rtf`, `rtf-replace`, `save`, `add`, `links-add`.
@@ -823,15 +819,12 @@ cms-edit resolve 4xKj2abcDef
823
819
 
824
820
  ## Inventory & Status
825
821
 
826
- Use `sitemap` to see all pages in a space with their publication status:
822
+ Use `list --type <type>` for inventory. Catalog types (page, article, pageVariant, template, taxonomy, navigation) use the local index. Use `--force-cma` for other types (person, customType, pageTest) or published-only with `--published`.
827
823
 
828
824
  ```bash
829
- cms-edit sitemap # All pages
830
- cms-edit sitemap --prefix /parent-coaching # Filter by slug prefix
831
- cms-edit sitemap --status draft # Draft pages only
832
- cms-edit sitemap --sort updated # Most recently updated first
833
- cms-edit sitemap --tree # Tree view
834
- cms-edit sitemap --include page,article # Include articles
825
+ cms-edit list --type page
826
+ cms-edit list --type article --sort date -n 20
827
+ cms-edit index dump --reference-only # Full catalog snapshot in terminal
835
828
  ```
836
829
 
837
830
  **Note on bulk publish:** The tool cannot publish entries — all saves create drafts only. This is intentional. Review and publish drafts from the Contentful web app.
@@ -41,7 +41,7 @@ For engineering work in a site repo (Cursor, Grok, terminal):
41
41
 
42
42
  1. Configure `.contentful-cms.json` in the project (or `~/.contentful-cms.json`) with space credentials
43
43
  2. Run `npx skills add @se-studio/skills` or `pnpm skills:sync` in the monorepo
44
- 3. Optionally `cms-edit skill install` for bundled cms-edit skills
44
+ 3. Bundled cms-edit skills (`core`, `setup`, etc.) are included when you run `npx skills add @se-studio/skills`
45
45
  4. Read `cms-edit/<site>/editor-pack/tasks-index.md` before editing content
46
46
 
47
47
  Do **not** register a local `mcpServers.cms-edit` entry in Claude Desktop — use the hosted connector URL instead.
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
3
- //# sourceMappingURL=contentful-cms.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"contentful-cms.d.ts","sourceRoot":"","sources":["../../src/bin/contentful-cms.ts"],"names":[],"mappings":""}
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
- // Alias for `cms-edit` — `npx @se-studio/contentful-cms` runs the CLI (hosted MCP is via `/cms-edit` OAuth).
3
- await import('./cms-edit.js');
4
- export {};
5
- //# sourceMappingURL=contentful-cms.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"contentful-cms.js","sourceRoot":"","sources":["../../src/bin/contentful-cms.ts"],"names":[],"mappings":";AACA,6GAA6G;AAE7G,MAAM,MAAM,CAAC,eAAe,CAAC,CAAC"}
@@ -1,4 +0,0 @@
1
- /** biome-ignore-all lint/suspicious/noConsole: Console output is intentional in CLI */
2
- import type { Command } from 'commander';
3
- export declare function registerAuditCommand(program: Command): void;
4
- //# sourceMappingURL=audit.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"audit.d.ts","sourceRoot":"","sources":["../../src/commands/audit.ts"],"names":[],"mappings":"AAAA,uFAAuF;AAEvF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AA8fzC,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CA2D3D"}
@@ -1,399 +0,0 @@
1
- /** biome-ignore-all lint/suspicious/noConsole: Console output is intentional in CLI */
2
- import pc from 'picocolors';
3
- import { loadConfig, resolveSpaceConfig } from '../config/load.js';
4
- import { createSafeEnvironment } from '../contentful/client.js';
5
- import { fetchEntryTree, findEntryBySlug, serializeEntry } from '../contentful/fetch.js';
6
- import { CONTENT_ARRAY_FIELDS, collectLinkedEntryIdsForLocale, TEMPLATE_EXTRA_CONTENT_ARRAY_FIELDS, } from '../contentful/linkedEntryFields.js';
7
- import { isJsonMode } from '../output/mode.js';
8
- import { errorMsg, infoMsg } from '../output/print.js';
9
- // ---------------------------------------------------------------------------
10
- // Walk-up: resolve slug-bearing ancestors
11
- // ---------------------------------------------------------------------------
12
- /**
13
- * Content types that have a public slug and represent meaningful usage context.
14
- * Intermediate types (media, visual, component, collection, navigationItem…)
15
- * are traversed silently until one of these is found.
16
- */
17
- const SLUG_BEARING_TYPES = new Set([
18
- 'page',
19
- 'article',
20
- 'articleType',
21
- 'pageVariant',
22
- 'tag',
23
- 'person',
24
- ]);
25
- const MAX_WALK_DEPTH = 5;
26
- const WALK_PARENT_LIMIT = 20;
27
- /**
28
- * Walks UP the entry graph via `links_to_entry` until it reaches a slug-bearing
29
- * content type (page, article, articleType, pageVariant, tag, person).
30
- *
31
- * Returns deduplicated slug-bearing ancestors. If the entry itself is slug-bearing
32
- * it is returned directly without further traversal.
33
- */
34
- async function resolveSlugBearingAncestors(env, entryId, contentType, locale, visited, depth = 0) {
35
- if (visited.has(entryId))
36
- return [];
37
- visited.add(entryId);
38
- // Base case: this entry is slug-bearing → fetch it and return
39
- if (SLUG_BEARING_TYPES.has(contentType)) {
40
- try {
41
- const raw = await env.getEntry(entryId);
42
- const fields = raw.fields;
43
- const label = getEntryLabel(fields, locale);
44
- const slugField = fields['slug'];
45
- const rawSlug = slugField ? String(slugField[locale] ?? slugField['en-US'] ?? '') : '';
46
- const slug = rawSlug ? (rawSlug.startsWith('/') ? rawSlug : `/${rawSlug}`) : null;
47
- return [{ id: entryId, contentType, label, slug }];
48
- }
49
- catch {
50
- return [];
51
- }
52
- }
53
- // Depth limit
54
- if (depth >= MAX_WALK_DEPTH)
55
- return [];
56
- // Walk up: find entries that link to this one
57
- const parents = await env.getEntries({ links_to_entry: entryId, limit: WALK_PARENT_LIMIT });
58
- const results = [];
59
- const seen = new Set();
60
- for (const parent of parents.items) {
61
- const ancestors = await resolveSlugBearingAncestors(env, parent.sys.id, parent.sys.contentType.sys.id, locale, visited, depth + 1);
62
- for (const a of ancestors) {
63
- if (!seen.has(a.id)) {
64
- seen.add(a.id);
65
- results.push(a);
66
- }
67
- }
68
- }
69
- return results;
70
- }
71
- // ---------------------------------------------------------------------------
72
- // Shared helpers
73
- // ---------------------------------------------------------------------------
74
- function getEntryLabel(fields, locale) {
75
- const lf = (key) => {
76
- const f = fields[key];
77
- if (!f)
78
- return undefined;
79
- const v = f[locale] ?? f['en-US'];
80
- return v ? String(v) : undefined;
81
- };
82
- return (lf('cmsLabel') ?? lf('heading') ?? lf('title') ?? lf('adminLabel') ?? lf('slug') ?? '(no label)');
83
- }
84
- function isAssetLink(item) {
85
- return (typeof item === 'object' &&
86
- item !== null &&
87
- 'sys' in item &&
88
- typeof item.sys === 'object' &&
89
- item.sys.linkType === 'Asset');
90
- }
91
- /**
92
- * Extracts all Asset links from an entry's fields at a given locale.
93
- * Returns { assetId, fieldName } for each found link.
94
- */
95
- function extractAssetLinks(fields, locale) {
96
- const results = [];
97
- for (const [fieldName, fieldData] of Object.entries(fields)) {
98
- if (!fieldData)
99
- continue;
100
- const val = fieldData[locale] ?? fieldData['en-US'];
101
- if (!val)
102
- continue;
103
- if (isAssetLink(val)) {
104
- results.push({ assetId: val.sys.id, fieldName });
105
- }
106
- else if (Array.isArray(val)) {
107
- for (const item of val) {
108
- if (isAssetLink(item))
109
- results.push({ assetId: item.sys.id, fieldName });
110
- }
111
- }
112
- }
113
- return results;
114
- }
115
- /**
116
- * Returns IDs of child entries reachable via content array / single-link fields.
117
- * Mirrors the traversal logic in fetch.ts extractLinkedEntryIds.
118
- */
119
- function getContentChildIds(entry, locale) {
120
- const ctId = entry.sys.contentType.sys.id;
121
- const contentArrayFields = ctId === 'template'
122
- ? [...CONTENT_ARRAY_FIELDS, ...TEMPLATE_EXTRA_CONTENT_ARRAY_FIELDS]
123
- : CONTENT_ARRAY_FIELDS;
124
- return collectLinkedEntryIdsForLocale(entry.fields, locale, contentArrayFields);
125
- }
126
- /** Paginates through all page entries in the CMA. */
127
- async function fetchAllPageInfos(env, locale) {
128
- const pages = [];
129
- let skip = 0;
130
- const limit = 200;
131
- while (true) {
132
- const result = await env.getEntries({
133
- content_type: 'page',
134
- select: 'sys,fields.slug,fields.title',
135
- limit,
136
- skip,
137
- });
138
- for (const raw of result.items) {
139
- const fields = raw.fields;
140
- const rawSlug = String(fields['slug']?.[locale] ?? fields['slug']?.['en-US'] ?? raw.sys.id);
141
- const slug = rawSlug.startsWith('/') ? rawSlug : `/${rawSlug}`;
142
- const title = String(fields['title']?.[locale] ?? fields['title']?.['en-US'] ?? slug);
143
- pages.push({ id: raw.sys.id, slug, title });
144
- }
145
- if (result.items.length < limit)
146
- break;
147
- skip += limit;
148
- }
149
- return pages;
150
- }
151
- function summariseRawAsset(raw) {
152
- const fileField = raw.fields.file;
153
- const fileLoc = Object.keys(fileField ?? {})[0] ?? 'en-US';
154
- const fileData = fileField?.[fileLoc];
155
- const titleField = raw.fields.title;
156
- const title = String(titleField?.[fileLoc] ?? titleField?.['en-US'] ?? raw.sys.id);
157
- return {
158
- id: raw.sys.id,
159
- title,
160
- fileName: fileData?.fileName ?? '',
161
- contentType: fileData?.contentType ?? '',
162
- url: fileData?.url ? `https:${fileData.url}` : '',
163
- width: fileData?.details?.image?.width ?? null,
164
- height: fileData?.details?.image?.height ?? null,
165
- size: fileData?.details?.size ?? null,
166
- };
167
- }
168
- async function runAuditImages(opts) {
169
- const config = loadConfig(opts.config);
170
- const { key, space } = resolveSpaceConfig(config, opts.space);
171
- const env = await createSafeEnvironment(space);
172
- const locale = space.defaultLocale;
173
- // 1. Fetch all image assets (paginated)
174
- infoMsg(`Fetching all image assets for space "${key}"…`);
175
- const rawAssets = [];
176
- let skip = 0;
177
- const limit = 100;
178
- while (true) {
179
- const result = await env.getAssets({ limit, skip });
180
- for (const raw of result.items) {
181
- const summary = summariseRawAsset(raw);
182
- if (summary.contentType.startsWith('image/') || summary.contentType === '') {
183
- rawAssets.push(summary);
184
- }
185
- }
186
- if (result.items.length < limit)
187
- break;
188
- skip += limit;
189
- }
190
- infoMsg(`Found ${String(rawAssets.length)} image asset(s).`);
191
- // 2. For each asset, walk up from immediate backlinks to slug-bearing ancestors
192
- const images = [];
193
- let i = 0;
194
- for (const asset of rawAssets) {
195
- i++;
196
- infoMsg(` [${String(i)}/${String(rawAssets.length)}] ${asset.title}`);
197
- const backlinks = await env.getEntries({ links_to_asset: asset.id, limit: 50 });
198
- const seen = new Set();
199
- const usages = [];
200
- // Shared visited set across all backlinks for this asset to avoid redundant walks
201
- const visited = new Set();
202
- for (const entry of backlinks.items) {
203
- const ancestors = await resolveSlugBearingAncestors(env, entry.sys.id, entry.sys.contentType.sys.id, locale, visited);
204
- for (const a of ancestors) {
205
- if (!seen.has(a.id)) {
206
- seen.add(a.id);
207
- usages.push(a);
208
- }
209
- }
210
- }
211
- images.push({ ...asset, usages });
212
- }
213
- const output = {
214
- space: key,
215
- generated: new Date().toISOString(),
216
- total: images.length,
217
- images,
218
- };
219
- if (isJsonMode()) {
220
- console.log(JSON.stringify(output, null, 2));
221
- return;
222
- }
223
- // Human-readable summary
224
- console.log(`\n${pc.bold(`Image Audit — ${key}`)}\n`);
225
- for (const img of images) {
226
- const dims = img.width && img.height ? ` ${String(img.width)}×${String(img.height)}` : '';
227
- const ct = img.contentType ? ` ${pc.dim(img.contentType)}` : '';
228
- console.log(`${pc.bold(img.title)} ${pc.dim(img.fileName)}${pc.dim(dims)}${ct}`);
229
- console.log(` ID: ${img.id}`);
230
- if (img.usages.length === 0) {
231
- console.log(` ${pc.yellow('⚠ No usages found — may be unused')}`);
232
- }
233
- else {
234
- for (const u of img.usages) {
235
- const slugStr = u.slug ? pc.cyan(u.slug) : pc.dim('(no slug)');
236
- console.log(` ${slugStr} ${pc.blue(u.contentType)} "${u.label}"`);
237
- }
238
- }
239
- console.log('');
240
- }
241
- console.log(pc.dim(`${String(images.length)} image(s) total. Use --json for full JSON output.`));
242
- }
243
- function buildNodeTree(entryId, allEntries, locale, visited) {
244
- if (visited.has(entryId))
245
- return null;
246
- const entry = allEntries[entryId];
247
- if (!entry)
248
- return null;
249
- visited.add(entryId);
250
- const fields = entry.fields;
251
- const ctId = entry.sys.contentType.sys.id;
252
- const label = getEntryLabel(fields, locale);
253
- const assets = extractAssetLinks(fields, locale);
254
- const childIds = getContentChildIds(entry, locale);
255
- const children = [];
256
- for (const childId of childIds) {
257
- const child = buildNodeTree(childId, allEntries, locale, visited);
258
- if (child)
259
- children.push(child);
260
- }
261
- return { id: entryId, contentType: ctId, label, assets, children };
262
- }
263
- function renderNodeLine(node, prefix, isLast) {
264
- const connector = isLast ? '└── ' : '├── ';
265
- const childPrefix = prefix + (isLast ? ' ' : '│ ');
266
- const ct = pc.blue(node.contentType.padEnd(18));
267
- const lbl = pc.white(`"${node.label.length > 45 ? `${node.label.slice(0, 44)}…` : node.label}"`);
268
- const id = pc.dim(`[…${node.id.slice(-6)}]`);
269
- console.log(`${prefix}${connector}${ct} ${lbl} ${id}`);
270
- const assetCount = node.assets.length;
271
- const childCount = node.children.length;
272
- const totalSubs = assetCount + childCount;
273
- let subIdx = 0;
274
- for (const a of node.assets) {
275
- subIdx++;
276
- const ac = subIdx === totalSubs ? '└── ' : '├── ';
277
- console.log(`${childPrefix}${ac}${pc.yellow('🖼')} ${pc.dim(a.fieldName)} → ${pc.dim(a.assetId)}`);
278
- }
279
- for (let i = 0; i < node.children.length; i++) {
280
- const child = node.children[i];
281
- if (child)
282
- renderNodeLine(child, childPrefix, i === node.children.length - 1);
283
- }
284
- }
285
- async function runAuditTree(opts) {
286
- const config = loadConfig(opts.config);
287
- const { key, space } = resolveSpaceConfig(config, opts.space);
288
- const env = await createSafeEnvironment(space);
289
- const locale = space.defaultLocale;
290
- let targetPages;
291
- if (opts.page) {
292
- infoMsg(`Finding page: ${opts.page}…`);
293
- const raw = await findEntryBySlug(env, opts.page, locale);
294
- if (!raw) {
295
- errorMsg(`Page not found: ${opts.page}`);
296
- process.exit(1);
297
- return;
298
- }
299
- const entry = serializeEntry(raw);
300
- const fields = entry.fields;
301
- const rawSlug = String(fields['slug']?.[locale] ?? fields['slug']?.['en-US'] ?? raw.sys.id);
302
- const slug = rawSlug.startsWith('/') ? rawSlug : `/${rawSlug}`;
303
- const title = String(fields['title']?.[locale] ?? fields['title']?.['en-US'] ?? slug);
304
- targetPages = [{ id: raw.sys.id, slug, title }];
305
- }
306
- else {
307
- infoMsg(`Fetching all pages for space "${key}"…`);
308
- targetPages = await fetchAllPageInfos(env, locale);
309
- }
310
- infoMsg(`Building content tree(s) for ${String(targetPages.length)} page(s)…`);
311
- const pageTrees = [];
312
- for (const page of targetPages) {
313
- infoMsg(` ${page.slug}…`);
314
- const allEntries = await fetchEntryTree(env, page.id);
315
- const rootEntry = allEntries[page.id];
316
- if (!rootEntry)
317
- continue;
318
- const visited = new Set([page.id]);
319
- const topLevelIds = getContentChildIds(rootEntry, locale);
320
- const children = [];
321
- for (const childId of topLevelIds) {
322
- const child = buildNodeTree(childId, allEntries, locale, visited);
323
- if (child)
324
- children.push(child);
325
- }
326
- pageTrees.push({ id: page.id, slug: page.slug, title: page.title, children });
327
- }
328
- if (opts.output === 'json' || isJsonMode()) {
329
- console.log(JSON.stringify({ space: key, pages: pageTrees }, null, 2));
330
- return;
331
- }
332
- // Text tree output
333
- console.log(`\n${pc.bold(`Content Tree — ${key}`)}\n`);
334
- for (const pageTree of pageTrees) {
335
- const titleStr = pc.dim(`"${pageTree.title}"`);
336
- const idStr = pc.dim(`[…${pageTree.id.slice(-6)}]`);
337
- console.log(`${pc.cyan(pc.bold(pageTree.slug))} ${titleStr} ${idStr}`);
338
- for (let i = 0; i < pageTree.children.length; i++) {
339
- const child = pageTree.children[i];
340
- if (child)
341
- renderNodeLine(child, '', i === pageTree.children.length - 1);
342
- }
343
- console.log('');
344
- }
345
- }
346
- // ---------------------------------------------------------------------------
347
- // Registration
348
- // ---------------------------------------------------------------------------
349
- export function registerAuditCommand(program) {
350
- const audit = program
351
- .command('audit')
352
- .description('Audit CMS content — asset inventory and content relationship trees. No session required.\n' +
353
- 'Subcommands: images, tree\n' +
354
- 'Examples:\n' +
355
- ' cms-edit --json audit images # full image inventory as JSON\n' +
356
- ' cms-edit audit tree --page / # content tree for the homepage');
357
- audit
358
- .command('images')
359
- .description('List all image assets with their page/component usages.\n' +
360
- 'Outputs a JSON payload designed for the image-guide skill to enrich with AI descriptions.\n' +
361
- 'Use --json flag on the parent command for machine-readable output:\n' +
362
- ' cms-edit --json audit images')
363
- .action(async (_opts, cmd) => {
364
- const parentOpts = cmd.parent?.parent?.opts() ?? {};
365
- try {
366
- await runAuditImages({ space: parentOpts.space, config: parentOpts.config });
367
- }
368
- catch (err) {
369
- errorMsg(err instanceof Error ? err.message : String(err));
370
- process.exit(1);
371
- }
372
- });
373
- audit
374
- .command('tree')
375
- .description('Show the content relationship tree for all pages, or a single page.\n' +
376
- 'Queries Contentful CMA directly — no session or running app needed.\n' +
377
- 'Examples:\n' +
378
- ' cms-edit audit tree # full site tree (text)\n' +
379
- ' cms-edit audit tree --page / # homepage only\n' +
380
- ' cms-edit --json audit tree # JSON output')
381
- .option('--page <slug>', 'Only show the tree for this page slug (e.g. /about)')
382
- .option('--output <format>', 'Output format: text (default) or json (overridden by --json flag)', 'text')
383
- .action(async (opts, cmd) => {
384
- const parentOpts = cmd.parent?.parent?.opts() ?? {};
385
- try {
386
- await runAuditTree({
387
- page: opts.page,
388
- output: opts.output,
389
- space: parentOpts.space,
390
- config: parentOpts.config,
391
- });
392
- }
393
- catch (err) {
394
- errorMsg(err instanceof Error ? err.message : String(err));
395
- process.exit(1);
396
- }
397
- });
398
- }
399
- //# sourceMappingURL=audit.js.map