1
+ import { ObjectId } from 'bson'
2
+ import fse = require( 'fs-extra' )
3
+ import path = require( 'path' )
4
+ import { Constants } from '../constants'
5
+ import { DatabaseAgent } from '../lib/database'
6
+ import { execSync } from 'child_process'
7
+
8
+ /**
9
+ * 在 node_modules 中创建 云函数 sdk 包:@, 这个包是为了云函数IDE 加载类型提示文件而创建的,不可发布
10
+ */
11
+ export function createCloudFunctionDeclarationPackage ( ) {
12
+ const source = path . resolve ( __dirname , '../../dist' )
13
+ const target = path . resolve ( __dirname , '../../node_modules/@' )
14
+
15
+ fse . ensureDirSync ( target )
16
+ fse . copySync ( source , target )
17
+
18
+ console . log ( `copy success: ${ source } => ${ target } ` )
19
+
20
+ const packageJson = `
21
+ {
22
+ "name": "@",
23
+ "version": "0.0.0"
24
+ }
25
+ `
26
+ const pkgJsonPath = path . join ( target , 'package.json' )
27
+ fse . writeFileSync ( pkgJsonPath , packageJson )
28
+
29
+ console . log ( `write success: ${ pkgJsonPath } ` )
30
+ }
31
+
32
+ export function isCloudSdkPackageExists ( ) {
33
+ const target = path . resolve ( __dirname , '../../../node_modules/@' )
34
+ const pkgJsonPath = path . join ( target , 'package.json' )
35
+ return fse . existsSync ( pkgJsonPath )
36
+ }
37
+
38
+ export function initCloudSdkPackage ( ) {
39
+ if ( ! isCloudSdkPackageExists ( ) ) {
40
+ createCloudFunctionDeclarationPackage ( )
41
+ }
42
+ }
43
+
44
+
45
+ interface AppConfigItem {
46
+ _id : ObjectId
47
+ key : string
48
+ value : {
49
+ name : string ,
50
+ version : string
51
+ } [ ]
52
+ }
53
+
54
+ /**
55
+ * Get extra npm packages
56
+ * @returns
57
+ */
58
+ export async function getExtraPackages ( ) {
59
+ await DatabaseAgent . accessor . ready
60
+ const db = DatabaseAgent . db
61
+ const doc = await db . collection < AppConfigItem > ( Constants . config_collection )
62
+ . findOne ( { key : 'packages' } )
63
+
64
+ return doc ?. value ?? [ ]
65
+ }
66
+
67
+ /**
68
+ * Install packages
69
+ * @param packages
70
+ * @returns
71
+ */
72
+ export function installPackages ( packages : { name : string , version : string } [ ] ) {
73
+ if ( ! packages ?. length ) {
74
+ return
75
+ }
76
+
77
+ const names = packages
78
+ . map ( pkg => {
79
+ return pkg . version ? `${ pkg . name } @${ pkg . version } ` : `${ pkg . name } `
80
+ } )
81
+
82
+ const cmd_str = names . join ( ' ' )
83
+ const r = execSync ( `npm install ${ cmd_str } ` )
84
+ return r . toString ( )
85
+ }
86
+
87
+ /**
88
+ * Check if node module exists
89
+ * @param moduleName
90
+ * @returns
91
+ */
92
+ export function moduleExists ( mod : string ) {
93
+ try {
94
+ require . resolve ( mod )
95
+ return true
96
+ } catch ( _err ) {
97
+ return false
98
+ }
99
+ }
0 commit comments