@aigne/doc-smith 0.9.6-beta → 0.9.6-beta.2

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 (41) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/agents/create/document-structure-tools/delete-document.mjs +53 -9
  3. package/agents/create/update-document-structure.yaml +1 -1
  4. package/agents/create/user-add-document/add-documents-to-structure.mjs +96 -0
  5. package/agents/create/user-add-document/find-documents-to-add-links.yaml +47 -0
  6. package/agents/create/user-add-document/index.yaml +46 -0
  7. package/agents/create/user-add-document/prepare-documents-to-translate.mjs +22 -0
  8. package/agents/create/user-add-document/print-add-document-summary.mjs +63 -0
  9. package/agents/create/user-add-document/review-documents-with-new-links.mjs +110 -0
  10. package/agents/create/user-remove-document/find-documents-with-invalid-links.mjs +78 -0
  11. package/agents/create/user-remove-document/index.yaml +41 -0
  12. package/agents/create/user-remove-document/prepare-documents-to-translate.mjs +22 -0
  13. package/agents/create/user-remove-document/print-remove-document-summary.mjs +53 -0
  14. package/agents/create/user-remove-document/remove-documents-from-structure.mjs +99 -0
  15. package/agents/create/user-remove-document/review-documents-with-invalid-links.mjs +119 -0
  16. package/agents/create/user-review-document-structure.mjs +1 -40
  17. package/agents/create/utils/init-current-content.mjs +38 -0
  18. package/agents/init/index.mjs +3 -4
  19. package/agents/update/document-tools/update-document-content.mjs +12 -12
  20. package/agents/update/update-document-detail.yaml +5 -1
  21. package/agents/update/update-single/update-single-document-detail.mjs +21 -6
  22. package/agents/update/user-review-document.mjs +10 -13
  23. package/agents/utils/add-translates-to-structure.mjs +29 -0
  24. package/agents/utils/{analyze-feedback-intent.yaml → analyze-document-feedback-intent.yaml} +5 -2
  25. package/agents/utils/analyze-structure-feedback-intent.yaml +29 -0
  26. package/agents/utils/check-detail-result.mjs +2 -14
  27. package/agents/utils/load-sources.mjs +36 -46
  28. package/aigne.yaml +10 -1
  29. package/package.json +1 -1
  30. package/prompts/detail/custom/custom-components/x-cards-usage-rules.md +18 -10
  31. package/prompts/structure/find-documents-to-add-links.md +52 -0
  32. package/prompts/utils/analyze-document-feedback-intent.md +54 -0
  33. package/prompts/utils/analyze-structure-feedback-intent.md +43 -0
  34. package/types/document-schema.mjs +2 -0
  35. package/types/document-structure-schema.mjs +6 -2
  36. package/utils/docs-finder-utils.mjs +161 -0
  37. package/utils/file-utils.mjs +9 -7
  38. package/utils/load-config.mjs +21 -4
  39. package/utils/markdown-checker.mjs +50 -5
  40. package/utils/utils.mjs +103 -0
  41. package/prompts/utils/analyze-feedback-intent.md +0 -55
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.9.6-beta.2](https://github.com/AIGNE-io/aigne-doc-smith/compare/v0.9.6-beta.1...v0.9.6-beta.2) (2025-11-20)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * enhance the robustness of add/remove document ([#325](https://github.com/AIGNE-io/aigne-doc-smith/issues/325)) ([f78668a](https://github.com/AIGNE-io/aigne-doc-smith/commit/f78668ad93fb1c9913cfd62de466018f177990b3))
9
+ * ignore video media temporary ([#326](https://github.com/AIGNE-io/aigne-doc-smith/issues/326)) ([e65e7fd](https://github.com/AIGNE-io/aigne-doc-smith/commit/e65e7fda49d870c1e60b433fac121193ee72a328))
10
+
11
+ ## [0.9.6-beta.1](https://github.com/AIGNE-io/aigne-doc-smith/compare/v0.9.6-beta...v0.9.6-beta.1) (2025-11-19)
12
+
13
+
14
+ ### Features
15
+
16
+ * support for add document and remove document ([#323](https://github.com/AIGNE-io/aigne-doc-smith/issues/323)) ([2672942](https://github.com/AIGNE-io/aigne-doc-smith/commit/26729424ca820eb962e79b4746c069887dd5a649))
17
+
3
18
  ## [0.9.6-beta](https://github.com/AIGNE-io/aigne-doc-smith/compare/v0.9.5...v0.9.6-beta) (2025-11-18)
4
19
 
5
20
 
@@ -3,6 +3,7 @@ import {
3
3
  getDeleteDocumentOutputJsonSchema,
4
4
  validateDeleteDocumentInput,
5
5
  } from "../../../types/document-structure-schema.mjs";
6
+ import { userContextAt } from "../../../utils/utils.mjs";
6
7
 
7
8
  export default async function deleteDocument(input, options) {
8
9
  // Validate input using Zod schema
@@ -16,13 +17,28 @@ export default async function deleteDocument(input, options) {
16
17
  };
17
18
  }
18
19
 
19
- const { path } = validation.data;
20
+ const { path, recursive = false } = validation.data;
20
21
  let documentStructure = options?.context?.userContext?.currentStructure;
21
22
 
22
23
  if (!documentStructure) {
23
24
  documentStructure = input.documentStructure;
24
25
  }
25
26
 
27
+ const deletedPathsContext = userContextAt(options, "deletedPaths");
28
+ const deletedPaths = deletedPathsContext.get() || [];
29
+
30
+ // Check if path has already been deleted
31
+ if (recursive) {
32
+ if (deletedPaths.includes(path)) {
33
+ const message = `Skipping duplicate deletion. Document '${path}' has already been deleted.`;
34
+ return {
35
+ documentStructure,
36
+ message,
37
+ deletedDocuments: [],
38
+ };
39
+ }
40
+ }
41
+
26
42
  // Find the document to delete
27
43
  const documentIndex = documentStructure.findIndex((item) => item.path === path);
28
44
  if (documentIndex === -1) {
@@ -36,10 +52,27 @@ export default async function deleteDocument(input, options) {
36
52
 
37
53
  const documentToDelete = documentStructure[documentIndex];
38
54
 
39
- // Check if any other documents have this document as parent
40
- const childDocuments = documentStructure.filter((item) => item.parentId === path);
41
- if (childDocuments.length > 0) {
42
- const errorMessage = `Cannot delete document: Document '${path}' has ${childDocuments.length} child document(s): ${childDocuments.map((p) => p.path).join(", ")}. Please first move or delete these child documents.`;
55
+ // Find all child documents (direct and indirect)
56
+ const findAllChildren = (parentPath, structure) => {
57
+ const children = structure.filter((item) => item.parentId === parentPath);
58
+ const allChildren = [...children];
59
+ for (const child of children) {
60
+ allChildren.push(...findAllChildren(child.path, structure));
61
+ }
62
+ return allChildren;
63
+ };
64
+
65
+ const childDocuments = findAllChildren(path, documentStructure);
66
+
67
+ // If recursive is false and there are child documents, return error
68
+ if (!recursive && childDocuments.length > 0) {
69
+ const errorMessage = `Cannot delete document: Document '${path}' has ${
70
+ childDocuments.length
71
+ } child document(s): ${childDocuments
72
+ .map((p) => p.path)
73
+ .join(
74
+ ", ",
75
+ )}. Please first move or delete these child documents, or set recursive=true to delete them all.`;
43
76
  console.log(`⚠️ ${errorMessage}`);
44
77
  return {
45
78
  documentStructure,
@@ -47,11 +80,22 @@ export default async function deleteDocument(input, options) {
47
80
  };
48
81
  }
49
82
 
50
- // Remove the document from the structure
51
- const updatedStructure = documentStructure.filter((_, index) => index !== documentIndex);
83
+ // Collect all documents to delete (children first, then parent)
84
+ const documentsToDelete = recursive ? [...childDocuments, documentToDelete] : [documentToDelete];
85
+ const pathsToDelete = new Set(documentsToDelete.map((doc) => doc.path));
86
+ const deletedCount = pathsToDelete.size - 1;
87
+
88
+ // Remove all documents from the structure
89
+ const updatedStructure = documentStructure.filter((item) => !pathsToDelete.has(item.path));
90
+
91
+ // Add paths to deleted paths
92
+ if (recursive) {
93
+ deletedPathsContext.set(deletedPaths.concat(Array.from(pathsToDelete)));
94
+ }
52
95
 
96
+ // Build success message
53
97
  const successMessage = `deleteDocument executed successfully.
54
- Successfully deleted document '${documentToDelete.title}' with path '${path}'.
98
+ Successfully deleted document '${documentToDelete.title}' with path '${path}'${recursive && deletedCount > 0 ? ` along with ${deletedCount} child document(s)` : ""}.
55
99
  Check if the latest version of documentStructure meets user feedback, if so, just return 'success'.`;
56
100
 
57
101
  // update shared document structure
@@ -62,7 +106,7 @@ export default async function deleteDocument(input, options) {
62
106
  return {
63
107
  documentStructure: updatedStructure,
64
108
  message: successMessage,
65
- deletedDocument: documentToDelete,
109
+ deletedDocuments: documentsToDelete,
66
110
  };
67
111
  }
68
112
 
@@ -2,7 +2,7 @@ type: team
2
2
  name: updateDocumentStructure
3
3
  description: Update documentation structure based on user feedback and intentions using structure modification tools
4
4
  skills:
5
- - url: ../utils/analyze-feedback-intent.yaml
5
+ - url: ../utils/analyze-structure-feedback-intent.yaml
6
6
  - type: ai
7
7
  instructions:
8
8
  - role: system
@@ -0,0 +1,96 @@
1
+ import { getActiveRulesForScope } from "../../../utils/preferences-utils.mjs";
2
+ import { printDocumentStructure } from "../../../utils/docs-finder-utils.mjs";
3
+ import addTranslatesToStructure from "../../utils/add-translates-to-structure.mjs";
4
+
5
+ export default async function addDocumentsToStructure(input = {}, options = {}) {
6
+ const { originalDocumentStructure = [], translateLanguages = [] } = input;
7
+ const analyzeIntent = options.context?.agents?.["analyzeStructureFeedbackIntent"];
8
+ const updateDocumentStructure = options.context?.agents?.["updateDocumentStructure"];
9
+ const allFeedback = [];
10
+ let currentStructure = [...originalDocumentStructure];
11
+ let isFirstAdd = true;
12
+
13
+ printDocumentStructure(originalDocumentStructure);
14
+
15
+ // update website structure
16
+ if (!options.context.userContext) {
17
+ options.context.userContext = {};
18
+ }
19
+
20
+ // Add document
21
+ while (true) {
22
+ let feedback = await options.prompts.input({
23
+ message: isFirstAdd
24
+ ? "You can add a new document.\n" +
25
+ " • e.g. Add a new document 'Troubleshooting'\n\n" +
26
+ "Press Enter to finish:"
27
+ : "You can continue adding documents, or press Enter to finish:",
28
+ });
29
+
30
+ feedback = feedback.trim();
31
+
32
+ // end the loop
33
+ if (!feedback) {
34
+ break;
35
+ }
36
+
37
+ try {
38
+ // validate feedback
39
+ const { intentType } = await options.context.invoke(analyzeIntent, {
40
+ feedback,
41
+ });
42
+
43
+ if (intentType !== "add") {
44
+ console.log(`⚠️ You can only add documents at this stage.`);
45
+ continue;
46
+ }
47
+ options.context.userContext.currentStructure = currentStructure;
48
+
49
+ const structureRules = getActiveRulesForScope("structure", []);
50
+ const globalRules = getActiveRulesForScope("global", []);
51
+ const allApplicableRules = [...structureRules, ...globalRules];
52
+ const userPreferences = allApplicableRules.map((rule) => rule.rule).join("\n\n");
53
+
54
+ await options.context.invoke(updateDocumentStructure, {
55
+ ...input,
56
+ dataSourceChunk: input.dataSources[0].dataSourceChunk,
57
+ feedback,
58
+ documentStructure: currentStructure,
59
+ needDataSources: true,
60
+ userPreferences,
61
+ });
62
+
63
+ allFeedback.push(feedback);
64
+
65
+ currentStructure = options.context.userContext.currentStructure;
66
+ printDocumentStructure(currentStructure);
67
+ isFirstAdd = false;
68
+ } catch (error) {
69
+ console.error("Error processing feedback:", {
70
+ type: error.name,
71
+ message: error.message,
72
+ });
73
+ process.exit(0);
74
+ }
75
+ }
76
+
77
+ if (currentStructure.length > originalDocumentStructure.length) {
78
+ const originalPaths = new Set(originalDocumentStructure.map((doc) => doc.path));
79
+ const { documentExecutionStructure } = addTranslatesToStructure({
80
+ originalDocumentStructure: currentStructure,
81
+ translateLanguages,
82
+ });
83
+ const newDocuments = documentExecutionStructure.filter((doc) => !originalPaths.has(doc.path));
84
+
85
+ return {
86
+ originalDocumentStructure: currentStructure,
87
+ documentStructure: JSON.parse(JSON.stringify(currentStructure)),
88
+ documentExecutionStructure,
89
+ newDocuments,
90
+ allFeedback,
91
+ };
92
+ } else {
93
+ console.log("No documents were added");
94
+ process.exit(0);
95
+ }
96
+ }
@@ -0,0 +1,47 @@
1
+ name: findDocumentsToAddLinks
2
+ description: Use AI to analyze document structure and determine which documents should reference newly added documents
3
+ task_render_mode: hide
4
+ instructions:
5
+ - role: system
6
+ url: ../../../prompts/structure/find-documents-to-add-links.md
7
+ input_schema:
8
+ type: object
9
+ properties:
10
+ originalDocumentStructure:
11
+ type: array
12
+ description: Original document structure before adding documents
13
+ documentStructure:
14
+ type: array
15
+ description: Updated document structure after adding documents
16
+ newDocuments:
17
+ type: array
18
+ description: Array of newly added documents
19
+ required:
20
+ - originalDocumentStructure
21
+ - documentStructure
22
+ - newDocuments
23
+ output_schema:
24
+ type: object
25
+ properties:
26
+ documentsWithNewLinks:
27
+ type: array
28
+ description: Array of existing documents that should add links to new documents
29
+ items:
30
+ type: object
31
+ properties:
32
+ path:
33
+ type: string
34
+ description: The path of the existing document that should be updated
35
+ newLinks:
36
+ type: array
37
+ description: Array of new document paths that should be added as links to this document
38
+ items:
39
+ type: string
40
+ required:
41
+ - path
42
+ - newLinks
43
+ required:
44
+ - documentsWithNewLinks
45
+
46
+
47
+
@@ -0,0 +1,46 @@
1
+ type: team
2
+ name: userAddDocument
3
+ description: Add documents to the documentation structure
4
+ skills:
5
+ - url: ../../init/index.mjs
6
+ default_input:
7
+ skipIfExists: true
8
+ - ../../utils/load-sources.mjs
9
+ - ./add-documents-to-structure.mjs
10
+ - url: ../../utils/save-output.mjs
11
+ default_input:
12
+ saveKey: documentStructure
13
+ savePath:
14
+ $get: outputDir
15
+ fileName: structure-plan.json
16
+ - ../../utils/save-sidebar.mjs
17
+ - ../../utils/ensure-document-icons.mjs
18
+ - ../../utils/format-document-structure.mjs
19
+ - ../../media/load-media-description.mjs
20
+ - type: team
21
+ skills:
22
+ - ../../update/check-document.mjs
23
+ iterate_on: newDocuments
24
+ concurrency: 5
25
+ - ./find-documents-to-add-links.yaml
26
+ - ./review-documents-with-new-links.mjs
27
+ - type: team
28
+ name: batchAddNewLinks
29
+ description: Batch add new links to documents
30
+ skills:
31
+ - ../utils/init-current-content.mjs
32
+ - ../../utils/transform-detail-data-sources.mjs
33
+ - ../../update/update-single/update-single-document-detail.mjs
34
+ iterate_on: documentsToUpdate
35
+ concurrency: 5
36
+ - ./prepare-documents-to-translate.mjs
37
+ - type: team
38
+ name: batchTranslateDocuments
39
+ description: Batch translate documents to multiple languages
40
+ skills:
41
+ - ../../localize/translate-multilingual.yaml
42
+ iterate_on: documentsToTranslate
43
+ concurrency: 5
44
+ - ../../utils/post-generate.mjs
45
+ - ./print-add-document-summary.mjs
46
+ mode: sequential
@@ -0,0 +1,22 @@
1
+ export default async function prepareDocumentsToTranslate(input, options) {
2
+ const { documentsWithNewLinks = [] } = input;
3
+ const documentsToTranslate = [];
4
+
5
+ documentsWithNewLinks.forEach((doc) => {
6
+ const content = options.context.userContext.currentContents[doc.path];
7
+
8
+ if (content) {
9
+ documentsToTranslate.push({
10
+ ...doc,
11
+ content,
12
+ });
13
+ } else {
14
+ console.warn(`⚠️ Could not find content from userContext at path: ${doc.path}`);
15
+ }
16
+ });
17
+
18
+ return {
19
+ documentsToUpdate: [], // clear, reduce token consumption
20
+ documentsToTranslate,
21
+ };
22
+ }
@@ -0,0 +1,63 @@
1
+ import chalk from "chalk";
2
+
3
+ import { recordUpdate } from "../../../utils/history-utils.mjs";
4
+ /**
5
+ * Print summary of added documents and documents with new links
6
+ */
7
+ export default async function printAddDocumentSummary({
8
+ newDocuments = [],
9
+ documentsWithNewLinks = [],
10
+ allFeedback = [],
11
+ }) {
12
+ let message = `\n---\n`;
13
+ message += `${chalk.bold.cyan("📊 Summary")}\n\n`;
14
+
15
+ // Record the update
16
+ if (allFeedback.length > 0) {
17
+ recordUpdate({
18
+ operation: "structure_update",
19
+ feedback: allFeedback.join("\n"),
20
+ });
21
+ }
22
+
23
+ // Display added documents
24
+ if (newDocuments && newDocuments.length > 0) {
25
+ message += `✨ Added Documents:\n`;
26
+ message += ` Total: ${newDocuments.length} document(s)\n\n`;
27
+ newDocuments.forEach((doc, index) => {
28
+ message += ` ${chalk.cyan(`${index + 1}. ${doc.path}`)}`;
29
+ if (doc.title && doc.title !== doc.path) {
30
+ message += ` - ${chalk.yellow(doc.title)}`;
31
+ }
32
+ message += `\n\n`;
33
+ });
34
+ } else {
35
+ message += `✨ Added Documents:\n`;
36
+ message += `${chalk.gray(" No documents were added.\n\n")}`;
37
+ }
38
+
39
+ // Display documents with new links
40
+ if (documentsWithNewLinks && documentsWithNewLinks.length > 0) {
41
+ message += `✅ Documents updated (Added new links):\n`;
42
+ message += ` Total: ${documentsWithNewLinks.length} document(s)\n\n`;
43
+ documentsWithNewLinks.forEach((doc, index) => {
44
+ message += ` ${chalk.cyan(`${index + 1}. ${doc.path}`)}`;
45
+ if (doc.title && doc.title !== doc.path) {
46
+ message += ` - ${chalk.yellow(doc.title)}`;
47
+ }
48
+ message += `\n`;
49
+ if (doc.newLinks && doc.newLinks.length > 0) {
50
+ message += ` New links added: ${chalk.gray(doc.newLinks.join(", "))}\n`;
51
+ }
52
+ message += `\n`;
53
+ });
54
+ } else {
55
+ message += `✅ Documents updated (Added new links):\n`;
56
+ message += `${chalk.gray(" No documents needed to be updated.\n\n")}`;
57
+ }
58
+
59
+ return { message };
60
+ }
61
+
62
+ printAddDocumentSummary.taskTitle = "Print add document summary";
63
+ printAddDocumentSummary.description = "Display summary of added documents";
@@ -0,0 +1,110 @@
1
+ import { join } from "node:path";
2
+ import chalk from "chalk";
3
+ import pLimit from "p-limit";
4
+ import { generateFileName, pathToFlatName } from "../../../utils/docs-finder-utils.mjs";
5
+ import { pathExists } from "../../../utils/file-utils.mjs";
6
+
7
+ /**
8
+ * Review documentsWithNewLinks and let user select which documents should be updated
9
+ */
10
+ export default async function reviewDocumentsWithNewLinks(
11
+ { documentsWithNewLinks = [], documentExecutionStructure = [], locale = "en", docsDir },
12
+ options,
13
+ ) {
14
+ // If no documents to review, return empty array
15
+ if (!documentsWithNewLinks || documentsWithNewLinks.length === 0) {
16
+ return { documentsWithNewLinks: [], documentsToUpdate: [] };
17
+ }
18
+
19
+ // Build choices with file existence check
20
+ const limit = pLimit(50);
21
+ const choices = await Promise.all(
22
+ documentsWithNewLinks.map((document, index) =>
23
+ limit(async () => {
24
+ // Find corresponding document in documentStructure to get title
25
+ const structureDoc = documentExecutionStructure.find((item) => item.path === document.path);
26
+ const title = structureDoc?.title || document.path;
27
+
28
+ // Generate filename from document path
29
+ const flatName = pathToFlatName(document.path);
30
+ const filename = generateFileName(flatName, locale);
31
+
32
+ // Check file existence if docsDir is provided
33
+ let fileExists = true;
34
+ let missingFileText = "";
35
+ if (docsDir) {
36
+ const filePath = join(docsDir, filename);
37
+ fileExists = await pathExists(filePath);
38
+ if (!fileExists) {
39
+ missingFileText = chalk.red(" - file not found");
40
+ }
41
+ }
42
+
43
+ return {
44
+ name: `${title} (${filename})${missingFileText}`,
45
+ value: index,
46
+ checked: fileExists, // Only check if file exists
47
+ disabled: !fileExists, // Disable if file doesn't exist
48
+ description: `New Links: ${document.newLinks.join(", ")}`,
49
+ };
50
+ }),
51
+ ),
52
+ );
53
+
54
+ // Let user select which documents to update (default: all selected)
55
+ const selectedDocs = await options.prompts.checkbox({
56
+ message:
57
+ "Select documents that need new links added (all selected by default, press Enter to confirm, or unselect all to skip):",
58
+ choices,
59
+ });
60
+
61
+ // Filter documentsWithNewLinks based on user selection
62
+ const filteredDocs = selectedDocs.map((index) => documentsWithNewLinks[index]).filter(Boolean);
63
+
64
+ if (filteredDocs.length === 0) {
65
+ console.log(`\n⚠️ No documents selected. Skipping link updates.\n`);
66
+ } else {
67
+ console.log(
68
+ `\n✅ Selected ${filteredDocs.length} out of ${documentsWithNewLinks.length} documents to update.\n`,
69
+ );
70
+ }
71
+
72
+ // save original documentsWithNewLinks to user context
73
+ options.context.userContext.originalDocumentsWithNewLinks = filteredDocs;
74
+
75
+ if (filteredDocs.length === 0) {
76
+ return {
77
+ documentsWithNewLinks: [],
78
+ documentsToUpdate: [],
79
+ };
80
+ }
81
+
82
+ // Prepare documents: add necessary fields for update (e.g. feedback)
83
+ const preparedDocs = [];
84
+
85
+ for (const doc of filteredDocs) {
86
+ if (!doc.path) continue;
87
+
88
+ // Find corresponding document in documentStructure to get additional fields
89
+ const structureDoc = documentExecutionStructure.find((item) => item.path === doc.path);
90
+
91
+ // Generate feedback message for adding new links
92
+ const newLinksList = doc.newLinks.join(", ");
93
+ const feedback = `Add the following links to this document: ${newLinksList}. Identify suitable places within the existing content — such as relevant sections, navigation items — and insert the links naturally to maintain context and readability.`;
94
+
95
+ preparedDocs.push({
96
+ ...structureDoc,
97
+ feedback,
98
+ newLinks: doc.newLinks,
99
+ });
100
+ }
101
+
102
+ return {
103
+ documentsWithNewLinks: preparedDocs, // for print summary
104
+ documentsToUpdate: JSON.parse(JSON.stringify(preparedDocs)), // for batch update
105
+ };
106
+ }
107
+
108
+ reviewDocumentsWithNewLinks.taskTitle = "Review documents to update";
109
+ reviewDocumentsWithNewLinks.description =
110
+ "Let the user review and select which documents should be updated with new links";
@@ -0,0 +1,78 @@
1
+ import { join } from "node:path";
2
+ import {
3
+ buildAllowedLinksFromStructure,
4
+ generateFileName,
5
+ pathToFlatName,
6
+ readFileContent,
7
+ } from "../../../utils/docs-finder-utils.mjs";
8
+ import { pathExists } from "../../../utils/file-utils.mjs";
9
+ import { checkMarkdown, getLinkFromError } from "../../../utils/markdown-checker.mjs";
10
+
11
+ export default async function findDocumentsWithInvalidLinks({
12
+ documentStructure = [],
13
+ docsDir,
14
+ locale = "en",
15
+ }) {
16
+ if (!Array.isArray(documentStructure) || documentStructure.length === 0) {
17
+ return {
18
+ documentsWithInvalidLinks: [],
19
+ };
20
+ }
21
+
22
+ if (!docsDir) {
23
+ return {
24
+ documentsWithInvalidLinks: [],
25
+ error: "docsDir is required to check document links",
26
+ };
27
+ }
28
+
29
+ // Check each document for invalid links
30
+ const allowedLinks = buildAllowedLinksFromStructure(documentStructure);
31
+ const documentsWithInvalidLinks = [];
32
+
33
+ for (const doc of documentStructure) {
34
+ if (!doc.path) continue;
35
+
36
+ // Generate filename from document path
37
+ const flatName = pathToFlatName(doc.path);
38
+ const fileName = generateFileName(flatName, locale);
39
+
40
+ // Check if file exists before reading
41
+ const filePath = join(docsDir, fileName);
42
+ const fileExists = await pathExists(filePath);
43
+
44
+ if (!fileExists) {
45
+ // Skip if file doesn't exist
46
+ continue;
47
+ }
48
+
49
+ // Read document content
50
+ const content = await readFileContent(docsDir, fileName);
51
+
52
+ if (!content) {
53
+ // Skip if content cannot be read
54
+ continue;
55
+ }
56
+
57
+ // Use checkMarkdown to check for dead links
58
+ const allErrors = await checkMarkdown(content, doc.path, {
59
+ allowedLinks,
60
+ baseDir: docsDir,
61
+ });
62
+
63
+ // Filter only dead link errors and extract invalid links
64
+ const invalidLinks = allErrors.map(getLinkFromError).filter(Boolean);
65
+
66
+ if (invalidLinks.length > 0) {
67
+ documentsWithInvalidLinks.push({
68
+ path: doc.path,
69
+ title: doc.title || doc.path,
70
+ invalidLinks,
71
+ });
72
+ }
73
+ }
74
+
75
+ return {
76
+ documentsWithInvalidLinks,
77
+ };
78
+ }
@@ -0,0 +1,41 @@
1
+ type: team
2
+ name: userRemoveDocument
3
+ description: Remove documents from the documentation structure
4
+ skills:
5
+ - url: ../../init/index.mjs
6
+ default_input:
7
+ skipIfExists: true
8
+ - ../../utils/load-sources.mjs
9
+ - ./remove-documents-from-structure.mjs
10
+ - url: ../../utils/save-output.mjs
11
+ default_input:
12
+ saveKey: documentStructure
13
+ savePath:
14
+ $get: outputDir
15
+ fileName: structure-plan.json
16
+ - ../../utils/save-sidebar.mjs
17
+ - ./find-documents-with-invalid-links.mjs
18
+ - ../../utils/add-translates-to-structure.mjs
19
+ - ./review-documents-with-invalid-links.mjs
20
+ - ../../utils/format-document-structure.mjs
21
+ - ../../media/load-media-description.mjs
22
+ - type: team
23
+ name: batchRemoveInvalidLinks
24
+ description: Batch remove invalid links from documents
25
+ skills:
26
+ - ../utils/init-current-content.mjs
27
+ - ../../utils/transform-detail-data-sources.mjs
28
+ - ../../update/update-single/update-single-document-detail.mjs
29
+ iterate_on: documentsToUpdate
30
+ concurrency: 5
31
+ - ./prepare-documents-to-translate.mjs
32
+ - type: team
33
+ name: batchTranslateDocuments
34
+ description: Batch translate documents to multiple languages
35
+ skills:
36
+ - ../../localize/translate-multilingual.yaml
37
+ iterate_on: documentsToTranslate
38
+ concurrency: 5
39
+ - ../../utils/post-generate.mjs
40
+ - ./print-remove-document-summary.mjs
41
+ mode: sequential
@@ -0,0 +1,22 @@
1
+ export default async function prepareDocumentsToTranslate(input, options) {
2
+ const { documentsWithInvalidLinks = [] } = input;
3
+ const documentsToTranslate = [];
4
+
5
+ documentsWithInvalidLinks.forEach((doc) => {
6
+ const content = options.context.userContext.currentContents[doc.path];
7
+
8
+ if (content) {
9
+ documentsToTranslate.push({
10
+ ...doc,
11
+ content,
12
+ });
13
+ } else {
14
+ console.warn(`⚠️ Could not find content from userContext at path: ${doc.path}`);
15
+ }
16
+ });
17
+
18
+ return {
19
+ documentsToUpdate: [], // clear, reduce token consumption
20
+ documentsToTranslate,
21
+ };
22
+ }