doc-render-sdk 0.0.3 → 0.0.5

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.
@@ -0,0 +1,393 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Doc SDK CLI 工具
5
+ */
6
+ const { program } = require('commander');
7
+ const path = require('path');
8
+ const fs = require('fs');
9
+ const { spawn } = require('child_process');
10
+ const sdkVersion = require('../package.json').version;
11
+ program
12
+ .name('doc-render-sdk')
13
+ .description('Doc SDK CLI - 文档站点构建工具')
14
+ .version('1.0.0');
15
+
16
+ // 创建新项目
17
+ program
18
+ .command('create <project-name>')
19
+ .description('创建新的文档项目')
20
+ .option('-t, --template <template>', '使用模板', 'default')
21
+ .action(async (projectName, options) => {
22
+ console.log(`🚀 创建文档项目: ${projectName}`);
23
+
24
+ const projectDir = path.resolve(projectName);
25
+
26
+ if (fs.existsSync(projectDir)) {
27
+ console.error(`❌ 目录已存在: ${projectDir}`);
28
+ process.exit(1);
29
+ }
30
+
31
+ try {
32
+ await createProject(projectDir, options.template);
33
+ console.log('✅ 项目创建成功!');
34
+ console.log(`📁 项目目录: ${projectDir}`);
35
+ console.log('\n下一步:');
36
+ console.log(` cd ${projectName}`);
37
+ console.log(' npm install');
38
+ console.log(' npm run dev');
39
+ } catch (error) {
40
+ console.error('❌ 创建失败:', error.message);
41
+ process.exit(1);
42
+ }
43
+ });
44
+
45
+ // 开发服务器
46
+ program
47
+ .command('dev')
48
+ .description('启动开发服务器')
49
+ .option('-p, --port <port>', '端口号', '8080')
50
+ .option('-h, --host <host>', '主机地址', 'localhost')
51
+ .action(async (options) => {
52
+ console.log('🚀 启动开发服务器...');
53
+
54
+ const configPath = findConfig();
55
+ if (!configPath) {
56
+ console.error('❌ 未找到配置文件');
57
+ process.exit(1);
58
+ }
59
+
60
+ await startDevServer(configPath, options);
61
+ });
62
+
63
+ // 构建项目
64
+ program
65
+ .command('build')
66
+ .description('构建文档站点')
67
+ .option('-o, --output <dir>', '输出目录', 'dist')
68
+ .action(async (options) => {
69
+ console.log('📦 构建文档站点...');
70
+
71
+ const configPath = findConfig();
72
+ if (!configPath) {
73
+ console.error('❌ 未找到配置文件');
74
+ process.exit(1);
75
+ }
76
+
77
+ await buildProject(configPath, options);
78
+ });
79
+
80
+
81
+ // 预览构建结果
82
+ program
83
+ .command('preview')
84
+ .description('预览构建结果')
85
+ .option('-p, --port <port>', '端口号', '3000')
86
+ .option('-d, --dir <dir>', '构建目录', 'dist')
87
+ .action((options) => {
88
+ console.log('👀 预览构建结果...');
89
+ previewBuild(options);
90
+ });
91
+
92
+ program.parse();
93
+
94
+ /**
95
+ * 创建新项目
96
+ */
97
+ async function createProject(projectDir, template) {
98
+ // 创建项目目录
99
+ fs.mkdirSync(projectDir, { recursive: true });
100
+
101
+ // 生成package.json
102
+ const packageJson = {
103
+ name: path.basename(projectDir),
104
+ version: '1.0.0',
105
+ description: 'Documentation site built with Doc SDK',
106
+ main: 'index.js',
107
+ scripts: {
108
+ dev: 'doc-render-sdk dev',
109
+ build: 'doc-render-sdk build',
110
+ preview: 'doc-render-sdk preview'
111
+ },
112
+ dependencies: {
113
+ 'doc-render-sdk': sdkVersion
114
+ },
115
+ devDependencies: {
116
+ vite: '^5.0.0',
117
+ '@vitejs/plugin-react': '^3.1.0'
118
+ }
119
+ };
120
+
121
+ fs.writeFileSync(
122
+ path.join(projectDir, 'package.json'),
123
+ JSON.stringify(packageJson, null, 2)
124
+ );
125
+
126
+ // 生成配置文件
127
+ const config = {
128
+ title: 'My Documentation',
129
+ description: 'Component documentation built with Doc SDK',
130
+ version: '1.0.0',
131
+ components: {
132
+ 'example': {
133
+ label: 'Example Component',
134
+ description: 'An example component to get you started',
135
+ demos: [
136
+ {
137
+ title: 'Basic Usage',
138
+ desc: 'Basic usage of the component',
139
+ source: 'basic'
140
+ }
141
+ ],
142
+ apis: [
143
+ {
144
+ title: 'Example',
145
+ apiKey: 'Example'
146
+ }
147
+ ]
148
+ }
149
+ }
150
+ };
151
+
152
+ fs.writeFileSync(
153
+ path.join(projectDir, 'doc.config.js'),
154
+ `export default ${JSON.stringify(config, null, 2)};`
155
+ );
156
+
157
+ // 生成入口文件
158
+ const indexJs = `import DocSDK from 'doc-render-sdk';
159
+ import config from './doc.config.js';
160
+
161
+ // 注册示例组件
162
+ const ExampleComponent = () => {
163
+ return (
164
+ <div style={{ padding: '20px' }}>
165
+ <h3>Example Component</h3>
166
+ <p>This is an example component.</p>
167
+ </div>
168
+ );
169
+ };
170
+
171
+ // 注册全局组件
172
+ window.__DOC_SDK_DEMOS__ = {
173
+ 'example': {
174
+ 'basic': ExampleComponent
175
+ }
176
+ };
177
+
178
+ window.__DOC_SDK_DEMO_CODES__ = {
179
+ 'example': {
180
+ 'basic': \`const ExampleComponent = () => {
181
+ return (
182
+ <div style={{ padding: '20px' }}>
183
+ <h3>Example Component</h3>
184
+ <p>This is an example component.</p>
185
+ </div>
186
+ );
187
+ };\`
188
+ }
189
+ };
190
+
191
+ window.__DOC_SDK_APIS__ = {
192
+ 'example': {
193
+ 'Example': [
194
+ {
195
+ param: 'children',
196
+ type: 'ReactNode',
197
+ desc: 'The content of the component',
198
+ option: '',
199
+ default: '',
200
+ required: false
201
+ }
202
+ ]
203
+ }
204
+ };
205
+
206
+ const docSdk = new DocSDK(config);
207
+ docSdk.render('#app');
208
+ `;
209
+
210
+ fs.writeFileSync(path.join(projectDir, 'index.js'), indexJs);
211
+
212
+ // 生成HTML文件
213
+ const indexHtml = `<!DOCTYPE html>
214
+ <html lang="zh-CN">
215
+ <head>
216
+ <meta charset="UTF-8">
217
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
218
+ <title>My Documentation</title>
219
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github.min.css">
220
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
221
+ </head>
222
+ <body>
223
+ <div id="app"></div>
224
+ <script src="index.js"></script>
225
+ </body>
226
+ </html>`;
227
+
228
+ fs.writeFileSync(path.join(projectDir, 'index.html'), indexHtml);
229
+
230
+ // 生成README
231
+ const readme = `# ${path.basename(projectDir)}
232
+
233
+ Documentation site built with Doc SDK.
234
+
235
+ ## Getting Started
236
+
237
+ \`\`\`bash
238
+ npm install
239
+ npm run dev
240
+ \`\`\`
241
+
242
+ ## Commands
243
+
244
+ - \`npm run dev\` - Start development server
245
+ - \`npm run build\` - Build for production
246
+ - \`npm run preview\` - Preview build
247
+
248
+ ## Documentation
249
+
250
+ - [Doc SDK Documentation](https://github.com/Sunny-117/doc-render-sdk)
251
+ `;
252
+
253
+ fs.writeFileSync(path.join(projectDir, 'README.md'), readme);
254
+ }
255
+
256
+ /**
257
+ * 查找配置文件
258
+ */
259
+ function findConfig() {
260
+ const configFiles = [
261
+ 'doc.config.js',
262
+ 'doc.config.json',
263
+ 'docs.config.js',
264
+ 'docs.config.json'
265
+ ];
266
+
267
+ for (const file of configFiles) {
268
+ if (fs.existsSync(file)) {
269
+ return path.resolve(file);
270
+ }
271
+ }
272
+
273
+ return null;
274
+ }
275
+
276
+ /**
277
+ * 启动开发服务器
278
+ */
279
+ function startDevServer(configPath, options) {
280
+ // Use Vite Node API to create a dev server via createViteServer
281
+ (async () => {
282
+ try {
283
+ const server = await createViteServer({
284
+ root: process.cwd(),
285
+ server: {
286
+ port: Number(options.port) || 8080,
287
+ host: options.host || 'localhost'
288
+ }
289
+ });
290
+
291
+ await server.listen();
292
+ server.printUrls();
293
+ } catch (err) {
294
+ console.error('❌ 启动 Vite 开发服务器失败:', err);
295
+ process.exit(1);
296
+ }
297
+ })();
298
+ }
299
+
300
+ /**
301
+ * 构建项目
302
+ */
303
+ function buildProject(configPath, options) {
304
+ // Use Vite build API with plugin-react
305
+ (async () => {
306
+ try {
307
+ const { build } = require('vite');
308
+ const outDir = options.output || 'dist';
309
+
310
+ console.log('📦 running vite build...');
311
+
312
+ await build({
313
+ root: process.cwd(),
314
+ build: {
315
+ outDir
316
+ },
317
+ plugins: createVitePlugins()
318
+ });
319
+
320
+ console.log('✅ 构建完成!');
321
+ } catch (err) {
322
+ console.error('❌ Vite 构建失败:', err);
323
+ process.exit(1);
324
+ }
325
+ })();
326
+ }
327
+
328
+ /**
329
+ * Create Vite server with shared plugins
330
+ */
331
+ function createViteServer(options = {}) {
332
+ const { createServer } = require('vite');
333
+ const plugins = createVitePlugins();
334
+ return createServer({ ...options, plugins });
335
+ }
336
+
337
+ function createVitePlugins() {
338
+ try {
339
+ const reactPlugin = require('@vitejs/plugin-react');
340
+ return [reactPlugin()];
341
+ } catch (err) {
342
+ // If plugin not installed, return empty array and let Vite warn later
343
+ return [];
344
+ }
345
+ }
346
+
347
+ /**
348
+ * 预览构建结果
349
+ */
350
+ function previewBuild(options) {
351
+ // Use Vite programmatic preview API if available, else fallback to npx vite preview
352
+ const distDir = options.dir || 'dist';
353
+ const port = Number(options.port) || 3000;
354
+
355
+ try {
356
+ const vite = require('vite');
357
+ if (typeof vite.preview === 'function') {
358
+ // Vite exposes preview function in some versions
359
+ (async () => {
360
+ try {
361
+ const server = await vite.preview({ root: process.cwd(), preview: { port } });
362
+ console.log(`📖 预览地址: http://localhost:${port}`);
363
+ } catch (err) {
364
+ console.error('❌ 启动 Vite preview 失败:', err);
365
+ process.exit(1);
366
+ }
367
+ })();
368
+ return;
369
+ }
370
+
371
+ // Fallback: try to create a server configured for preview
372
+ if (typeof vite.createServer === 'function') {
373
+ (async () => {
374
+ try {
375
+ const server = await vite.createServer({ root: process.cwd(), preview: { port } });
376
+ await server.listen();
377
+ console.log(`📖 预览地址: http://localhost:${port}`);
378
+ } catch (err) {
379
+ // continue to fallback
380
+ console.error('❌ 使用 createServer 作为 preview 启动失败,回退到 CLI:', err.message || err);
381
+ }
382
+ })();
383
+ return;
384
+ }
385
+ } catch (err) {
386
+ // vite not installed locally, will fallback to npx
387
+ }
388
+
389
+ // Final fallback: spawn npx vite preview
390
+ const args = ['vite', 'preview', '--port', String(port)];
391
+ const child = spawn('npx', args, { stdio: 'inherit', shell: true, cwd: process.cwd() });
392
+ child.on('close', (code) => process.exit(code));
393
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doc-render-sdk",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "A powerful documentation rendering SDK for component libraries",
5
5
  "main": "dist/index.mjs",
6
6
  "module": "dist/index.mjs",