scripting-cli 1.0.0

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 ADDED
@@ -0,0 +1,31 @@
1
+ import chalk from 'chalk'
2
+ import Webpack from "webpack"
3
+ import webpackConfig from './config/webpack.config'
4
+
5
+ export function buildApp() {
6
+ const compiler = Webpack(webpackConfig)
7
+
8
+ console.log(
9
+ 'Start running build...\n'
10
+ // +
11
+ // chalk.green(
12
+ // Object.keys(webpackConfig.entry).map(e => ` - ${e}`).join('\n')
13
+ // )
14
+ // +
15
+ // '\n'
16
+ )
17
+
18
+ compiler.run((err, stats) => {
19
+ if (err) {
20
+ console.log(
21
+ chalk.red('Webpack compile error: \n') + err
22
+ )
23
+ } else {
24
+ console.log(stats?.toString({
25
+ chunks: false,
26
+ colors: false,
27
+ }))
28
+ }
29
+ })
30
+
31
+ }
@@ -0,0 +1,96 @@
1
+ import { Compiler, WebpackPluginInstance } from "webpack"
2
+
3
+ export default class AppJsonPlugin implements WebpackPluginInstance {
4
+
5
+ apply(compiler: Compiler) {
6
+ const pluginName = 'AppJsonPlugin'
7
+
8
+ // webpack 模块实例,可以通过 compiler 对象访问,
9
+ // 这样确保使用的是模块的正确版本
10
+ // (不要直接 require/import webpack)
11
+ const { webpack } = compiler
12
+
13
+ // Compilation 对象提供了对一些有用常量的访问。
14
+ const { Compilation } = webpack
15
+
16
+ // RawSource 是其中一种 “源码”("sources") 类型,
17
+ // 用来在 compilation 中表示资源的源码
18
+ const { RawSource } = webpack.sources
19
+
20
+ // 绑定到 “thisCompilation” 钩子,
21
+ // 以便进一步绑定到 compilation 过程更早期的阶段
22
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
23
+ // 绑定到资源处理流水线(assets processing pipeline)
24
+ compilation.hooks.processAssets.tap(
25
+ {
26
+ name: pluginName,
27
+
28
+ // 用某个靠后的资源处理阶段,
29
+ // 确保所有资源已被插件添加到 compilation
30
+ stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
31
+ },
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('/')
43
+ const filePath = others[others.length - 1]
44
+
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
+ // "assets" 是一个包含 compilation 中所有资源(assets)的对象。
75
+ // 该对象的键是资源的路径,
76
+ // 值是文件的源码
77
+
78
+ // 遍历所有资源,
79
+ // 生成 Markdown 文件的内容
80
+ // const content =
81
+ // '# In this build:\n\n' +
82
+ // Object.keys(assets)
83
+ // .map((filename) => `- ${filename}`)
84
+ // .join('\n');
85
+
86
+ // // 向 compilation 添加新的资源,
87
+ // // 这样 webpack 就会自动生成并输出到 output 目录
88
+ // compilation.emitAsset(
89
+ // this.options.outputFile,
90
+ // new RawSource(content)
91
+ // );
92
+ }
93
+ )
94
+ })
95
+ }
96
+ }
@@ -0,0 +1,80 @@
1
+ import path from 'path'
2
+
3
+ import TerserPlugin from 'terser-webpack-plugin'
4
+ import webpack from 'webpack'
5
+
6
+ import AppJsonPlugin from './AppJsonPlugin'
7
+
8
+ const baseDir = path.resolve(__dirname, '..')
9
+ const srcDir = path.resolve(baseDir, 'src')
10
+ const buildDir = path.resolve(baseDir, 'build')
11
+
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,
24
+ },
25
+ },
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/', '')
55
+ },
56
+ },
57
+ },
58
+ ],
59
+ },
60
+ resolve: {
61
+ extensions: ['.tsx', '.ts', '.js'],
62
+ modules: ['node_modules', srcDir,],
63
+ alias: {
64
+ '@': srcDir,
65
+ }
66
+ },
67
+ output: {
68
+ // filename: 'index.js',
69
+ // filename: '[name]/index.js',
70
+ filename: '[name]/[contenthash:8].js',
71
+ path: buildDir,
72
+ clean: true,
73
+ },
74
+ plugins: [
75
+ new AppJsonPlugin(),
76
+ ],
77
+ devtool: false,
78
+ }
79
+
80
+ export default config
@@ -0,0 +1,206 @@
1
+ import chalk from 'chalk'
2
+ import path from 'node:path'
3
+ import { exec } from 'node:child_process'
4
+ import fs from 'node:fs'
5
+ import { mkdir, writeFile, copyFile } from 'node:fs/promises'
6
+
7
+ console.log(__dirname)
8
+
9
+ function getAppDir(appName: string) {
10
+ return path.join(__dirname, appName)
11
+ }
12
+
13
+ async function createAppDir(appName: string) {
14
+ const dir = path.join(getAppDir(appName), 'src')
15
+ if (fs.existsSync(dir)) {
16
+ throw new Error(`Directory "./${appName}" already exists.`)
17
+ }
18
+ await mkdir(dir, { recursive: true })
19
+ }
20
+
21
+ async function createEntryFile(appName: string) {
22
+ console.log(` > Creating ${appName}/src/index.tsx ...`)
23
+
24
+ const filePath = path.join(getAppDir(appName), '/src/index.tsx')
25
+
26
+ await writeFile(
27
+ filePath,
28
+ `
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
+
57
+ runApp(
58
+ <RouterProvider router={router} />
59
+ )
60
+ `,
61
+ 'utf-8'
62
+ )
63
+
64
+ console.log(
65
+ chalk.green(` ✔️ Created ${appName}/src/index.tsx`)
66
+ )
67
+ }
68
+
69
+ async function createPackageJson(appName: string) {
70
+ console.log(` > Creating ${appName}/package.json ...`)
71
+
72
+ const filePath = path.join(getAppDir(appName), 'package.json')
73
+
74
+ await writeFile(
75
+ filePath,
76
+ `{
77
+ "name": "${appName}",
78
+ "version": "0.0.1",
79
+ "private": true,
80
+ "scripts": {
81
+ "dev": "npx scripting-cli dev",
82
+ "build": "npx scripting-cli build"
83
+ }
84
+ }`,
85
+ 'utf-8'
86
+ )
87
+
88
+ console.log(
89
+ chalk.green(` ✔️ Created ${appName}/package.json`)
90
+ )
91
+ }
92
+
93
+ async function createReadme(appName: string) {
94
+
95
+ console.log(` > Creating ${appName}/README.md ...`)
96
+
97
+ const filePath = path.join(getAppDir(appName), 'README.md')
98
+
99
+ await writeFile(
100
+ filePath,
101
+ `# ${appName} - A Scripting application
102
+
103
+ ## Quick Start
104
+
105
+ ### Installation
106
+
107
+ \`npm install\`
108
+
109
+ ### Start dev server
110
+
111
+ \`npm run dev\`
112
+
113
+ ### Build App
114
+
115
+ \`npm run build\`
116
+ `,
117
+ 'utf-8'
118
+ )
119
+
120
+ console.log(
121
+ chalk.green(` ✔️ Created ${appName}/README.md`)
122
+ )
123
+ }
124
+
125
+ async function createTSConfig(appName: string) {
126
+
127
+ console.log(` > Creating ${appName}/tsconfig.json ...`)
128
+
129
+ const filePath = path.join(getAppDir(appName), 'tsconfig.json')
130
+
131
+ await writeFile(
132
+ filePath,
133
+ `{
134
+ "compilerOptions": {
135
+ "target": "es5",
136
+ "lib": [
137
+ "esnext",
138
+ ],
139
+ "allowJs": false,
140
+ "skipLibCheck": true,
141
+ "esModuleInterop": true,
142
+ "allowSyntheticDefaultImports": true,
143
+ "strict": true,
144
+ "forceConsistentCasingInFileNames": true,
145
+ "noFallthroughCasesInSwitch": true,
146
+ "module": "esnext",
147
+ "moduleResolution": "node",
148
+ "resolveJsonModule": true,
149
+ "isolatedModules": true,
150
+ "jsx": "react",
151
+ "jsxFactory": "createElement",
152
+ "baseUrl": "src",
153
+ "paths": {
154
+ "@/*": [
155
+ "src/*"
156
+ ]
157
+ }
158
+ },
159
+ "include": [
160
+ "src"
161
+ ],
162
+ }`,
163
+ 'utf-8'
164
+ )
165
+
166
+ console.log(
167
+ chalk.green(` ✔️ Created ${appName}/tsconfig.json`)
168
+ )
169
+ }
170
+
171
+ async function createScriptingDeclaration(appName: string) {
172
+ console.log(` > Creating ${appName}/src/scripting.d.ts ...`)
173
+
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)
178
+
179
+ console.log(
180
+ chalk.green(` ✔️ Created ${appName}/src/scripting.d.ts`)
181
+ )
182
+ }
183
+
184
+ export async function createApp(appName: string) {
185
+ if (!/^[a-zA-Z]+[a-zA-Z0-9-_]+$/.test(appName)) {
186
+ console.log(
187
+ chalk.red(`✖️ Invalid Scripting application name "${appName}"`)
188
+ )
189
+ return
190
+ }
191
+
192
+ try {
193
+ await createAppDir(appName)
194
+ await createPackageJson(appName)
195
+ await createTSConfig(appName)
196
+ await createReadme(appName)
197
+ await createEntryFile(appName)
198
+ await createScriptingDeclaration(appName)
199
+
200
+ // exec('npm i')
201
+ } catch (e: any) {
202
+ console.log(
203
+ chalk.red(`✖️ Create Scripting application failed: ${e.message}`)
204
+ )
205
+ }
206
+ }
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ import minimist from "minimist"
2
+ import { startDevServer } from './startDevServer'
3
+ import { buildApp } from './build'
4
+ import { createApp } from './createApp'
5
+
6
+ function run() {
7
+ const args = minimist(process.argv.slice(2))
8
+
9
+ console.log(args)
10
+ if (args['create'] != null) {
11
+ createApp(args['create'])
12
+ } else if (args._.includes('dev')) {
13
+ startDevServer()
14
+ } else if (args._.includes('build')) {
15
+ buildApp()
16
+ }
17
+
18
+ }
19
+
20
+ run()
@@ -0,0 +1,136 @@
1
+ import http from 'node:http'
2
+ import path from 'node:path'
3
+ import chalk from 'chalk'
4
+ import express from 'express'
5
+ import minimist from 'minimist'
6
+
7
+ import { Server, Socket } from 'socket.io'
8
+
9
+ import * as utils from './utils'
10
+
11
+ import Webpack from "webpack"
12
+ import webpackConfig from './config/webpack.config'
13
+
14
+ export function startDevServer() {
15
+ const args = minimist(process.argv.slice(2))
16
+
17
+ const ipAddress = utils.getIpAddress()
18
+ const port = args['port'] || 8000
19
+
20
+ const app = express()
21
+ const server = http.createServer(app)
22
+ const io = new Server(server)
23
+
24
+ let isStarted = false
25
+ let connectedSockets: Socket[] = []
26
+
27
+ webpackConfig.mode = 'development'
28
+
29
+ const compiler = Webpack(webpackConfig)
30
+
31
+ console.log(
32
+ 'Start running webpack compiler in watch mode...'
33
+ )
34
+
35
+ compiler.watch(
36
+ {
37
+
38
+ },
39
+ (err, stats) => {
40
+ utils.clearConsole()
41
+ if (err) {
42
+ console.log(
43
+ chalk.red('[DevServer] webpack compile error: \n') + err
44
+ )
45
+ } else {
46
+ console.log(stats?.toString({
47
+ chunks: false,
48
+ colors: true,
49
+ }))
50
+
51
+ if (stats?.toJson().errorsCount === 0) {
52
+ onCompileDone()
53
+ }
54
+ }
55
+ }
56
+ )
57
+
58
+ function onCompileDone() {
59
+ if (isStarted) {
60
+ printDevServerAddress()
61
+ console.log(
62
+ chalk.gray(`[DevServer] Sent update event to ${connectedSockets.length} client(s)`)
63
+ )
64
+ connectedSockets.forEach(socket => {
65
+ socket.emit('update')
66
+ })
67
+ } else {
68
+ start()
69
+ }
70
+ }
71
+
72
+ function printDevServerAddress() {
73
+ console.log(`Server running at ${chalk.bold(
74
+ chalk.green(
75
+ `http://${ipAddress}:${port}`
76
+ ),
77
+ )}`)
78
+ }
79
+
80
+ function start() {
81
+ if (isStarted) {
82
+ return
83
+ }
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('Content-Type', 'application/jsoncharset=utf-8')
89
+ res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
90
+ next()
91
+ })
92
+
93
+ app.use(
94
+ '/',
95
+ express.static(
96
+ path.resolve(__dirname, '../build')
97
+ )
98
+ )
99
+
100
+ //有新的客户端连接时触发
101
+ io.on('connection', function (socket) {
102
+ console.log(
103
+ chalk.green(
104
+ '[DevServer] A client connected.'
105
+ )
106
+ )
107
+ connectedSockets.push(socket)
108
+
109
+ socket.on('error', function (err) {
110
+ console.log(
111
+ chalk.red(
112
+ '[DevServer] Error: ', err
113
+ )
114
+ )
115
+ })
116
+
117
+ socket.on('disconnect', function () {
118
+ var index = connectedSockets.indexOf(socket)
119
+ if (index > -1) {
120
+ connectedSockets.splice(index, 1)
121
+ console.log(
122
+ chalk.gray(
123
+ '[DevServer] A client disconnected.'
124
+ )
125
+ )
126
+ }
127
+ })
128
+ })
129
+
130
+ server.listen(port)
131
+ printDevServerAddress()
132
+ isStarted = true
133
+ }
134
+
135
+ }
136
+
package/src/utils.ts ADDED
@@ -0,0 +1,30 @@
1
+
2
+ import os from 'node:os'
3
+
4
+ export function getIpAddress() {
5
+ const interfaces = os.networkInterfaces()
6
+
7
+ for (const devName in interfaces) {
8
+ const iface = interfaces[devName]
9
+
10
+ if (iface == null) {
11
+ continue
12
+ }
13
+
14
+ for (let i = 0; i < iface.length; i++) {
15
+ const alias = iface[i]
16
+ if (alias.family === 'IPv4'
17
+ && alias.address !== '127.0.0.1'
18
+ && !alias.internal
19
+ ) {
20
+ return alias.address
21
+ }
22
+ }
23
+ }
24
+ }
25
+
26
+ export function clearConsole() {
27
+ process.stdout.write(
28
+ process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H'
29
+ )
30
+ }