@aigne/doc-smith 0.8.15-beta → 0.8.15-beta.10

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 (89) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/agents/clear/choose-contents.mjs +4 -4
  3. package/agents/clear/clear-auth-tokens.mjs +8 -8
  4. package/agents/clear/clear-deployment-config.mjs +2 -2
  5. package/agents/clear/clear-document-config.mjs +3 -3
  6. package/agents/clear/clear-document-structure.mjs +10 -10
  7. package/agents/clear/clear-generated-docs.mjs +103 -14
  8. package/agents/clear/clear-media-description.mjs +7 -7
  9. package/agents/evaluate/document-structure.yaml +3 -1
  10. package/agents/evaluate/document.yaml +3 -1
  11. package/agents/evaluate/index.yaml +1 -3
  12. package/agents/generate/check-diagram.mjs +1 -1
  13. package/agents/generate/check-need-generate-structure.mjs +2 -7
  14. package/agents/generate/draw-diagram.yaml +4 -0
  15. package/agents/generate/generate-structure.yaml +117 -65
  16. package/agents/generate/index.yaml +3 -3
  17. package/agents/generate/{merge-d2-diagram.yaml → merge-diagram.yaml} +7 -6
  18. package/agents/generate/update-document-structure.yaml +1 -1
  19. package/agents/generate/user-review-document-structure.mjs +1 -0
  20. package/agents/generate/utils/merge-document-structures.mjs +30 -0
  21. package/agents/init/check.mjs +3 -1
  22. package/agents/init/index.mjs +37 -7
  23. package/agents/media/load-media-description.mjs +12 -24
  24. package/agents/publish/publish-docs.mjs +3 -8
  25. package/agents/schema/document-execution-structure.yaml +1 -1
  26. package/agents/schema/document-structure-item.yaml +23 -0
  27. package/agents/schema/document-structure-refine-item.yaml +20 -0
  28. package/agents/schema/document-structure.yaml +1 -1
  29. package/agents/translate/index.yaml +1 -4
  30. package/agents/translate/record-translation-history.mjs +6 -2
  31. package/agents/translate/translate-multilingual.yaml +1 -1
  32. package/agents/update/batch-generate-document.yaml +1 -1
  33. package/agents/update/batch-update-document.yaml +1 -1
  34. package/agents/update/check-document.mjs +50 -13
  35. package/agents/update/check-generate-diagram.mjs +26 -0
  36. package/agents/update/generate-diagram.yaml +29 -0
  37. package/agents/update/generate-document.yaml +17 -30
  38. package/agents/update/handle-document-update.yaml +10 -1
  39. package/agents/update/save-and-translate-document.mjs +18 -47
  40. package/agents/update/update-document-detail.yaml +2 -1
  41. package/agents/update/update-single-document.yaml +1 -1
  42. package/agents/update/user-review-document.mjs +6 -5
  43. package/agents/utils/choose-docs.mjs +8 -2
  44. package/agents/utils/load-sources.mjs +132 -57
  45. package/agents/utils/{save-docs.mjs → post-generate.mjs} +2 -51
  46. package/agents/utils/save-doc-translation.mjs +27 -0
  47. package/agents/utils/{save-single-doc.mjs → save-doc.mjs} +17 -12
  48. package/agents/utils/save-sidebar.mjs +59 -0
  49. package/agents/utils/transform-detail-data-sources.mjs +45 -0
  50. package/aigne.yaml +16 -8
  51. package/package.json +2 -1
  52. package/prompts/common/document/content-rules-core.md +6 -6
  53. package/prompts/common/document/media-file-list-usage-rules.md +12 -0
  54. package/prompts/common/document/openapi-usage-rules.md +36 -0
  55. package/prompts/common/document/role-and-personality.md +1 -2
  56. package/prompts/common/document-structure/conflict-resolution-guidance.md +2 -2
  57. package/prompts/common/document-structure/document-structure-rules.md +8 -8
  58. package/prompts/common/document-structure/output-constraints.md +3 -3
  59. package/prompts/detail/custom/custom-components.md +38 -3
  60. package/prompts/detail/d2-diagram/rules.md +11 -14
  61. package/prompts/detail/d2-diagram/system-prompt.md +33 -21
  62. package/prompts/detail/d2-diagram/user-prompt.md +39 -0
  63. package/prompts/detail/generate/document-rules.md +3 -3
  64. package/prompts/detail/generate/system-prompt.md +2 -6
  65. package/prompts/detail/generate/user-prompt.md +20 -24
  66. package/prompts/detail/update/system-prompt.md +2 -6
  67. package/prompts/detail/update/user-prompt.md +7 -6
  68. package/prompts/evaluate/document.md +0 -4
  69. package/prompts/structure/check-document-structure.md +4 -4
  70. package/prompts/structure/generate/system-prompt.md +0 -31
  71. package/prompts/structure/generate/user-prompt.md +99 -26
  72. package/prompts/structure/review/structure-review-system.md +79 -0
  73. package/prompts/structure/update/system-prompt.md +1 -1
  74. package/prompts/structure/update/user-prompt.md +4 -4
  75. package/prompts/translate/code-block.md +13 -3
  76. package/prompts/translate/translate-document.md +1 -1
  77. package/types/document-structure-schema.mjs +3 -3
  78. package/utils/docs-finder-utils.mjs +48 -0
  79. package/utils/extract-api.mjs +32 -0
  80. package/utils/file-utils.mjs +124 -93
  81. package/utils/history-utils.mjs +20 -8
  82. package/utils/load-config.mjs +1 -1
  83. package/utils/markdown-checker.mjs +35 -1
  84. package/utils/openapi/index.mjs +24 -0
  85. package/utils/utils.mjs +67 -65
  86. package/agents/generate/document-structure-tools/generate-sub-structure.mjs +0 -131
  87. package/agents/generate/generate-structure-without-tools.yaml +0 -65
  88. package/agents/utils/transform-detail-datasources.mjs +0 -23
  89. package/prompts/common/document/media-handling-rules.md +0 -9
@@ -1,32 +1,73 @@
1
+ <data_sources>
2
+ Following are the partial or complete data sources provided by the user to help you design the document structure. Use these data sources to inform your structural planning.
1
3
 
2
- {% include "../../common/document-structure/user-locale-rules.md" %}
4
+ {{ dataSources }}
3
5
 
4
- {% include "../../common/document-structure/user-preferences.md" %}
5
6
 
7
+ NOTICE: There are additional data source contents not displayed. When operating on the document structure, be sure to consider these undisplayed contents and do not easily delete any nodes unless users explicitly request deletion.
8
+ </data_sources>
6
9
 
7
- <file_list>
8
- {{allFilesPaths}}
9
- </file_list>
10
+ {% if userContext.openAPISpec %}
11
+ <openapi>
10
12
 
11
- <datasources>
12
- {{ datasources }}
13
- </datasources>
13
+ **Goal:** Use the provided OpenAPI (Swagger) specification to design how the OpenAPI content and the overall document should be structured together.
14
+
15
+ **OpenAPI File Content:**
16
+ <openapi_doc>
17
+
18
+ {{ userContext.openAPISpec }}
19
+
20
+ </openapi_doc>
21
+
22
+ ---
23
+
24
+ ### **Documentation Requirements and Constraints**
25
+
26
+ 1. **Section structure and titles:**
27
+ * Create a dedicated top-level section for the OpenAPI content.
28
+ * The section title must be professional and user friendly; **never** include terms such as OpenAPI, Swagger, or file formats. Recommended titles include **"API Interface Reference"** or **"Interface Reference"**.
29
+
30
+ 2. **Content hierarchy and presentation:**
31
+ * **Ideal state (single-level page):** Prefer to present all API endpoints within **one Markdown file (one page)**.
32
+ * **Split criteria (two-level pages):** Only when the number of endpoints is too large for a single file should you split by OpenAPI tags or logical modules, creating individual Markdown files per module.
33
+ * **Forced file hierarchy constraint:** Whether using one or two levels, the generated API reference files (Markdown) may contain **no more than two levels.**
34
+ * **Example (two-level structure):** `/api-reference.md` (index) -> `/api/user.md`, `/api/order.md` (module pages)
35
+ * **Disallow any third level or deeper structure:** for example, `/api/v1/user/get.md`.
36
+
37
+ 3. **Mandatory API description constraints (deduplication rule):**
38
+ * **Ensure that for the entire document (including preface, overview, etc.), any introduction to the project APIs appears only within this OpenAPI-generated "API reference" section.**
39
+ * **Never** repeat or extend the API list elsewhere in the document (for example, "Quick Start" or "Architecture Overview" sections).
40
+
41
+ </openapi>
42
+ {% endif %}
14
43
 
15
44
 
16
- {% if originalDocumentStructure %}
17
45
  <last_document_structure>
18
- {{originalDocumentStructure}}
46
+ projectName: |
47
+ {{projectName}}
48
+ projectDesc: |
49
+ {{projectDesc}}
50
+
51
+ {% if originalDocumentStructure %}
52
+ {{ originalDocumentStructure | yaml.stringify }}
53
+ {% elseif userContext.originalDocumentStructure %}
54
+ {{ userContext.originalDocumentStructure | yaml.stringify }}
55
+ No previous document structure provided. generate a new structure based on the data sources!
56
+ {% endif %}
57
+
19
58
  </last_document_structure>
20
59
 
21
60
 
61
+ {% include "../../common/document-structure/user-locale-rules.md" %}
62
+
63
+ {% include "../../common/document-structure/user-preferences.md" %}
64
+
22
65
  <last_document_structure_rule>
23
66
  If a previous structural plan (last_document_structure) is provided, follow these rules:
24
67
  1. **Feedback Implementation**: The new structural plan **must** correctly implement all changes requested in user feedback.
25
68
  2. **Unrelated Node Stability**: Nodes not mentioned in user feedback **must not have their path or sourcesIds attributes modified**. `path` and `sourcesIds` are critical identifiers linking existing content, and their stability is paramount.
26
69
  Ideally, other attributes (such as `title`, `description`) should also remain stable, unless these changes are directly caused by a requested modification or result from DataSource updates.
27
70
  </last_document_structure_rule>
28
- {% endif %}
29
-
30
71
 
31
72
  {% if documentStructure %}
32
73
  <review_document_structure>
@@ -55,30 +96,62 @@ The current process is planning sub-structures for the following section:
55
96
  {{parentDocument}}
56
97
 
57
98
  Sub-structures must meet the following requirements:
58
- - Sub-structures are planned based on DataSources and the parent document's description
99
+ - Sub-structures are planned based on `<data_sources>` and the parent document's description
59
100
  - The parent document provides an overview of the planned content, while sub-structures directly plan the specific content to be displayed
60
101
  - Further break down and comprehensively display the content planned in the parent document
61
- - All sub-structures must have their parentId value set to {{parentDocument.path}}
102
+ - All sub-structures must have their parentPath value set to {{parentDocument.path}}
62
103
  </parent_document>
63
104
  {% endif %}
64
105
 
65
106
  <instructions>
66
- Your task is to design a detailed structural plan for the document to be generated. This plan will serve as a "blueprint" for subsequent content generation, guiding the LLM on how to organize and present information, ensuring the document is logically clear, easy to understand, well-structured, and comprehensive.
107
+ Your task is to **analyze, refine, and adjust** the existing document structure (`last_document_structure`) based on the partial code repository content currently provided, generating a structural update plan.
108
+ You are not creating a structure from scratch, but rather **performing intelligent updates based on understanding the existing structure** to make the document structure more accurately reflect the latest code content, architectural changes, and logical relationships.
109
+
110
+ ## When using `<data_sources>` data sources, please note the following:
111
+
112
+ - Fully respect the project descriptions and usage instructions in README files, as these typically summarize the project's core functionality and objectives.
113
+ - Pay attention to comments and docstrings in source code files, as these reveal the design intent and usage methods of the code.
114
+ - Understand the relationships between various modules and files, which helps build a logically clear and well-structured document hierarchy.
115
+ - Notice key concepts, APIs, and configuration options in the code, as these are typically important components of the document structure.
116
+ - The generated document structure must include all public modules, interfaces, and features to ensure document completeness and usability.
117
+
118
+
119
+ ## Objective
120
+
121
+ Your output should contain a `structures` array with document structure items that need to be added or updated:
122
+
123
+ - **structures**: Array of document structure items representing incremental changes to the existing document structure. Each item should include a `path` field - the system will automatically replace existing items with matching paths or add new items if the path doesn't exist.
124
+
125
+ IMPORTANT: You should avoid duplicating existing structure items. Only include items that are genuinely new or need updates. The system will automatically merge these changes with the existing document structure based on the `path` field.
126
+
127
+ ## Behavior Rules
128
+
129
+ 1. **Understanding and Inheritance**
130
+ - Fully understand the hierarchical logic, section divisions, and naming style in `<last_document_structure>`.
131
+ - Perform incremental updates based on this foundation, not complete rewrites.
132
+ - Preserve existing reasonable structures, only modify or extend when there is clear justification.
133
+
134
+ 2. **Contextual Association Analysis**
135
+ - You will receive part of the code repository content (such as partial source files or directory content), please analyze their **documentation value and structural impact**.
136
+ - Identify which parts represent new concepts, APIs, modules, configurations, or features; determine if they require adding or modifying corresponding sections in the document structure.
67
137
 
68
- Key capabilities and behavioral principles:
69
- - Data Comprehension: Ability to parse and understand structured and unstructured data, identifying key concepts, entities, attributes, relationships, and processes within them.
70
- - Structured Thinking: Strong logical analysis capabilities to decompose complex information into clear chapters, sections, and items, establishing reasonable hierarchical relationships.
71
- - User-Oriented Approach: Ability to flexibly adjust the focus and level of detail in structural planning based on document objectives and audience characteristics provided by users.
72
- - Modular Design: Tendency to divide documents into independent, reusable modules or sections for easy content population and subsequent maintenance.
73
- - Flexibility and Adaptability: Ability to handle multiple types of data sources and design the most suitable documentation structure based on data source characteristics (such as code function/class structures, API endpoints/parameters, text paragraphs/themes).
74
- - Clarity and Completeness: Ensure the final structural plan is easy to understand and can guide the LLM to generate a comprehensive and well-organized document.
138
+ 3. **Structure Adjustment Strategy**
139
+ - If new content supplements details of existing sections, include the updated item in the `structures` array with the same path.
140
+ - If new content introduces new topics, modules, or hierarchies, include new items in the `structures` array with new paths.
141
+ - Ensure the position, hierarchy, and naming of new nodes align with the overall document logic.
75
142
 
143
+ 4. **Consistency and Clarity**
144
+ - Ensure new or modified structure items are consistent with existing structure style.
145
+ - Each structure node (whether new or updated) should include:
146
+ - **Title**
147
+ - **Brief description in one sentence**, describing main content and purpose
148
+ - Maintain clear hierarchy, avoid duplication, ensure logical coherence. Excellent documentation should allow users to quickly understand project structure and content distribution, organized by modules, functional features, and other dimensions.
76
149
 
77
- Objectives:
78
- - Create a clear and logical structural plan that comprehensively presents information from the user-provided context while providing users with intuitive navigation paths.
79
- - Each {{nodeName}} should include: a {{nodeName}} title, a one-sentence introduction describing its main content, with presentation and organization methods tailored to the target audience.
150
+ 5. **Requirements**
151
+ - Follow all rules and guidelines in `<document_structure_rules>`.
152
+ - Generate rich document structure where functional modules must have sub-documents, comprehensively covering the codebase's functionality and modules, ensuring users can easily get started, understand, and use various modules and main features of the project through documentation.
80
153
 
81
154
  {% include "../../common/document-structure/intj-traits.md" %}
82
155
 
83
- Always follow one principle: You must ensure the final structural plan meets user requirements.
156
+ You must make reasonable incremental modifications based solely on the new information provided while respecting the existing structure, ensuring the final structure remains complete, clear, and extensible.
84
157
  </instructions>
@@ -0,0 +1,79 @@
1
+ <role_and_goal>
2
+ You are a **Documentation Structure Refiner** with the analytical mindset of an **INTJ (The Architect)**. You combine expert knowledge in technical documentation architecture and information design with strategic thinking, systematic analysis, and perfectionist attention to detail. Your core strengths are understanding complex systems, creating logically sound blueprints, and anticipating future documentation challenges.
3
+ </role_and_goal>
4
+
5
+ <document_info>
6
+ projectName: |
7
+ {{projectName}}
8
+ projectDesc: |
9
+ {{projectDesc}}
10
+ </document_info>
11
+
12
+ <document_structure>
13
+ {{ documentStructure | yaml.stringify }}
14
+ </document_structure>
15
+
16
+ <instructions>
17
+
18
+ Your task:
19
+ Given an existing document structure (a JSON array or tree of sections), refine and optimize its **hierarchy and order** to improve clarity, usability, and conventional organization.
20
+ ️ You must not add or rename any nodes. You may delete nodes when necessary for better organization and adjust the **order** and **nesting levels** of existing nodes.
21
+
22
+ ---
23
+
24
+ ## Optimization Goals
25
+
26
+ 1. **Logical Order**
27
+ - Introductory materials should always appear at the beginning:
28
+ - “Overview”, “Introduction”, “Quick Start”, “Getting Started”, “Setup” should be near the top.
29
+ - Meta and community-related sections (e.g., “Community”, “Contributing”, “License”, “Changelog”) should always be at the end.
30
+ - Technical reference and configuration sections should appear after conceptual and usage sections.
31
+
32
+ 2. **Hierarchy Correction**
33
+ - Ensure proper depth:
34
+ - “Overview” and “Quick Start” should have **1–2 levels max**.
35
+ - Remove deeply nested technical details from “Overview” or “Quick Start”.
36
+ - Relocate such details under “Architecture”, “API Reference”, or “Modules”.
37
+ - Keep beneficial nodes — you may delete duplicated, redundant, or harmful nodes when needed for clarity.
38
+
39
+ 3. **Grouping and Alignment**
40
+ - Align similar nodes logically (e.g., group “Usage”, “Examples”, “Tutorials” together).
41
+ - Avoid duplication or overlap by reordering or strategic deletion when necessary.
42
+
43
+ 4. **Naming and Identity**
44
+ - You are **not allowed to rename or reword** any section titles or descriptions.
45
+ - Keep all existing keys, identifiers, and text intact.
46
+
47
+ 5. **Balance**
48
+ - Maintain a clean, well-organized hierarchy.
49
+ - Keep top-level nodes concise (≤ 8 preferred).
50
+ - Avoid over-nesting (≤ 4 levels deep).
51
+
52
+ ---
53
+
54
+ ## Behavior Rules
55
+
56
+ - Do **not** add new nodes.
57
+ - You **may** delete nodes when they are redundant, duplicated, or detrimental to documentation clarity.
58
+ - Do **not** rename or rewrite content.
59
+ - You **may** move nodes to different parents or reorder siblings to achieve better logical flow.
60
+ - You **must** maintain structural integrity for all remaining nodes.
61
+ - The output must be a complete, valid document structure array matching the expected schema.
62
+
63
+ ---
64
+
65
+ ## Objective
66
+
67
+ Output a complete `structures` array containing the optimized document structure:
68
+ 1. Include ALL nodes from the input structure (whether modified or not)
69
+ 2. Each item must include: `id`, `title`, `description`, `path`, `parentPath` (if not top-level)
70
+ 3. Apply your optimizations through proper ordering, hierarchy changes, and selective deletion
71
+ 4. Maintain all required fields and ensure paths are valid (start with /, no spaces/special chars)
72
+ 5. **Important**: Only modify structural aspects (`id`, `title`, `description`, `path`, `parentPath`). Do NOT modify `sourceIds` or other data fields
73
+
74
+ **Optimization Approach:**
75
+ - Reorder nodes by adjusting their position in the array
76
+ - Change hierarchy by modifying `parentPath` values (use the path of the new parent node)
77
+ - Delete problematic nodes by simply omitting them from the output array
78
+ - Keep beneficial nodes with their original content intact
79
+ </instructions>
@@ -99,7 +99,7 @@ Analyze the user feedback to determine the intended operation:
99
99
 
100
100
  When to use Tools:
101
101
  - During document structure update, if the given context is missing or lacks referenced content, use glob/grep/readFile to obtain more context
102
- - When sourceIds or file content from <file_list> is needed but not provided in DataSources, use readFile to read the file content
102
+ - When sourceIds or file content from `<file_list>` is needed but not provided in `<data_sources>`, use readFile to read the file content
103
103
  </file_tool_usage>
104
104
 
105
105
 
@@ -6,9 +6,9 @@
6
6
  {{allFilesPaths}}
7
7
  </file_list>
8
8
 
9
- <datasources>
10
- {{ datasources }}
11
- </datasources>
9
+ <data_sources>
10
+ {{ dataSources }}
11
+ </data_sources>
12
12
 
13
13
 
14
14
  Initial Documentation Structure:
@@ -38,5 +38,5 @@ Processing workflow:
38
38
 
39
39
  Rules:
40
40
  ** All changes must be made using Tools. **
41
- ** Carefully check if the latest version of documentStructure data meets user requirements, must avoid duplicate Tool calls. **
41
+ ** Carefully check if the latest version of `<document_structure>` data meets user requirements, must avoid duplicate Tool calls. **
42
42
  </instructions>
@@ -2,13 +2,23 @@
2
2
  The following formats are considered Code Blocks:
3
3
 
4
4
  - Wrapped with ```
5
- - Supports configurations: language, title, icon, where title and icon are optional
5
+ - Supports configurations: language, optional title, optional icon (icon uses key=value)
6
+ - title is free text placed after the language (not as title=xxx), may contain spaces, and **must NEVER be wrapped in quotes**
6
7
  - content can be code, command line examples, text or any other content
7
8
 
8
9
  <code_block_sample>
9
10
 
10
- ```{language} [{title}] [icon={icon}]
11
- {content}
11
+ - `language`: javascript
12
+ - `title`: Modern: Using createRoot()
13
+ - `icon`: logos:javascript
14
+
15
+ ```javascript Modern: Using createRoot() icon=logos:javascript
16
+ import { createRoot } from 'react-dom/client'
17
+
18
+ const container = document.getElementById('root')
19
+ const root = createRoot(container)
20
+
21
+ root.unmount()
12
22
  ```
13
23
 
14
24
  </code_block_sample>
@@ -299,5 +299,5 @@ Original text as follows:
299
299
  </content>
300
300
 
301
301
  <output_constraints>
302
- Please **accurately** translate the content within <content> tags (excluding the outermost <content> tags) into **{{ language }}**, strictly following the translation requirements.
302
+ Please **accurately** translate the content within `<content>` tags (excluding the outermost `<content>` tags) into **{{ language }}**, strictly following the translation requirements.
303
303
  </output_constraints>
@@ -6,7 +6,7 @@ export const documentItemSchema = z.object({
6
6
  title: z.string().min(1, "Title is required"),
7
7
  description: z.string().min(1, "Description is required"),
8
8
  path: z.string().startsWith("/", 'Path must start with "/"'),
9
- parentId: z.string().nullable(),
9
+ parentId: z.string().nullish(),
10
10
  sourceIds: z.array(z.string()).min(1, "At least one source ID is required"),
11
11
  });
12
12
 
@@ -18,7 +18,7 @@ export const addDocumentInputSchema = z.object({
18
18
  title: z.string().min(1, "Title is required"),
19
19
  description: z.string().min(1, "Description is required"),
20
20
  path: z.string().startsWith("/", 'Path must start with "/"'),
21
- parentId: z.string().nullable().optional(),
21
+ parentId: z.string().nullish(),
22
22
  sourceIds: z.array(z.string()).min(1, "At least one source ID is required"),
23
23
  });
24
24
 
@@ -44,7 +44,7 @@ export const deleteDocumentOutputSchema = z.object({
44
44
  // Move document schemas
45
45
  export const moveDocumentInputSchema = z.object({
46
46
  path: z.string().min(1, "Path is required"),
47
- newParentId: z.string().nullable().optional(),
47
+ newParentId: z.string().nullish(),
48
48
  });
49
49
 
50
50
  export const moveDocumentOutputSchema = z.object({
@@ -1,5 +1,6 @@
1
1
  import { access, readdir, readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { pathExists } from "./file-utils.mjs";
3
4
 
4
5
  /**
5
6
  * Get action-specific text based on isTranslate flag
@@ -276,3 +277,50 @@ export function addFeedbackToItems(items, feedback) {
276
277
  feedback: feedback.trim(),
277
278
  }));
278
279
  }
280
+
281
+ /**
282
+ * Load document execution structure from structure-plan.json
283
+ * @param {string} outputDir - Output directory containing structure-plan.json
284
+ * @returns {Promise<Array|null>} Document execution structure array or null if not found/failed
285
+ */
286
+ export async function loadDocumentStructure(outputDir) {
287
+ if (!outputDir) {
288
+ return null;
289
+ }
290
+
291
+ try {
292
+ const structurePlanPath = join(outputDir, "structure-plan.json");
293
+ const structureExists = await pathExists(structurePlanPath);
294
+
295
+ if (!structureExists) {
296
+ return null;
297
+ }
298
+
299
+ const structureContent = await readFile(structurePlanPath, "utf8");
300
+ if (!structureContent?.trim()) {
301
+ return null;
302
+ }
303
+
304
+ try {
305
+ // Validate that the content looks like JSON before parsing
306
+ const trimmedContent = structureContent.trim();
307
+ if (!trimmedContent.startsWith("[") && !trimmedContent.startsWith("{")) {
308
+ console.warn("structure-plan.json contains non-JSON content, skipping parse");
309
+ return null;
310
+ }
311
+
312
+ const parsed = JSON.parse(structureContent);
313
+ // Return array if it's an array, otherwise return null
314
+ return Array.isArray(parsed) ? parsed : null;
315
+ } catch (parseError) {
316
+ console.error(`Failed to parse structure-plan.json: ${parseError.message}`);
317
+ return null;
318
+ }
319
+ } catch (readError) {
320
+ // Only warn if it's not a "file not found" error
321
+ if (readError.code !== "ENOENT") {
322
+ console.warn(`Error reading structure-plan.json: ${readError.message}`);
323
+ }
324
+ return null;
325
+ }
326
+ }
@@ -0,0 +1,32 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { transpileDeclaration } from "typescript";
3
+
4
+ export async function extractApi(path) {
5
+ const content = await readFile(path, "utf8");
6
+
7
+ const lang = languages.find((lang) => lang.match(path, content));
8
+ if (lang) {
9
+ return lang.extract(path, content);
10
+ }
11
+
12
+ return content;
13
+ }
14
+
15
+ const languages = [
16
+ {
17
+ match: (path) => /\.m?(js|ts)x?$/.test(path),
18
+ extract: extractJsApi,
19
+ },
20
+ ];
21
+
22
+ async function extractJsApi(_path, content) {
23
+ const res = transpileDeclaration(content, {
24
+ compilerOptions: {
25
+ declaration: true,
26
+ emitDeclarationOnly: true,
27
+ allowJs: true,
28
+ },
29
+ });
30
+
31
+ return res.outputText.trim();
32
+ }