scripting-cli 1.0.3 → 1.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.
package/src/build.ts CHANGED
@@ -1,8 +1,26 @@
1
1
  import chalk from 'chalk'
2
2
  import Webpack from "webpack"
3
- import webpackConfig from './config/webpack.config'
3
+ import { zip } from 'cross-zip'
4
+ import qrcode from 'qrcode-terminal'
5
+
6
+ import path from 'node:path'
7
+ import http from 'node:http'
8
+ import express from 'express'
9
+
10
+ import getConfig from './config/webpack.config'
11
+ import * as utils from './utils'
12
+ import minimist from 'minimist'
4
13
 
5
14
  export function buildApp() {
15
+ const webpackConfig = getConfig()
16
+
17
+ const appName = Object.keys(webpackConfig.entry as any)[0]
18
+ const appFile = `${appName}.zip`
19
+
20
+ const outputDir = path.resolve(process.cwd(), appName)
21
+
22
+ webpackConfig.output!.path = outputDir
23
+
6
24
  const compiler = Webpack(webpackConfig)
7
25
 
8
26
  console.log(
@@ -25,7 +43,68 @@ export function buildApp() {
25
43
  chunks: false,
26
44
  colors: false,
27
45
  }))
46
+
47
+ createAppFile()
28
48
  }
29
49
  })
30
50
 
51
+
52
+
53
+ function createAppFile() {
54
+ console.log(
55
+ ` ~ Creating ${appFile}....`
56
+ )
57
+
58
+ zip(
59
+ outputDir,
60
+ path.resolve(outputDir, appFile),
61
+ (error) => {
62
+ if (error != null) {
63
+ console.log(
64
+ chalk.red('Error zipping app files: \n') + error
65
+ )
66
+ } else {
67
+ console.log(
68
+ chalk.green(` ✔️ ${appFile} created.`)
69
+ )
70
+
71
+ startServer()
72
+ }
73
+ }
74
+ )
75
+ }
76
+
77
+ function startServer() {
78
+ const app = express()
79
+ const server = http.createServer(app)
80
+
81
+ const args = minimist(process.argv.slice(2))
82
+ const ipAddress = utils.getIpAddress()
83
+ const port = args['port'] || 8000
84
+
85
+ app.all('*', function (req, res, next) {
86
+ res.header('Access-Control-Allow-Origin', '*')
87
+ res.header('Access-Control-Allow-Headers', '*')
88
+ res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
89
+ next()
90
+ })
91
+
92
+ app.use(
93
+ '/',
94
+ express.static(
95
+ outputDir
96
+ )
97
+ )
98
+
99
+ server.listen(port)
100
+
101
+ console.log(`Server running at ${chalk.bold(
102
+ chalk.green(
103
+ `http://${ipAddress}:${port}`
104
+ ),
105
+ )}`)
106
+ console.log(`Use the Scripting app to scan the QR code below to install:`)
107
+ qrcode.generate(`http://${ipAddress}:${port}`, { small: true })
108
+ }
109
+
31
110
  }
@@ -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,83 +1,111 @@
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 = process.cwd()
9
- const srcDir = path.resolve(baseDir, 'src')
10
- const buildDir = path.resolve(baseDir, 'build')
11
+ export default function getConfig() {
12
+
13
+ const baseDir = process.cwd()
14
+ const srcDir = path.resolve(baseDir, 'src')
15
+ const outputDir = path.resolve(baseDir, 'build')
16
+
17
+ const pkgPath = path.resolve(baseDir, 'package.json')
18
+
19
+ if (!fs.existsSync(pkgPath)) {
20
+ console.log(
21
+ chalk.red('✖️ package.json not found.')
22
+ )
23
+ process.exit(404)
24
+ }
25
+
26
+ const pkg = JSON.parse(
27
+ fs.readFileSync(
28
+ pkgPath,
29
+ 'utf8'
30
+ )
31
+ )
11
32
 
12
- const config: webpack.Configuration = {
13
- mode: 'production',
14
- entry: path.join(srcDir, 'index.tsx'),
15
- optimization: {
16
- moduleIds: 'deterministic',
17
- chunkIds: 'named',
18
- minimizer: [
19
- new TerserPlugin({
20
- extractComments: false,
21
- terserOptions: {
22
- format: {
23
- comments: false,
33
+ const entry = {
34
+ [pkg.name]: path.join(srcDir, 'index.tsx'),
35
+ }
36
+
37
+ const config: webpack.Configuration = {
38
+ mode: 'production',
39
+ entry,
40
+ optimization: {
41
+ moduleIds: 'deterministic',
42
+ chunkIds: 'named',
43
+ minimizer: [
44
+ new TerserPlugin({
45
+ extractComments: false,
46
+ terserOptions: {
47
+ format: {
48
+ comments: false,
49
+ },
24
50
  },
51
+ }),
52
+ ],
53
+ },
54
+ module: {
55
+ rules: [
56
+ {
57
+ test: /\.tsx?$/,
58
+ use: 'ts-loader',
59
+ exclude: /node_modules/,
25
60
  },
26
- }),
27
- ],
28
- },
29
- module: {
30
- rules: [
31
- {
32
- test: /\.tsx?$/,
33
- use: 'ts-loader',
34
- exclude: /node_modules/,
35
- },
36
- {
37
- test: /\.(png|jpe?g|gif|svg)$/i,
38
- loader: 'file-loader',
39
- options: {
40
- name: '[path][contenthash:8].[ext]',
41
- outputPath: (url: string, resourcePath: string, context: any) => {
42
- // if (url.startsWith('src/app/')) {
43
- // return url.replace('src/app/', '')
44
- // }
45
- return url.replace('src/', '')
46
- // return url.replace(/src\/([^/]+)\//, '')
47
- },
48
- publicPath: (url: string, resourcePath: string, context: any) => {
49
- // console.log([url, resourcePath])
50
- // return url.replace(/.*src\/app\/(\w+\/)?/, '')
51
- // if (url.startsWith('src/app/')) {
52
- // return url.replace('src/app/', '')
53
- // }
54
- return url.replace('src/', '')
61
+ {
62
+ test: /\.(png|jpe?g|gif|svg)$/i,
63
+ loader: 'file-loader',
64
+ options: {
65
+ name: '[path][contenthash:8].[ext]',
66
+ outputPath: (url: string, resourcePath: string, context: any) => {
67
+ // if (url.startsWith('src/app/')) {
68
+ // return url.replace('src/app/', '')
69
+ // }
70
+ return url.replace('src/', '')
71
+ // return url.replace(/src\/([^/]+)\//, '')
72
+ },
73
+ publicPath: (url: string, resourcePath: string, context: any) => {
74
+ // console.log([url, resourcePath])
75
+ // return url.replace(/.*src\/app\/(\w+\/)?/, '')
76
+ // if (url.startsWith('src/app/')) {
77
+ // return url.replace('src/app/', '')
78
+ // }
79
+ return url.replace('src/', '')
80
+ },
55
81
  },
56
82
  },
57
- },
58
- ],
59
- },
60
- resolve: {
61
- extensions: ['.tsx', '.ts', '.js'],
62
- modules: [
63
- 'node_modules',
64
- srcDir,
83
+ ],
84
+ },
85
+ resolve: {
86
+ extensions: ['.tsx', '.ts', '.js'],
87
+ modules: [
88
+ 'node_modules',
89
+ srcDir,
90
+ ],
91
+ alias: {
92
+ '@': srcDir,
93
+ }
94
+ },
95
+ output: {
96
+ filename: '[name]/[contenthash:8].js',
97
+ // filename: '[contenthash:8].js',
98
+ path: outputDir,
99
+ clean: true,
100
+ },
101
+ plugins: [
102
+ new AppJsonPlugin(),
65
103
  ],
66
- alias: {
67
- '@': srcDir,
104
+ devtool: false,
105
+ externals: {
106
+ 'scripting': 'Scripting',
68
107
  }
69
- },
70
- output: {
71
- // filename: 'index.js',
72
- // filename: '[name]/index.js',
73
- filename: '[name]/[contenthash:8].js',
74
- path: buildDir,
75
- clean: true,
76
- },
77
- plugins: [
78
- new AppJsonPlugin(),
79
- ],
80
- devtool: false,
81
- }
108
+ }
82
109
 
83
- export default config
110
+ return config
111
+ }
package/src/createApp.ts CHANGED
@@ -4,17 +4,18 @@ 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(process.cwd())
8
-
9
7
  function getAppDir(appName: string) {
10
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
 
@@ -25,11 +26,29 @@ async function createEntryFile(appName: string) {
25
26
 
26
27
  await writeFile(
27
28
  filePath,
28
- `
29
- const { runApp, createElement, RouterProvider, Router, } = Scripting
30
- const { Center, Text, CupertinoPageScaffold, CupertinoNavigationBar, } = Scripting.Widgets
29
+ `import { runApp, createElement, RouterProvider, Router, Column, CupertinoNavigationBar, CupertinoPageScaffold, Svg, Text, Container, useCupertinoColors } from 'scripting'
30
+ import Logo from './svgs/logo.svg'
31
+
32
+ function ScriptingLogo() {
33
+ return (
34
+ <Container
35
+ clipBehavior={'hardEdge'}
36
+ width={80}
37
+ height={80}
38
+ margin={{
39
+ vertical: 100,
40
+ }}
41
+ borderRadius={16}
42
+ >
43
+ <Svg src={Logo} />
44
+ </Container>
45
+ )
46
+ }
47
+
48
+ function HomePage() {
49
+ const cupertinoColors = useCupertinoColors()
50
+ const backgroundColor = cupertinoColors.systemBackground
31
51
 
32
- function IndexPage() {
33
52
  return (
34
53
  <CupertinoPageScaffold
35
54
  navigationBar={
@@ -37,12 +56,24 @@ function IndexPage() {
37
56
  middle={
38
57
  <Text>${appName}</Text>
39
58
  }
59
+ backgroundColor={backgroundColor}
40
60
  />
41
61
  }
42
62
  >
43
- <Center>
44
- <Text>Welcome to Scripting!</Text>
45
- </Center>
63
+ <Container
64
+ width={'infinity'}
65
+ height={'infinity'}
66
+ color={backgroundColor}
67
+ >
68
+ <Column
69
+ crossAxisAlignment={'center'}
70
+ >
71
+ <ScriptingLogo />
72
+ <Text
73
+ color={cupertinoColors.label}
74
+ >Welcome to Scripting!</Text>
75
+ </Column>
76
+ </Container>
46
77
  </CupertinoPageScaffold>
47
78
  )
48
79
  }
@@ -50,14 +81,13 @@ function IndexPage() {
50
81
  const router = new Router([
51
82
  {
52
83
  path: '/',
53
- element: <IndexPage />,
84
+ element: <HomePage />,
54
85
  },
55
86
  ])
56
87
 
57
88
  runApp(
58
89
  <RouterProvider router={router} />
59
- )
60
- `,
90
+ )`,
61
91
  'utf-8'
62
92
  )
63
93
 
@@ -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,24 +192,56 @@ 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')
176
-
177
- await copyFile(srcPath, destPath)
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
+ )
178
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
+ )
179
219
  console.log(
180
- chalk.green(` ✔️ Created ${appName}/src/scripting.d.ts`)
220
+ chalk.green(` ✔️ Created ${appName}/src/svgs/logo.svg`)
221
+ )
222
+ }
223
+
224
+ async function createVSCodeSettings(appName: string) {
225
+ const destDir = path.join(getAppDir(appName), '.vscode')
226
+
227
+ if (!fs.existsSync(destDir)) {
228
+ await mkdir(destDir, { recursive: true })
229
+ }
230
+
231
+ await copyFile(
232
+ path.join(__dirname, '../.vscode/settings.json'),
233
+ path.join(destDir, 'settings.json')
181
234
  )
182
235
  }
183
236
 
184
237
  function installDeps(appName: string) {
238
+ console.log(
239
+ ` > cd ${appName} && npm i -D ts-loader typescript file-loader`
240
+ )
185
241
  execSync(`cd ${appName} && npm i -D ts-loader typescript file-loader`)
186
242
 
187
243
  console.log(
188
- chalk.green(` ✔️ Scripting application ${chalk.bold(appName)} created!`)
244
+ chalk.green(` ✔️ Scripting application ${chalk.bold(appName)} is ready!`)
189
245
  )
190
246
  }
191
247
 
@@ -197,16 +253,27 @@ export async function createApp(appName: string) {
197
253
  return
198
254
  }
199
255
 
256
+ console.log(
257
+ `Start creating ${appName} ...`
258
+ )
259
+
200
260
  try {
201
261
  await createAppDir(appName)
202
262
  await createPackageJson(appName)
203
263
  await createTSConfig(appName)
204
264
  await createReadme(appName)
205
265
  await createEntryFile(appName)
206
- await createScriptingDeclaration(appName)
266
+ await copyAssets(appName)
267
+ await createVSCodeSettings(appName)
207
268
 
208
269
  installDeps(appName)
209
270
 
271
+ console.log(
272
+ `All done! Run ${chalk.bold(
273
+ chalk.green(`cd ${appName} && npm run dev`)
274
+ )} to start the dev server.`
275
+ )
276
+
210
277
  } catch (e: any) {
211
278
  console.log(
212
279
  chalk.red(`✖️ Create Scripting application failed: ${e.message}`)
package/src/index.ts CHANGED
@@ -8,7 +8,6 @@ import { createApp } from './createApp'
8
8
  function run() {
9
9
  const args = minimist(process.argv.slice(2))
10
10
 
11
- // console.log(args)
12
11
  if (args['create'] != null) {
13
12
  createApp(args['create'])
14
13
  } else if (args._.includes('dev')) {