@steambrew/ttc 1.0.5 → 1.1.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/Compiler.ts CHANGED
@@ -1,242 +1,259 @@
1
- import { OutputOptions, RollupOptions, rollup } from "rollup";
2
- import json from '@rollup/plugin-json';
3
- import commonjs from '@rollup/plugin-commonjs';
4
- import replace from '@rollup/plugin-replace';
5
- import typescript from '@rollup/plugin-typescript';
6
- import resolve from '@rollup/plugin-node-resolve';
7
- import terser from '@rollup/plugin-terser';
8
- import babel from '@rollup/plugin-babel';
9
-
10
- import chalk from 'chalk'
11
- import { Logger } from "./Logger";
12
- import fs from 'fs';
13
-
14
- declare global {
15
- interface Window {
16
- PLUGIN_LIST: any
17
- }
18
- }
19
-
20
- declare const pluginName: string, millennium_main: any, MILLENNIUM_BACKEND_IPC: any
21
-
22
- export interface TranspilerProps {
23
- bTersePlugin?: boolean,
24
- strPluginInternalName: string
25
- }
26
-
27
- const WrappedCallServerMethod = "const __call_server_method__ = (methodName, kwargs) => Millennium.callServerMethod(pluginName, methodName, kwargs)"
28
- const WrappedCallable = "const __wrapped_callable__ = (route) => MILLENNIUM_API.callable(__call_server_method__, route)"
29
-
30
- /**
31
- * @description Append the active plugin to the global plugin
32
- * list and notify that the frontend Loaded.
33
- */
34
- function ExecutePluginModule() {
35
- // Assign the plugin on plugin list.
36
- Object.assign(window.PLUGIN_LIST[pluginName], millennium_main)
37
- // Run the rolled up plugins default exported function
38
- millennium_main["default"]();
39
- MILLENNIUM_BACKEND_IPC.postMessage(1, { pluginName: pluginName })
40
- }
41
-
42
- /**
43
- * @description Append the active plugin to the global plugin
44
- * list and notify that the frontend Loaded.
45
- */
46
- function ExecuteWebkitModule() {
47
- // Assign the plugin on plugin list.
48
- Object.assign(window.PLUGIN_LIST[pluginName], millennium_main)
49
- // Run the rolled up plugins default exported function
50
- millennium_main["default"]();
51
- }
52
-
53
- /**
54
- * @description Simple bootstrap function that initializes PLUGIN_LIST
55
- * for current plugin given that is doesnt exist.
56
- */
57
- function InitializePlugins() {
58
- /**
59
- * This function is called n times depending on n plugin count,
60
- * Create the plugin list if it wasn't already created
61
- */
62
- !window.PLUGIN_LIST && (window.PLUGIN_LIST = {})
63
-
64
- // initialize a container for the plugin
65
- if (!window.PLUGIN_LIST[pluginName]) {
66
- window.PLUGIN_LIST[pluginName] = {};
67
- }
68
- }
69
-
70
- const ContructFunctions = (parts: any) => { return parts.join('\n'); }
71
-
72
- function InsertMillennium(props: TranspilerProps)
73
- {
74
- const generateBundle = (_: unknown, bundle: any) => {
75
- for (const fileName in bundle) {
76
- if (bundle[fileName].type != 'chunk') continue
77
-
78
- Logger.Info("Injecting Millennium shims into module... " + chalk.green.bold("okay"))
79
-
80
- bundle[fileName].code = ContructFunctions([
81
- `const pluginName = "${props.strPluginInternalName}";`,
82
- InitializePlugins.toString(), InitializePlugins.name + "()",
83
- WrappedCallServerMethod, WrappedCallable, bundle[fileName].code,
84
- ExecutePluginModule.toString(), ExecutePluginModule.name + "()"
85
- ])
86
- }
87
- }
88
-
89
- return { name: String(), generateBundle };
90
- }
91
-
92
- function InsertWebkitMillennium(props: TranspilerProps)
93
- {
94
- const generateBundle = (_: unknown, bundle: any) => {
95
- for (const fileName in bundle) {
96
- if (bundle[fileName].type != 'chunk') continue
97
-
98
- Logger.Info("Injecting Millennium shims into webkit module... " + chalk.green.bold("okay"))
99
-
100
- bundle[fileName].code = ContructFunctions([
101
- `const pluginName = "${props.strPluginInternalName}";`,
102
- InitializePlugins.toString(), InitializePlugins.name + "()",
103
- WrappedCallServerMethod, WrappedCallable, bundle[fileName].code,
104
- ExecuteWebkitModule.toString(), ExecuteWebkitModule.name + "()"
105
- ])
106
- }
107
- }
108
-
109
- return { name: String(), generateBundle };
110
- }
111
-
112
- function GetPluginComponents(props: TranspilerProps) {
113
-
114
- let tsConfigPath = `./${GetFrontEndDirectory()}/tsconfig.json`
115
-
116
- if (!fs.existsSync(tsConfigPath)) {
117
- tsConfigPath = './tsconfig.json'
118
- }
119
-
120
- const pluginList = [
121
- InsertMillennium(props),
122
- typescript({
123
- tsconfig: tsConfigPath
124
- }),
125
- resolve(), commonjs(), json(),
126
- replace({
127
- delimiters: ['', ''],
128
- preventAssignment: true,
129
- 'process.env.NODE_ENV' : JSON.stringify('production'),
130
- 'Millennium.callServerMethod' : `__call_server_method__`,
131
- 'client.callable' : `__wrapped_callable__`,
132
- 'client.pluginSelf' : 'window.PLUGIN_LIST[pluginName]',
133
- 'client.Millennium.exposeObj(': 'client.Millennium.exposeObj(exports, '
134
- }),
135
- ]
136
-
137
- if (props.bTersePlugin) {
138
- pluginList.push(terser())
139
- }
140
- return pluginList
141
- }
142
-
143
- function GetWebkitPluginComponents(props: TranspilerProps) {
144
- const pluginList = [
145
- InsertWebkitMillennium(props),
146
- typescript({
147
- tsconfig: './webkit/tsconfig.json'
148
- }),
149
- resolve(), commonjs(), json(),
150
- replace({
151
- delimiters: ['', ''],
152
- preventAssignment: true,
153
- 'Millennium.callServerMethod': `__call_server_method__`,
154
- 'webkit.callable': `__wrapped_callable__`,
155
- }),
156
- babel({
157
- presets: ['@babel/preset-env', '@babel/preset-react'],
158
- babelHelpers: 'bundled',
159
- })
160
- ]
161
-
162
- props.bTersePlugin && pluginList.push(terser())
163
- return pluginList
164
- }
165
-
166
- const GetFrontEndDirectory = () => {
167
- const pluginJsonPath = './plugin.json';
168
- try {
169
- return JSON.parse(fs.readFileSync(pluginJsonPath, 'utf8'))?.frontend ?? "frontend";
170
- }
171
- catch (error) {
172
- return "frontend";
173
- }
174
- }
175
-
176
- export const TranspilerPluginComponent = async (props: TranspilerProps) => {
177
-
178
- const frontendRollupConfig: RollupOptions = {
179
- input: `./${GetFrontEndDirectory()}/index.tsx`,
180
- plugins: GetPluginComponents(props),
181
- context: 'window',
182
- external: (id) => {
183
- if (id === '@steambrew/webkit') {
184
- Logger.Error('The @steambrew/webkit module should not be included in the frontend module, use @steambrew/client instead. Please remove it from the frontend module and try again.')
185
- process.exit(1)
186
- }
187
-
188
- return id === '@steambrew/client' || id === 'react' || id === 'react-dom'
189
- },
190
- output: {
191
- name: "millennium_main",
192
- file: ".millennium/Dist/index.js",
193
- globals: {
194
- "react" : "window.SP_REACT",
195
- "react-dom" : "window.SP_REACTDOM",
196
- "@steambrew/client": "window.MILLENNIUM_API"
197
- },
198
- exports: 'named',
199
- format: 'iife'
200
- }
201
- }
202
-
203
- Logger.Info("Starting build; this may take a few moments...")
204
-
205
- try {
206
- await (await rollup(frontendRollupConfig)).write(frontendRollupConfig.output as OutputOptions);
207
-
208
- if (fs.existsSync(`./webkit/index.tsx`)) {
209
- Logger.Info("Compiling webkit module...")
210
-
211
- const webkitRollupConfig: RollupOptions = {
212
- input: `./webkit/index.tsx`,
213
- plugins: GetWebkitPluginComponents(props),
214
- context: 'window',
215
- external: (id) => {
216
- if (id === '@steambrew/client') {
217
- Logger.Error('The @steambrew/client module should not be included in the webkit module, use @steambrew/webkit instead. Please remove it from the webkit module and try again.')
218
- process.exit(1)
219
- }
220
-
221
- return id === '@steambrew/webkit'
222
- },
223
- output: {
224
- name: "millennium_main",
225
- file: ".millennium/Dist/webkit.js",
226
- exports: 'named',
227
- format: 'iife',
228
- globals: {
229
- "@steambrew/webkit": "window.MILLENNIUM_API"
230
- },
231
- }
232
- }
233
-
234
- await (await rollup(webkitRollupConfig)).write(webkitRollupConfig.output as OutputOptions);
235
- }
236
-
237
- Logger.Info('Build succeeded!', Number((performance.now() - global.PerfStartTime).toFixed(3)), 'ms elapsed.')
238
- }
239
- catch (exception) {
240
- Logger.Error('Build failed!', exception)
241
- }
1
+ import { OutputOptions, RollupOptions, rollup } from "rollup";
2
+ import json from '@rollup/plugin-json';
3
+ import commonjs from '@rollup/plugin-commonjs';
4
+ import replace from '@rollup/plugin-replace';
5
+ import typescript from '@rollup/plugin-typescript';
6
+ import resolve from '@rollup/plugin-node-resolve';
7
+ import terser from '@rollup/plugin-terser';
8
+ import babel from '@rollup/plugin-babel';
9
+
10
+ import chalk from 'chalk'
11
+ import { Logger } from "./Logger";
12
+ import fs from 'fs';
13
+
14
+ import injectProcessEnv from 'rollup-plugin-inject-process-env';
15
+ import dotenv from 'dotenv';
16
+
17
+ const envConfig = dotenv.config().parsed || {};
18
+
19
+ if (envConfig) {
20
+ Logger.Info("Injecting environment variables...")
21
+ }
22
+
23
+ const envVars = Object.keys(envConfig).reduce((acc: any, key) => {
24
+ acc[`process.env.${key}`] = JSON.stringify(envConfig[key]);
25
+ return acc;
26
+ }, {});
27
+
28
+ declare global {
29
+ interface Window {
30
+ PLUGIN_LIST: any
31
+ }
32
+ }
33
+
34
+ declare const pluginName: string, millennium_main: any, MILLENNIUM_BACKEND_IPC: any
35
+
36
+ export interface TranspilerProps {
37
+ bTersePlugin?: boolean,
38
+ strPluginInternalName: string
39
+ }
40
+
41
+ const WrappedCallServerMethod = "const __call_server_method__ = (methodName, kwargs) => Millennium.callServerMethod(pluginName, methodName, kwargs)"
42
+ const WrappedCallable = "const __wrapped_callable__ = (route) => MILLENNIUM_API.callable(__call_server_method__, route)"
43
+
44
+ /**
45
+ * @description Append the active plugin to the global plugin
46
+ * list and notify that the frontend Loaded.
47
+ */
48
+ function ExecutePluginModule() {
49
+ // Assign the plugin on plugin list.
50
+ Object.assign(window.PLUGIN_LIST[pluginName], millennium_main)
51
+ // Run the rolled up plugins default exported function
52
+ millennium_main["default"]();
53
+ MILLENNIUM_BACKEND_IPC.postMessage(1, { pluginName: pluginName })
54
+ }
55
+
56
+ /**
57
+ * @description Append the active plugin to the global plugin
58
+ * list and notify that the frontend Loaded.
59
+ */
60
+ function ExecuteWebkitModule() {
61
+ // Assign the plugin on plugin list.
62
+ Object.assign(window.PLUGIN_LIST[pluginName], millennium_main)
63
+ // Run the rolled up plugins default exported function
64
+ millennium_main["default"]();
65
+ }
66
+
67
+ /**
68
+ * @description Simple bootstrap function that initializes PLUGIN_LIST
69
+ * for current plugin given that is doesnt exist.
70
+ */
71
+ function InitializePlugins() {
72
+ /**
73
+ * This function is called n times depending on n plugin count,
74
+ * Create the plugin list if it wasn't already created
75
+ */
76
+ !window.PLUGIN_LIST && (window.PLUGIN_LIST = {})
77
+
78
+ // initialize a container for the plugin
79
+ if (!window.PLUGIN_LIST[pluginName]) {
80
+ window.PLUGIN_LIST[pluginName] = {};
81
+ }
82
+ }
83
+
84
+ const ContructFunctions = (parts: any) => { return parts.join('\n'); }
85
+
86
+ function InsertMillennium(props: TranspilerProps)
87
+ {
88
+ const generateBundle = (_: unknown, bundle: any) => {
89
+ for (const fileName in bundle) {
90
+ if (bundle[fileName].type != 'chunk') continue
91
+
92
+ Logger.Info("Injecting Millennium shims into module... " + chalk.green.bold("okay"))
93
+
94
+ bundle[fileName].code = ContructFunctions([
95
+ `const pluginName = "${props.strPluginInternalName}";`,
96
+ InitializePlugins.toString(), InitializePlugins.name + "()",
97
+ WrappedCallServerMethod, WrappedCallable, bundle[fileName].code,
98
+ ExecutePluginModule.toString(), ExecutePluginModule.name + "()"
99
+ ])
100
+ }
101
+ }
102
+
103
+ return { name: String(), generateBundle };
104
+ }
105
+
106
+ function InsertWebkitMillennium(props: TranspilerProps)
107
+ {
108
+ const generateBundle = (_: unknown, bundle: any) => {
109
+ for (const fileName in bundle) {
110
+ if (bundle[fileName].type != 'chunk') continue
111
+
112
+ Logger.Info("Injecting Millennium shims into webkit module... " + chalk.green.bold("okay"))
113
+
114
+ bundle[fileName].code = ContructFunctions([
115
+ `const pluginName = "${props.strPluginInternalName}";`,
116
+ InitializePlugins.toString(), InitializePlugins.name + "()",
117
+ WrappedCallServerMethod, WrappedCallable, bundle[fileName].code,
118
+ ExecuteWebkitModule.toString(), ExecuteWebkitModule.name + "()"
119
+ ])
120
+ }
121
+ }
122
+
123
+ return { name: String(), generateBundle };
124
+ }
125
+
126
+ function GetPluginComponents(props: TranspilerProps) {
127
+
128
+ let tsConfigPath = `./${GetFrontEndDirectory()}/tsconfig.json`
129
+
130
+ if (!fs.existsSync(tsConfigPath)) {
131
+ tsConfigPath = './tsconfig.json'
132
+ }
133
+
134
+ const pluginList = [
135
+ InsertMillennium(props),
136
+ typescript({
137
+ tsconfig: tsConfigPath
138
+ }),
139
+ resolve(), commonjs(), json(),
140
+ injectProcessEnv(envVars),
141
+ replace({
142
+ delimiters: ['', ''],
143
+ preventAssignment: true,
144
+ 'process.env.NODE_ENV' : JSON.stringify('production'),
145
+ 'Millennium.callServerMethod' : `__call_server_method__`,
146
+ 'client.callable' : `__wrapped_callable__`,
147
+ 'client.pluginSelf' : 'window.PLUGIN_LIST[pluginName]',
148
+ 'client.Millennium.exposeObj(': 'client.Millennium.exposeObj(exports, '
149
+ }),
150
+ ]
151
+
152
+ if (props.bTersePlugin) {
153
+ pluginList.push(terser())
154
+ }
155
+ return pluginList
156
+ }
157
+
158
+ function GetWebkitPluginComponents(props: TranspilerProps) {
159
+ const pluginList = [
160
+ InsertWebkitMillennium(props),
161
+ typescript({
162
+ tsconfig: './webkit/tsconfig.json'
163
+ }),
164
+ resolve(), commonjs(), json(),
165
+ injectProcessEnv(envVars),
166
+ replace({
167
+ delimiters: ['', ''],
168
+ preventAssignment: true,
169
+ 'Millennium.callServerMethod': `__call_server_method__`,
170
+ 'webkit.callable': `__wrapped_callable__`,
171
+ }),
172
+ babel({
173
+ presets: ['@babel/preset-env', '@babel/preset-react'],
174
+ babelHelpers: 'bundled',
175
+ })
176
+ ]
177
+
178
+ props.bTersePlugin && pluginList.push(terser())
179
+ return pluginList
180
+ }
181
+
182
+ const GetFrontEndDirectory = () => {
183
+ const pluginJsonPath = './plugin.json';
184
+ try {
185
+ return JSON.parse(fs.readFileSync(pluginJsonPath, 'utf8'))?.frontend ?? "frontend";
186
+ }
187
+ catch (error) {
188
+ return "frontend";
189
+ }
190
+ }
191
+
192
+ export const TranspilerPluginComponent = async (props: TranspilerProps) => {
193
+
194
+ const frontendRollupConfig: RollupOptions = {
195
+ input: `./${GetFrontEndDirectory()}/index.tsx`,
196
+ plugins: GetPluginComponents(props),
197
+ context: 'window',
198
+ external: (id) => {
199
+ if (id === '@steambrew/webkit') {
200
+ Logger.Error('The @steambrew/webkit module should not be included in the frontend module, use @steambrew/client instead. Please remove it from the frontend module and try again.')
201
+ process.exit(1)
202
+ }
203
+
204
+ return id === '@steambrew/client' || id === 'react' || id === 'react-dom'
205
+ },
206
+ output: {
207
+ name: "millennium_main",
208
+ file: ".millennium/Dist/index.js",
209
+ globals: {
210
+ "react" : "window.SP_REACT",
211
+ "react-dom" : "window.SP_REACTDOM",
212
+ "@steambrew/client": "window.MILLENNIUM_API"
213
+ },
214
+ exports: 'named',
215
+ format: 'iife'
216
+ }
217
+ }
218
+
219
+ Logger.Info("Starting build; this may take a few moments...")
220
+
221
+ try {
222
+ await (await rollup(frontendRollupConfig)).write(frontendRollupConfig.output as OutputOptions);
223
+
224
+ if (fs.existsSync(`./webkit/index.tsx`)) {
225
+ Logger.Info("Compiling webkit module...")
226
+
227
+ const webkitRollupConfig: RollupOptions = {
228
+ input: `./webkit/index.tsx`,
229
+ plugins: GetWebkitPluginComponents(props),
230
+ context: 'window',
231
+ external: (id) => {
232
+ if (id === '@steambrew/client') {
233
+ Logger.Error('The @steambrew/client module should not be included in the webkit module, use @steambrew/webkit instead. Please remove it from the webkit module and try again.')
234
+ process.exit(1)
235
+ }
236
+
237
+ return id === '@steambrew/webkit'
238
+ },
239
+ output: {
240
+ name: "millennium_main",
241
+ file: ".millennium/Dist/webkit.js",
242
+ exports: 'named',
243
+ format: 'iife',
244
+ globals: {
245
+ "@steambrew/webkit": "window.MILLENNIUM_API"
246
+ },
247
+ }
248
+ }
249
+
250
+ await (await rollup(webkitRollupConfig)).write(webkitRollupConfig.output as OutputOptions);
251
+ }
252
+
253
+ Logger.Info('Build succeeded!', Number((performance.now() - global.PerfStartTime).toFixed(3)), 'ms elapsed.')
254
+ }
255
+ catch (exception) {
256
+ Logger.Error('Build failed!', exception)
257
+ process.exit(1)
258
+ }
242
259
  }
package/Linter.ts CHANGED
@@ -1,44 +1,44 @@
1
- import chalk from 'chalk'
2
- import path from 'path'
3
- import { existsSync, readFile } from 'fs'
4
-
5
- export const ValidatePlugin = (target: string): Promise<any> => {
6
-
7
- return new Promise<any>((resolve, reject) => {
8
- if (!existsSync(target)) {
9
- console.error(chalk.red.bold(`\n[-] --target [${target}] `) + chalk.red("is not a valid system path"))
10
- reject()
11
- return
12
- }
13
-
14
- const pluginModule = path.join(target, "plugin.json")
15
-
16
- if (!existsSync(pluginModule)) {
17
- console.error(chalk.red.bold(`\n[-] --target [${target}] `) + chalk.red("is not a valid plugin (missing plugin.json)"))
18
- reject()
19
- return
20
- }
21
-
22
- readFile(pluginModule, 'utf8', (err, data) => {
23
- if (err) {
24
- console.error(chalk.red.bold(`\n[-] couldn't read plugin.json from [${pluginModule}]`))
25
- reject()
26
- return
27
- }
28
-
29
- try {
30
- if (!("name" in JSON.parse(data))) {
31
- console.error(chalk.red.bold(`\n[-] target plugin doesn't contain "name" in plugin.json [${pluginModule}]`))
32
- reject()
33
- }
34
- else {
35
- resolve(JSON.parse(data))
36
- }
37
- }
38
- catch (parseError) {
39
- console.error(chalk.red.bold(`\n[-] couldn't parse JSON in plugin.json from [${pluginModule}]`))
40
- reject()
41
- }
42
- });
43
- })
1
+ import chalk from 'chalk'
2
+ import path from 'path'
3
+ import { existsSync, readFile } from 'fs'
4
+
5
+ export const ValidatePlugin = (target: string): Promise<any> => {
6
+
7
+ return new Promise<any>((resolve, reject) => {
8
+ if (!existsSync(target)) {
9
+ console.error(chalk.red.bold(`\n[-] --target [${target}] `) + chalk.red("is not a valid system path"))
10
+ reject()
11
+ return
12
+ }
13
+
14
+ const pluginModule = path.join(target, "plugin.json")
15
+
16
+ if (!existsSync(pluginModule)) {
17
+ console.error(chalk.red.bold(`\n[-] --target [${target}] `) + chalk.red("is not a valid plugin (missing plugin.json)"))
18
+ reject()
19
+ return
20
+ }
21
+
22
+ readFile(pluginModule, 'utf8', (err, data) => {
23
+ if (err) {
24
+ console.error(chalk.red.bold(`\n[-] couldn't read plugin.json from [${pluginModule}]`))
25
+ reject()
26
+ return
27
+ }
28
+
29
+ try {
30
+ if (!("name" in JSON.parse(data))) {
31
+ console.error(chalk.red.bold(`\n[-] target plugin doesn't contain "name" in plugin.json [${pluginModule}]`))
32
+ reject()
33
+ }
34
+ else {
35
+ resolve(JSON.parse(data))
36
+ }
37
+ }
38
+ catch (parseError) {
39
+ console.error(chalk.red.bold(`\n[-] couldn't parse JSON in plugin.json from [${pluginModule}]`))
40
+ reject()
41
+ }
42
+ });
43
+ })
44
44
  }
package/Logger.ts CHANGED
@@ -1,49 +1,49 @@
1
- import chalk from 'chalk'
2
-
3
- const Logger = {
4
-
5
- Info: (...LogMessage: any) => {
6
- console.log(chalk.magenta.bold("++"), ...LogMessage)
7
- },
8
-
9
- Warn: (...LogMessage: any) => {
10
- console.log(chalk.yellow.bold("**"), ...LogMessage)
11
- },
12
-
13
- Error: (...LogMessage: any) => {
14
- console.log(chalk.red.bold("!!"), ...LogMessage)
15
- },
16
-
17
- Tree: (strTitle: string, LogObject: any) => {
18
-
19
- console.log(chalk.magenta.bold("++"), strTitle);
20
-
21
- const isLocalPath = (strTestPath: string): boolean => {
22
- // Regular expression to match common file path patterns
23
- const filePathRegex = /^(\/|\.\/|\.\.\/|\w:\/)?([\w-.]+\/)*[\w-.]+\.\w+$/;
24
- return filePathRegex.test(strTestPath);
25
- }
26
-
27
- const entries = Object.entries(LogObject);
28
- const totalEntries = entries.length;
29
-
30
- for (const [index, [key, value]] of entries.entries()) {
31
-
32
- const connector = index === totalEntries - 1 ? " " : " "
33
- let color = chalk.white
34
-
35
- switch (typeof value) {
36
- case typeof String(): {
37
- color = isLocalPath(value as string) ? chalk.blueBright : chalk.white;
38
- break
39
- }
40
- case typeof Boolean(): color = chalk.green; break
41
- case typeof Number(): color = chalk.yellow; break
42
- }
43
-
44
- console.log(chalk.magenta.bold(` ${connector}──${key}:`), color(value))
45
- }
46
- }
47
- }
48
-
1
+ import chalk from 'chalk'
2
+
3
+ const Logger = {
4
+
5
+ Info: (...LogMessage: any) => {
6
+ console.log(chalk.magenta.bold("++"), ...LogMessage)
7
+ },
8
+
9
+ Warn: (...LogMessage: any) => {
10
+ console.log(chalk.yellow.bold("**"), ...LogMessage)
11
+ },
12
+
13
+ Error: (...LogMessage: any) => {
14
+ console.error(chalk.red.bold("!!"), ...LogMessage)
15
+ },
16
+
17
+ Tree: (strTitle: string, LogObject: any) => {
18
+
19
+ console.log(chalk.magenta.bold("++"), strTitle);
20
+
21
+ const isLocalPath = (strTestPath: string): boolean => {
22
+ // Regular expression to match common file path patterns
23
+ const filePathRegex = /^(\/|\.\/|\.\.\/|\w:\/)?([\w-.]+\/)*[\w-.]+\.\w+$/;
24
+ return filePathRegex.test(strTestPath);
25
+ }
26
+
27
+ const entries = Object.entries(LogObject);
28
+ const totalEntries = entries.length;
29
+
30
+ for (const [index, [key, value]] of entries.entries()) {
31
+
32
+ const connector = index === totalEntries - 1 ? " " : " "
33
+ let color = chalk.white
34
+
35
+ switch (typeof value) {
36
+ case typeof String(): {
37
+ color = isLocalPath(value as string) ? chalk.blueBright : chalk.white;
38
+ break
39
+ }
40
+ case typeof Boolean(): color = chalk.green; break
41
+ case typeof Number(): color = chalk.yellow; break
42
+ }
43
+
44
+ console.log(chalk.magenta.bold(` ${connector}──${key}:`), color(value))
45
+ }
46
+ }
47
+ }
48
+
49
49
  export { Logger }
package/Parameters.ts CHANGED
@@ -1,72 +1,72 @@
1
- import chalk from 'chalk'
2
- import { Logger } from "./Logger"
3
-
4
- /***
5
- * @brief print the parameter list to the stdout
6
- */
7
- export const PrintParamHelp = () => {
8
-
9
- console.log(
10
- "millennium-ttc parameter list:" +
11
- "\n\t" + chalk.magenta("--help") + ": display parameter list" +
12
- "\n\t" + chalk.bold.red("--build") + ": " + chalk.bold.red("(required)") + ": build type [dev, prod] (prod minifies code)" +
13
- "\n\t" + chalk.magenta("--target") + ": path to plugin, default to cwd"
14
- );
15
- }
16
-
17
- export enum BuildType {
18
- DevBuild, ProdBuild
19
- }
20
-
21
- export interface ParameterProps {
22
- type: BuildType,
23
- targetPlugin: string // path
24
- }
25
-
26
- export const ValidateParameters = (args: Array<string>): ParameterProps => {
27
-
28
- let typeProp: BuildType = BuildType.DevBuild, targetProp: string = process.cwd()
29
-
30
- if (args.includes("--help")) {
31
- PrintParamHelp()
32
- process.exit();
33
- }
34
-
35
- // startup args are invalid
36
- if (!args.includes("--build")) {
37
- Logger.Error("Received invalid arguments...");
38
- PrintParamHelp();
39
- process.exit();
40
- }
41
-
42
- for (let i = 0; i < args.length; i++)
43
- {
44
- if (args[i] === "--build")
45
- {
46
- const BuildMode: string = args[i + 1]
47
-
48
- switch (BuildMode) {
49
- case "dev": typeProp = BuildType.DevBuild; break
50
- case "prod": typeProp = BuildType.ProdBuild; break
51
- default: {
52
- Logger.Error('--build parameter must be preceded by build type [dev, prod]');
53
- process.exit();
54
- }
55
- }
56
- }
57
-
58
- if (args[i] == "--target") {
59
- if (args[i + 1] === undefined) {
60
- Logger.Error('--target parameter must be preceded by system path');
61
- process.exit();
62
- }
63
-
64
- targetProp = args[i + 1]
65
- }
66
- }
67
-
68
- return {
69
- type: typeProp,
70
- targetPlugin: targetProp
71
- }
1
+ import chalk from 'chalk'
2
+ import { Logger } from "./Logger"
3
+
4
+ /***
5
+ * @brief print the parameter list to the stdout
6
+ */
7
+ export const PrintParamHelp = () => {
8
+
9
+ console.log(
10
+ "millennium-ttc parameter list:" +
11
+ "\n\t" + chalk.magenta("--help") + ": display parameter list" +
12
+ "\n\t" + chalk.bold.red("--build") + ": " + chalk.bold.red("(required)") + ": build type [dev, prod] (prod minifies code)" +
13
+ "\n\t" + chalk.magenta("--target") + ": path to plugin, default to cwd"
14
+ );
15
+ }
16
+
17
+ export enum BuildType {
18
+ DevBuild, ProdBuild
19
+ }
20
+
21
+ export interface ParameterProps {
22
+ type: BuildType,
23
+ targetPlugin: string // path
24
+ }
25
+
26
+ export const ValidateParameters = (args: Array<string>): ParameterProps => {
27
+
28
+ let typeProp: BuildType = BuildType.DevBuild, targetProp: string = process.cwd()
29
+
30
+ if (args.includes("--help")) {
31
+ PrintParamHelp()
32
+ process.exit();
33
+ }
34
+
35
+ // startup args are invalid
36
+ if (!args.includes("--build")) {
37
+ Logger.Error("Received invalid arguments...");
38
+ PrintParamHelp();
39
+ process.exit();
40
+ }
41
+
42
+ for (let i = 0; i < args.length; i++)
43
+ {
44
+ if (args[i] === "--build")
45
+ {
46
+ const BuildMode: string = args[i + 1]
47
+
48
+ switch (BuildMode) {
49
+ case "dev": typeProp = BuildType.DevBuild; break
50
+ case "prod": typeProp = BuildType.ProdBuild; break
51
+ default: {
52
+ Logger.Error('--build parameter must be preceded by build type [dev, prod]');
53
+ process.exit();
54
+ }
55
+ }
56
+ }
57
+
58
+ if (args[i] == "--target") {
59
+ if (args[i + 1] === undefined) {
60
+ Logger.Error('--target parameter must be preceded by system path');
61
+ process.exit();
62
+ }
63
+
64
+ targetProp = args[i + 1]
65
+ }
66
+ }
67
+
68
+ return {
69
+ type: typeProp,
70
+ targetPlugin: targetProp
71
+ }
72
72
  }
package/VersionMon.ts CHANGED
@@ -1,28 +1,28 @@
1
- import path from 'path';
2
- import { fileURLToPath } from 'url';
3
- import { readFile } from 'fs/promises';
4
- import { dirname } from 'path';
5
- import { Logger } from './Logger';
6
-
7
- export const CheckForUpdates = async (): Promise<boolean> => {
8
- return new Promise<boolean>(async (resolve) => {
9
- const packageJsonPath = path.resolve(dirname(fileURLToPath(import.meta.url)), '../package.json');
10
- const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8'));
11
-
12
- fetch("https://registry.npmjs.org/@steambrew/ttc").then(response => response.json()).then(json => {
13
-
14
- if (json?.["dist-tags"]?.latest != packageJson.version) {
15
-
16
- Logger.Tree(`@steambrew/ttc@${packageJson.version} requires update to ${json?.["dist-tags"]?.latest}`, {
17
- cmd: `run "npm install @steambrew/ttc@${json?.["dist-tags"]?.latest}" to get latest updates!`
18
- })
19
-
20
- resolve(true)
21
- }
22
- else {
23
- Logger.Info(`@steambrew/ttc@${packageJson.version} is up-to-date!`)
24
- resolve(false)
25
- }
26
- })
27
- })
1
+ import path from 'path';
2
+ import { fileURLToPath } from 'url';
3
+ import { readFile } from 'fs/promises';
4
+ import { dirname } from 'path';
5
+ import { Logger } from './Logger';
6
+
7
+ export const CheckForUpdates = async (): Promise<boolean> => {
8
+ return new Promise<boolean>(async (resolve) => {
9
+ const packageJsonPath = path.resolve(dirname(fileURLToPath(import.meta.url)), '../package.json');
10
+ const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8'));
11
+
12
+ fetch("https://registry.npmjs.org/@steambrew/ttc").then(response => response.json()).then(json => {
13
+
14
+ if (json?.["dist-tags"]?.latest != packageJson.version) {
15
+
16
+ Logger.Tree(`@steambrew/ttc@${packageJson.version} requires update to ${json?.["dist-tags"]?.latest}`, {
17
+ cmd: `run "npm install @steambrew/ttc@${json?.["dist-tags"]?.latest}" to get latest updates!`
18
+ })
19
+
20
+ resolve(true)
21
+ }
22
+ else {
23
+ Logger.Info(`@steambrew/ttc@${packageJson.version} is up-to-date!`)
24
+ resolve(false)
25
+ }
26
+ })
27
+ })
28
28
  }
package/dist/index.js CHANGED
@@ -12,6 +12,8 @@ import typescript from '@rollup/plugin-typescript';
12
12
  import resolve from '@rollup/plugin-node-resolve';
13
13
  import terser from '@rollup/plugin-terser';
14
14
  import babel from '@rollup/plugin-babel';
15
+ import injectProcessEnv from 'rollup-plugin-inject-process-env';
16
+ import dotenv from 'dotenv';
15
17
  import { performance as performance$1 } from 'perf_hooks';
16
18
 
17
19
  const Logger = {
@@ -22,7 +24,7 @@ const Logger = {
22
24
  console.log(chalk.yellow.bold("**"), ...LogMessage);
23
25
  },
24
26
  Error: (...LogMessage) => {
25
- console.log(chalk.red.bold("!!"), ...LogMessage);
27
+ console.error(chalk.red.bold("!!"), ...LogMessage);
26
28
  },
27
29
  Tree: (strTitle, LogObject) => {
28
30
  console.log(chalk.magenta.bold("++"), strTitle);
@@ -164,6 +166,14 @@ const ValidatePlugin = (target) => {
164
166
  });
165
167
  };
166
168
 
169
+ const envConfig = dotenv.config().parsed || {};
170
+ if (envConfig) {
171
+ Logger.Info("Injecting environment variables...");
172
+ }
173
+ const envVars = Object.keys(envConfig).reduce((acc, key) => {
174
+ acc[`process.env.${key}`] = JSON.stringify(envConfig[key]);
175
+ return acc;
176
+ }, {});
167
177
  const WrappedCallServerMethod = "const __call_server_method__ = (methodName, kwargs) => Millennium.callServerMethod(pluginName, methodName, kwargs)";
168
178
  const WrappedCallable = "const __wrapped_callable__ = (route) => MILLENNIUM_API.callable(__call_server_method__, route)";
169
179
  /**
@@ -246,6 +256,7 @@ function GetPluginComponents(props) {
246
256
  tsconfig: tsConfigPath
247
257
  }),
248
258
  resolve(), commonjs(), json(),
259
+ injectProcessEnv(envVars),
249
260
  replace({
250
261
  delimiters: ['', ''],
251
262
  preventAssignment: true,
@@ -268,6 +279,7 @@ function GetWebkitPluginComponents(props) {
268
279
  tsconfig: './webkit/tsconfig.json'
269
280
  }),
270
281
  resolve(), commonjs(), json(),
282
+ injectProcessEnv(envVars),
271
283
  replace({
272
284
  delimiters: ['', ''],
273
285
  preventAssignment: true,
@@ -347,6 +359,7 @@ const TranspilerPluginComponent = async (props) => {
347
359
  }
348
360
  catch (exception) {
349
361
  Logger.Error('Build failed!', exception);
362
+ process.exit(1);
350
363
  }
351
364
  };
352
365
 
@@ -361,11 +374,11 @@ const CheckModuleUpdates = async () => {
361
374
  const StartCompilerModule = () => {
362
375
  const parameters = ValidateParameters(process.argv.slice(2));
363
376
  const bTersePlugin = parameters.type == BuildType.ProdBuild;
364
- // Logger.Tree("Transpiler config: ", {
365
- // target: parameters.targetPlugin,
366
- // build: BuildType[parameters.type],
367
- // minify: bTersePlugin
368
- // })
377
+ Logger.Tree("Transpiler config: ", {
378
+ target: parameters.targetPlugin,
379
+ build: BuildType[parameters.type],
380
+ minify: bTersePlugin
381
+ });
369
382
  ValidatePlugin(parameters.targetPlugin).then((json) => {
370
383
  const props = {
371
384
  bTersePlugin: bTersePlugin,
package/index.ts CHANGED
@@ -1,66 +1,67 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * this component serves as:
5
- * - typescript transpiler
6
- * - rollup configurator
7
- */
8
- import { BuildType, ValidateParameters } from "./Parameters"
9
- import { CheckForUpdates } from "./VersionMon"
10
- import { ValidatePlugin } from './Linter'
11
- import { TranspilerPluginComponent, TranspilerProps } from './Compiler'
12
- import { performance } from 'perf_hooks';
13
- // import { Logger } from './Logger'
14
-
15
- declare global {
16
- var PerfStartTime: number;
17
- }
18
-
19
- const CheckModuleUpdates = async () => {
20
- return await CheckForUpdates()
21
- }
22
-
23
- const StartCompilerModule = () => {
24
-
25
- const parameters = ValidateParameters( process.argv.slice(2) );
26
- const bTersePlugin = parameters.type == BuildType.ProdBuild
27
-
28
- // Logger.Tree("Transpiler config: ", {
29
- // target: parameters.targetPlugin,
30
- // build: BuildType[parameters.type],
31
- // minify: bTersePlugin
32
- // })
33
-
34
- ValidatePlugin(parameters.targetPlugin).then((json: any) => {
35
-
36
- const props: TranspilerProps = {
37
- bTersePlugin: bTersePlugin,
38
- strPluginInternalName: json?.name
39
- }
40
-
41
- TranspilerPluginComponent(props)
42
- })
43
-
44
- /**
45
- * plugin is invalid, we close the proccess as it has already been handled
46
- */
47
- .catch(() => {
48
- process.exit()
49
- })
50
- }
51
-
52
- const Initialize = () => {
53
- global.PerfStartTime = performance.now();
54
-
55
- // Check for --no-update flag
56
- if (process.argv.includes("--no-update")) {
57
- StartCompilerModule()
58
- return
59
- }
60
-
61
- CheckModuleUpdates().then((needsUpdate: boolean) => {
62
- needsUpdate ? process.exit() : StartCompilerModule()
63
- })
64
- }
65
-
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * this component serves as:
5
+ * - typescript transpiler
6
+ * - rollup configurator
7
+ */
8
+ import { BuildType, ValidateParameters } from "./Parameters"
9
+ import { CheckForUpdates } from "./VersionMon"
10
+ import { ValidatePlugin } from './Linter'
11
+ import { TranspilerPluginComponent, TranspilerProps } from './Compiler'
12
+ import { performance } from 'perf_hooks';
13
+ import { Logger } from "./Logger";
14
+ // import { Logger } from './Logger'
15
+
16
+ declare global {
17
+ var PerfStartTime: number;
18
+ }
19
+
20
+ const CheckModuleUpdates = async () => {
21
+ return await CheckForUpdates()
22
+ }
23
+
24
+ const StartCompilerModule = () => {
25
+
26
+ const parameters = ValidateParameters( process.argv.slice(2) );
27
+ const bTersePlugin = parameters.type == BuildType.ProdBuild
28
+
29
+ Logger.Tree("Transpiler config: ", {
30
+ target: parameters.targetPlugin,
31
+ build: BuildType[parameters.type],
32
+ minify: bTersePlugin
33
+ })
34
+
35
+ ValidatePlugin(parameters.targetPlugin).then((json: any) => {
36
+
37
+ const props: TranspilerProps = {
38
+ bTersePlugin: bTersePlugin,
39
+ strPluginInternalName: json?.name
40
+ }
41
+
42
+ TranspilerPluginComponent(props)
43
+ })
44
+
45
+ /**
46
+ * plugin is invalid, we close the proccess as it has already been handled
47
+ */
48
+ .catch(() => {
49
+ process.exit()
50
+ })
51
+ }
52
+
53
+ const Initialize = () => {
54
+ global.PerfStartTime = performance.now();
55
+
56
+ // Check for --no-update flag
57
+ if (process.argv.includes("--no-update")) {
58
+ StartCompilerModule()
59
+ return
60
+ }
61
+
62
+ CheckModuleUpdates().then((needsUpdate: boolean) => {
63
+ needsUpdate ? process.exit() : StartCompilerModule()
64
+ })
65
+ }
66
+
66
67
  Initialize();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steambrew/ttc",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -18,21 +18,23 @@
18
18
  "license": "ISC",
19
19
  "description": "A tiny typescript compiler for Millennium plugins.",
20
20
  "dependencies": {
21
+ "@babel/preset-env": "^7.26.0",
22
+ "@babel/preset-react": "^7.25.9",
23
+ "@rollup/plugin-babel": "^6.0.4",
21
24
  "@rollup/plugin-commonjs": "^28.0.1",
22
25
  "@rollup/plugin-json": "^6.1.0",
23
26
  "@rollup/plugin-node-resolve": "^15.3.0",
24
27
  "@rollup/plugin-replace": "^6.0.1",
25
28
  "@rollup/plugin-terser": "^0.4.4",
26
29
  "@rollup/plugin-typescript": "^12.1.1",
27
- "@rollup/plugin-babel": "^6.0.4",
28
- "@babel/preset-react": "^7.25.9",
29
- "@babel/preset-env": "^7.26.0",
30
- "rollup": "^4.28.0",
31
30
  "chalk": "^5.3.0",
31
+ "dotenv": "^16.4.7",
32
32
  "fs": "^0.0.1-security",
33
+ "rollup": "^4.28.0",
34
+ "rollup-plugin-inject-process-env": "^1.3.1",
33
35
  "tslib": "^2.8.1"
34
36
  },
35
37
  "devDependencies": {
36
38
  "@types/node": "^22.10.1"
37
39
  }
38
- }
40
+ }
package/rollup.config.js CHANGED
@@ -1,29 +1,31 @@
1
- import commonjs from '@rollup/plugin-commonjs';
2
- import typescript from '@rollup/plugin-typescript';
3
- import json from '@rollup/plugin-json';
4
-
5
- export default {
6
- input: 'index.ts',
7
- context: 'window',
8
- output: {
9
- file: 'dist/index.js'
10
- },
11
- plugins: [commonjs(), typescript(), json()],
12
- external: [
13
- "chalk",
14
- "path",
15
- "url",
16
- "fs/promises",
17
- "fs",
18
- "rollup",
19
- "@rollup/plugin-json",
20
- "@rollup/plugin-commonjs",
21
- "@rollup/plugin-replace",
22
- "@rollup/plugin-typescript",
23
- "@rollup/plugin-node-resolve",
24
- "rollup-plugin-import-css",
25
- "@rollup/plugin-terser",
26
- "@rollup/plugin-babel",
27
- "perf_hooks",
28
- ]
1
+ import commonjs from '@rollup/plugin-commonjs';
2
+ import typescript from '@rollup/plugin-typescript';
3
+ import json from '@rollup/plugin-json';
4
+
5
+ export default {
6
+ input: 'index.ts',
7
+ context: 'window',
8
+ output: {
9
+ file: 'dist/index.js'
10
+ },
11
+ plugins: [commonjs(), typescript(), json()],
12
+ external: [
13
+ "chalk",
14
+ "path",
15
+ "url",
16
+ "fs/promises",
17
+ "fs",
18
+ "rollup",
19
+ "@rollup/plugin-json",
20
+ "@rollup/plugin-commonjs",
21
+ "@rollup/plugin-replace",
22
+ "@rollup/plugin-typescript",
23
+ "@rollup/plugin-node-resolve",
24
+ "rollup-plugin-import-css",
25
+ "@rollup/plugin-terser",
26
+ "@rollup/plugin-babel",
27
+ "rollup-plugin-inject-process-env",
28
+ "dotenv",
29
+ "perf_hooks",
30
+ ]
29
31
  };
package/tsconfig.json CHANGED
@@ -1,24 +1,24 @@
1
- {
2
- "compilerOptions": {
3
- "outDir": "dist",
4
- "module": "ESNext",
5
- "target": "ES2020",
6
- "jsx": "react",
7
- "jsxFactory": "window.SP_REACT.createElement",
8
- "declaration": false,
9
- "moduleResolution": "node",
10
- "noUnusedLocals": true,
11
- "noUnusedParameters": true,
12
- "esModuleInterop": true,
13
- "noImplicitReturns": true,
14
- "noImplicitThis": true,
15
- "noImplicitAny": true,
16
- "strict": true,
17
- "ignoreDeprecations": "5.0",
18
- "allowSyntheticDefaultImports": true,
19
- "skipLibCheck": true
20
- },
21
- "include": ["./"],
22
- "exclude": ["node_modules"]
23
- }
1
+ {
2
+ "compilerOptions": {
3
+ "outDir": "dist",
4
+ "module": "ESNext",
5
+ "target": "ES2020",
6
+ "jsx": "react",
7
+ "jsxFactory": "window.SP_REACT.createElement",
8
+ "declaration": false,
9
+ "moduleResolution": "node",
10
+ "noUnusedLocals": true,
11
+ "noUnusedParameters": true,
12
+ "esModuleInterop": true,
13
+ "noImplicitReturns": true,
14
+ "noImplicitThis": true,
15
+ "noImplicitAny": true,
16
+ "strict": true,
17
+ "ignoreDeprecations": "5.0",
18
+ "allowSyntheticDefaultImports": true,
19
+ "skipLibCheck": true
20
+ },
21
+ "include": ["./"],
22
+ "exclude": ["node_modules"]
23
+ }
24
24