scripting-cli 1.0.2 → 1.0.4

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.
package/src/build.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import chalk from 'chalk'
2
2
  import Webpack from "webpack"
3
3
  import webpackConfig from './config/webpack.config'
4
+ import { zip } from 'cross-zip'
5
+ import path from 'node:path'
4
6
 
5
7
  export function buildApp() {
6
8
  const compiler = Webpack(webpackConfig)
@@ -25,7 +27,33 @@ export function buildApp() {
25
27
  chunks: false,
26
28
  colors: false,
27
29
  }))
30
+
31
+ createAppFile()
28
32
  }
29
33
  })
30
34
 
35
+ }
36
+
37
+ function createAppFile() {
38
+ const appFile = `${Object.keys(webpackConfig.entry as any)[0]}.zip`
39
+
40
+ console.log(
41
+ ` ~ Creating ${appFile}....`
42
+ )
43
+
44
+ zip(
45
+ path.resolve(process.cwd(), './build'),
46
+ path.resolve(process.cwd(), `./build/${appFile}`),
47
+ (error) => {
48
+ if (error != null) {
49
+ console.log(
50
+ chalk.red('Error zipping app files: \n') + error
51
+ )
52
+ } else {
53
+ console.log(
54
+ chalk.green(` ✔️ ${appFile} created.`)
55
+ )
56
+ }
57
+ }
58
+ )
31
59
  }
@@ -30,47 +30,88 @@ export default class AppJsonPlugin implements WebpackPluginInstance {
30
30
  stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
31
31
  },
32
32
  (assets) => {
33
- const appMap: {
34
- [appName: string]: {
35
- appName: string
36
- index: string
37
- hash: string
38
- }
39
- } = {}
40
-
41
- Object.keys(assets).forEach(path => {
42
- const [appName, ...others] = path.split('/')
33
+
34
+ const appJson: {
35
+ name: string
36
+ index: string
37
+ hash: string
38
+ assets: string[]
39
+ } = {
40
+ name: '',
41
+ index: '',
42
+ hash: '',
43
+ assets: Object.keys(assets),
44
+ }
45
+
46
+ const indexJs = appJson.assets.find(filePath => filePath.match(/\.js$/i) != null)
47
+
48
+ if (indexJs != null) {
49
+ const [appName, ...others] = indexJs.split('/')
43
50
  const filePath = others[others.length - 1]
51
+ appJson.name = appName
52
+ appJson.index = filePath
53
+ appJson.hash = filePath.replace('.js', '')
54
+
55
+ const indexJsSource = assets[indexJs]
56
+
57
+ appJson.assets = [
58
+ ...appJson.assets.filter(e => e !== indexJs),
59
+ filePath,
60
+ ]
61
+
62
+ compilation.deleteAsset(indexJs)
63
+ compilation.emitAsset(filePath, indexJsSource)
64
+
65
+ }
66
+
67
+ compilation.emitAsset(
68
+ 'app.json',
69
+ new RawSource(JSON.stringify(appJson, null, 2))
70
+ )
71
+
72
+ // const appMap: {
73
+ // [appName: string]: {
74
+ // appName: string
75
+ // index: string
76
+ // hash: string
77
+ // }
78
+ // } = {}
79
+
80
+
81
+ // Object.keys(assets).forEach(path => {
82
+ // const [appName, ...others] = path.split('/')
83
+ // const filePath = others[others.length - 1]
84
+
85
+ // // console.log(appName, filePath)
86
+
87
+ // // if (appMap[appName] == null) {
88
+ // // appMap[appName] = {
89
+ // // appName,
90
+ // // // assets: [],
91
+ // // }
92
+ // // }
93
+
94
+ // if (filePath.match(/\.js$/i)) {
95
+ // appMap[appName] = {
96
+ // appName,
97
+ // index: filePath,
98
+ // hash: filePath.replace('.js', '')
99
+ // }
100
+ // // appMap[appName].index = filePath
101
+ // // appMap[appName].hash = filePath.replace('.js', '')
102
+ // }
103
+ // // else if (filePath.match(/\.(png|jpe?g|gif|svg)$/i)) {
104
+ // // appMap[appName].assets.push(path.replace(appName + '/', ''))
105
+ // // }
106
+ // })
107
+
108
+ // Object.entries(appMap).forEach(([appName, content]) => {
109
+ // compilation.emitAsset(
110
+ // appName + '/app.json',
111
+ // new RawSource(JSON.stringify(content, null, 2))
112
+ // )
113
+ // })
44
114
 
45
- // console.log(appName, filePath)
46
-
47
- // if (appMap[appName] == null) {
48
- // appMap[appName] = {
49
- // appName,
50
- // // assets: [],
51
- // }
52
- // }
53
-
54
- if (filePath.match(/\.js$/i)) {
55
- appMap[appName] = {
56
- appName,
57
- index: filePath,
58
- hash: filePath.replace('.js', '')
59
- }
60
- // appMap[appName].index = filePath
61
- // appMap[appName].hash = filePath.replace('.js', '')
62
- }
63
- // else if (filePath.match(/\.(png|jpe?g|gif|svg)$/i)) {
64
- // appMap[appName].assets.push(path.replace(appName + '/', ''))
65
- // }
66
- })
67
-
68
- Object.entries(appMap).forEach(([appName, content]) => {
69
- compilation.emitAsset(
70
- appName + '/app.json',
71
- new RawSource(JSON.stringify(content, null, 2))
72
- )
73
- })
74
115
  // "assets" 是一个包含 compilation 中所有资源(assets)的对象。
75
116
  // 该对象的键是资源的路径,
76
117
  // 值是文件的源码
@@ -1,17 +1,40 @@
1
- import path from 'path'
1
+ import path from 'node:path'
2
+ import fs from 'node:fs'
3
+
4
+ import chalk from 'chalk'
2
5
 
3
6
  import TerserPlugin from 'terser-webpack-plugin'
4
7
  import webpack from 'webpack'
5
8
 
6
9
  import AppJsonPlugin from './AppJsonPlugin'
7
10
 
8
- const baseDir = path.resolve(__dirname, '..')
11
+ const baseDir = process.cwd()
9
12
  const srcDir = path.resolve(baseDir, 'src')
10
13
  const buildDir = path.resolve(baseDir, 'build')
11
14
 
15
+ const pkgPath = path.resolve(baseDir, 'package.json')
16
+
17
+ if (!fs.existsSync(pkgPath)) {
18
+ console.log(
19
+ chalk.red('✖️ package.json not found.')
20
+ )
21
+ process.exit(404)
22
+ }
23
+
24
+ const pkg = JSON.parse(
25
+ fs.readFileSync(
26
+ pkgPath,
27
+ 'utf8'
28
+ )
29
+ )
30
+
31
+ const entry = {
32
+ [pkg.name]: path.join(srcDir, 'index.tsx'),
33
+ }
34
+
12
35
  const config: webpack.Configuration = {
13
36
  mode: 'production',
14
- entry: path.join(srcDir, 'index.tsx'),
37
+ entry,
15
38
  optimization: {
16
39
  moduleIds: 'deterministic',
17
40
  chunkIds: 'named',
@@ -59,15 +82,17 @@ const config: webpack.Configuration = {
59
82
  },
60
83
  resolve: {
61
84
  extensions: ['.tsx', '.ts', '.js'],
62
- modules: ['node_modules', srcDir,],
85
+ modules: [
86
+ 'node_modules',
87
+ srcDir,
88
+ ],
63
89
  alias: {
64
90
  '@': srcDir,
65
91
  }
66
92
  },
67
93
  output: {
68
- // filename: 'index.js',
69
- // filename: '[name]/index.js',
70
94
  filename: '[name]/[contenthash:8].js',
95
+ // filename: '[contenthash:8].js',
71
96
  path: buildDir,
72
97
  clean: true,
73
98
  },
@@ -75,6 +100,9 @@ const config: webpack.Configuration = {
75
100
  new AppJsonPlugin(),
76
101
  ],
77
102
  devtool: false,
103
+ externals: {
104
+ 'scripting': 'Scripting',
105
+ }
78
106
  }
79
107
 
80
108
  export default config
package/src/createApp.ts CHANGED
@@ -1,20 +1,21 @@
1
1
  import chalk from 'chalk'
2
2
  import path from 'node:path'
3
- import { exec } from 'node:child_process'
3
+ import { execSync } from 'node:child_process'
4
4
  import fs from 'node:fs'
5
5
  import { mkdir, writeFile, copyFile } from 'node:fs/promises'
6
6
 
7
- console.log(__dirname)
8
-
9
7
  function getAppDir(appName: string) {
10
- return path.join(__dirname, appName)
8
+ return path.join(process.cwd(), appName)
11
9
  }
12
10
 
13
11
  async function createAppDir(appName: string) {
14
- const dir = path.join(getAppDir(appName), 'src')
15
- if (fs.existsSync(dir)) {
12
+ const appDir = getAppDir(appName)
13
+
14
+ if (fs.existsSync(appDir)) {
16
15
  throw new Error(`Directory "./${appName}" already exists.`)
17
16
  }
17
+
18
+ const dir = path.resolve(appDir, 'src/svgs')
18
19
  await mkdir(dir, { recursive: true })
19
20
  }
20
21
 
@@ -26,37 +27,66 @@ async function createEntryFile(appName: string) {
26
27
  await writeFile(
27
28
  filePath,
28
29
  `
29
- const { runApp, createElement, RouterProvider, Router, } = Scripting
30
- const { Center, Text, CupertinoPageScaffold, CupertinoNavigationBar, } = Scripting.Widgets
31
-
32
- function IndexPage() {
33
- return (
34
- <CupertinoPageScaffold
35
- navigationBar={
36
- <CupertinoNavigationBar
37
- middle={
38
- <Text>${appName}</Text>
39
- }
40
- />
41
- }
42
- >
43
- <Center>
44
- <Text>Welcome to Scripting!</Text>
45
- </Center>
46
- </CupertinoPageScaffold>
47
- )
48
- }
49
-
50
- const router = new Router([
51
- {
52
- path: '/',
53
- element: <IndexPage />,
54
- },
55
- ])
56
30
 
57
- runApp(
58
- <RouterProvider router={router} />
59
- )
31
+ import { runApp, createElement, RouterProvider, Router, Column, CupertinoNavigationBar, CupertinoPageScaffold, Svg, Text, Container, Color } from 'scripting'
32
+ import Logo from './svgs/logo.svg'
33
+
34
+ function ScriptingLogo() {
35
+ return (
36
+ <Container
37
+ clipBehavior={'hardEdge'}
38
+ width={80}
39
+ height={80}
40
+ margin={{
41
+ vertical: 100,
42
+ }}
43
+ borderRadius={16}
44
+ >
45
+ <Svg src={Logo} />
46
+ </Container>
47
+ )
48
+ }
49
+
50
+ function HomePage() {
51
+ const backgroundColor: Color = '#ffffff'
52
+ return (
53
+ <CupertinoPageScaffold
54
+ navigationBar={
55
+ <CupertinoNavigationBar
56
+ middle={
57
+ <Text>${appName}</Text>
58
+ }
59
+ backgroundColor={backgroundColor}
60
+ />
61
+ }
62
+ >
63
+ <Container
64
+ width={'infinity'}
65
+ height={'infinity'}
66
+ color={backgroundColor}
67
+ >
68
+ <Column
69
+ crossAxisAlignment={'center'}
70
+ >
71
+ <ScriptingLogo />
72
+ <Text>Welcome to Scripting!</Text>
73
+ </Column>
74
+ </Container>
75
+ </CupertinoPageScaffold>
76
+ )
77
+ }
78
+
79
+ const router = new Router([
80
+ {
81
+ path: '/',
82
+ element: <HomePage />,
83
+ },
84
+ ])
85
+
86
+ runApp(
87
+ <RouterProvider router={router} />
88
+ )
89
+
60
90
  `,
61
91
  'utf-8'
62
92
  )
@@ -100,17 +130,11 @@ async function createReadme(appName: string) {
100
130
  filePath,
101
131
  `# ${appName} - A Scripting application
102
132
 
103
- ## Quick Start
104
-
105
- ### Installation
106
-
107
- \`npm install\`
108
-
109
- ### Start dev server
133
+ ## Start dev server
110
134
 
111
135
  \`npm run dev\`
112
136
 
113
- ### Build App
137
+ ## Build App
114
138
 
115
139
  \`npm run build\`
116
140
  `,
@@ -168,16 +192,53 @@ async function createTSConfig(appName: string) {
168
192
  )
169
193
  }
170
194
 
171
- async function createScriptingDeclaration(appName: string) {
195
+ async function copyAssets(appName: string) {
172
196
  console.log(` > Creating ${appName}/src/scripting.d.ts ...`)
197
+ await copyFile(
198
+ path.join(__dirname, '../public/scripting.d.ts'),
199
+ path.join(getAppDir(appName), 'src/scripting.d.ts')
200
+ )
201
+ console.log(
202
+ chalk.green(` ✔️ Created ${appName}/src/scripting.d.ts`)
203
+ )
173
204
 
174
- const srcPath = path.join(__dirname, '../public/scripting.d.ts')
175
- const destPath = path.join(getAppDir(appName), 'src/scripting.d.ts')
205
+ console.log(` > Creating ${appName}/src/assets.d.ts ...`)
206
+ await copyFile(
207
+ path.join(__dirname, '../public/assets.d.ts'),
208
+ path.join(getAppDir(appName), 'src/assets.d.ts')
209
+ )
210
+ console.log(
211
+ chalk.green(` ✔️ Created ${appName}/src/assets.d.ts`)
212
+ )
213
+
214
+ console.log(` > Creating ${appName}/src/svgs/logo.svg ...`)
215
+ await copyFile(
216
+ path.join(__dirname, '../public/logo.svg'),
217
+ path.join(getAppDir(appName), 'src/svgs/logo.svg')
218
+ )
219
+ console.log(
220
+ chalk.green(` ✔️ Created ${appName}/src/svgs/logo.svg`)
221
+ )
222
+ }
176
223
 
177
- await copyFile(srcPath, destPath)
224
+ async function createVSCodeSettings(appName: string) {
225
+ const destDir = path.join(process.cwd(), '.vscode')
226
+
227
+ if (!fs.existsSync(destDir)) {
228
+ await mkdir(destDir)
229
+ }
230
+
231
+ await copyFile(
232
+ path.join(__dirname, '../.vscode/settings.json'),
233
+ path.join(getAppDir(appName), '.vscode/settings.json')
234
+ )
235
+ }
236
+
237
+ function installDeps(appName: string) {
238
+ execSync(`cd ${appName} && npm i -D ts-loader typescript file-loader`)
178
239
 
179
240
  console.log(
180
- chalk.green(` ✔️ Created ${appName}/src/scripting.d.ts`)
241
+ chalk.green(` ✔️ Scripting application ${chalk.bold(appName)} created!`)
181
242
  )
182
243
  }
183
244
 
@@ -195,9 +256,17 @@ export async function createApp(appName: string) {
195
256
  await createTSConfig(appName)
196
257
  await createReadme(appName)
197
258
  await createEntryFile(appName)
198
- await createScriptingDeclaration(appName)
259
+ await copyAssets(appName)
260
+ await createVSCodeSettings(appName)
261
+
262
+ installDeps(appName)
263
+
264
+ console.log(
265
+ ` ✔️ All done! Run ${chalk.bold(
266
+ chalk.green('npm run dev')
267
+ )} to start the dev server.`
268
+ )
199
269
 
200
- // exec('npm i')
201
270
  } catch (e: any) {
202
271
  console.log(
203
272
  chalk.red(`✖️ Create Scripting application failed: ${e.message}`)
@@ -1,8 +1,10 @@
1
1
  import http from 'node:http'
2
2
  import path from 'node:path'
3
+ import { readFile, } from 'node:fs/promises'
3
4
  import chalk from 'chalk'
4
5
  import express from 'express'
5
6
  import minimist from 'minimist'
7
+ import qrcode from 'qrcode-terminal'
6
8
 
7
9
  import { Server, Socket } from 'socket.io'
8
10
 
@@ -40,7 +42,7 @@ export function startDevServer() {
40
42
  utils.clearConsole()
41
43
  if (err) {
42
44
  console.log(
43
- chalk.red('[DevServer] webpack compile error: \n') + err
45
+ chalk.red(' ✖️ webpack compile error: \n') + err
44
46
  )
45
47
  } else {
46
48
  console.log(stats?.toString({
@@ -55,15 +57,25 @@ export function startDevServer() {
55
57
  }
56
58
  )
57
59
 
58
- function onCompileDone() {
60
+ async function onCompileDone() {
59
61
  if (isStarted) {
60
62
  printDevServerAddress()
63
+
61
64
  console.log(
62
- chalk.gray(`[DevServer] Sent update event to ${connectedSockets.length} client(s)`)
65
+ chalk.gray(` ~ Sent update event to ${connectedSockets.length} client(s)`)
63
66
  )
64
- connectedSockets.forEach(socket => {
65
- socket.emit('update')
66
- })
67
+
68
+ const appJson = await readFile(
69
+ path.resolve(
70
+ process.cwd(),
71
+ 'build/app.json'
72
+ ),
73
+ 'utf-8'
74
+ )
75
+
76
+ for (const socket of connectedSockets) {
77
+ socket.emit('update', appJson)
78
+ }
67
79
  } else {
68
80
  start()
69
81
  }
@@ -75,6 +87,8 @@ export function startDevServer() {
75
87
  `http://${ipAddress}:${port}`
76
88
  ),
77
89
  )}`)
90
+ console.log(`Use the Scripting app to scan the QR code below:`)
91
+ qrcode.generate(`http://${ipAddress}:${port}`, { small: true })
78
92
  }
79
93
 
80
94
  function start() {
@@ -85,7 +99,6 @@ export function startDevServer() {
85
99
  app.all('*', function (req, res, next) {
86
100
  res.header('Access-Control-Allow-Origin', '*')
87
101
  res.header('Access-Control-Allow-Headers', '*')
88
- // res.header('Content-Type', 'application/jsoncharset=utf-8')
89
102
  res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
90
103
  next()
91
104
  })
@@ -93,7 +106,7 @@ export function startDevServer() {
93
106
  app.use(
94
107
  '/',
95
108
  express.static(
96
- path.resolve(__dirname, '../build')
109
+ path.resolve(process.cwd(), 'build')
97
110
  )
98
111
  )
99
112
 
@@ -101,7 +114,7 @@ export function startDevServer() {
101
114
  io.on('connection', function (socket) {
102
115
  console.log(
103
116
  chalk.green(
104
- '[DevServer] A client connected.'
117
+ ` + A client(${socket.id}) connected.`
105
118
  )
106
119
  )
107
120
  connectedSockets.push(socket)
@@ -109,7 +122,7 @@ export function startDevServer() {
109
122
  socket.on('error', function (err) {
110
123
  console.log(
111
124
  chalk.red(
112
- '[DevServer] Error: ', err
125
+ ' ✖️ Server Error: ', err
113
126
  )
114
127
  )
115
128
  })
@@ -120,7 +133,7 @@ export function startDevServer() {
120
133
  connectedSockets.splice(index, 1)
121
134
  console.log(
122
135
  chalk.gray(
123
- '[DevServer] A client disconnected.'
136
+ ` - A client(${socket.id}) disconnected.`
124
137
  )
125
138
  )
126
139
  }