@ptkl/toolkit 0.4.0 → 0.6.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.
@@ -1,12 +1,14 @@
1
1
  import CompilerSDK4 from "./sdk4/vue2.js";
2
2
  import CompilerSDK5 from "./sdk5/vue2.js";
3
3
  import CompilerSDK5Vue3 from "./sdk5/vue3.js";
4
+ import CompiltedSDK5React from "./sdk5/react.js";
4
5
  const latestVersion = 5;
5
6
  const defaultEngine = 'vue2';
6
7
  const compilers = {
7
8
  'sdk4::vue2': new CompilerSDK4,
8
9
  'sdk5::vue2': new CompilerSDK5,
9
10
  'sdk5::vue3': new CompilerSDK5Vue3,
11
+ 'sdk5::react': new CompiltedSDK5React,
10
12
  };
11
13
  export default {
12
14
  getCompiler(sdkVersion, engine) {
@@ -0,0 +1,35 @@
1
+ import * as Babel from '@babel/standalone';
2
+ import less from 'less';
3
+ export default class Compiler {
4
+ async compileBabel(expression) {
5
+ let code = Babel.transform(expression, { sourceType: "module", presets: ["env", "react"] });
6
+ return code.code;
7
+ }
8
+ async compileCSS(scope, lang, expression) {
9
+ switch (lang) {
10
+ case 'less':
11
+ if (scope) {
12
+ return await less.render(`.${scope} { ${expression} }`);
13
+ }
14
+ const { css } = await less.render(`${expression}`);
15
+ return css;
16
+ default:
17
+ return expression;
18
+ }
19
+ }
20
+ async compile(ext, content) {
21
+ switch (ext) {
22
+ case 'js':
23
+ return await this.compileBabel(content);
24
+ case 'css':
25
+ return await this.compileCSS(null, "css", content);
26
+ case 'less':
27
+ return await this.compileCSS(null, "less", content);
28
+ default:
29
+ return await Promise.resolve(content);
30
+ }
31
+ }
32
+ getSupportedExt() {
33
+ return ["vue", "js", "css", "less", "json", "svg"];
34
+ }
35
+ }
@@ -30,11 +30,9 @@ class ComponentCommand {
30
30
  const nodes = JSON.parse(message.toString());
31
31
  try {
32
32
  let dist = null;
33
- if (version === '5') {
34
- const builder = new Builder(5, "vue2");
35
- const compiledFiles = await builder.buildFromNodes(nodes);
36
- dist = Object.assign({}, compiledFiles);
37
- }
33
+ const builder = new Builder(version, engine);
34
+ const compiledFiles = await builder.buildFromNodes(nodes);
35
+ dist = Object.assign({}, compiledFiles);
38
36
  socket.send(JSON.stringify({ dist }));
39
37
  console.log('Component templates built successfully');
40
38
  // Do something with the parsed JSON
@@ -62,9 +60,18 @@ class ComponentCommand {
62
60
  const bundle = await rollup({
63
61
  input: inputPath,
64
62
  ...rollupOptions,
63
+ external: [],
65
64
  output: outputOptions,
66
65
  });
67
66
  const { output } = await bundle.generate(outputOptions);
67
+ bundle.write({
68
+ dir: resolve(path, 'dist'),
69
+ format: 'esm',
70
+ entryFileNames: '[name].js',
71
+ chunkFileNames: '[name]-[hash].js',
72
+ assetFileNames: '[name]-[hash][extname]',
73
+ sourcemap: true,
74
+ });
68
75
  console.log(`Bundle generated with size ${output[0].code.length} bytes`);
69
76
  const profile = util.getCurrentProfile();
70
77
  const client = new Api({ token: profile.token, host: profile.host }).component(name);
@@ -30,70 +30,99 @@ class ForgeCommand {
30
30
  }
31
31
  async bundle(options) {
32
32
  const { path, upload } = options;
33
- const module = await import(`${path}/ptkl.config.js`);
34
- const { views, name, version, distPath, icon, type, label, permissions, } = module.default ?? {};
35
- // build manifest file
36
- const manifest = {
37
- name,
38
- version,
39
- views: {},
40
- label,
41
- icon,
42
- permissions,
43
- type: type || 'platform', // default to 'platform' if not specified
44
- };
45
- const client = Util.getClientForProfile();
46
- // get base url of the platform client
47
- const baseUrl = client.getPlatformBaseURL();
48
- const base = `${baseUrl}/luma/appservice/v1/forge/static/bundle/${name}/${version}`;
49
- manifest.icon = `${base}/${icon}`;
50
- const buildViews = Object.keys(views).map((view) => {
51
- manifest.views[view] = `${view}.bundle.js`;
52
- return build({
53
- root: path,
54
- base,
55
- build: {
56
- rollupOptions: {
57
- input: views[view],
58
- output: {
59
- format: 'esm',
60
- entryFileNames: `${view}.bundle.js`,
61
- assetFileNames: (assetInfo) => {
62
- return '[name].[ext]'; // Example: Customize the output file name format
63
- },
64
- }
33
+ // Store original working directory
34
+ const originalCwd = process.cwd();
35
+ try {
36
+ // Change to the app directory
37
+ process.chdir(path);
38
+ const module = await import(`${path}/ptkl.config.js`);
39
+ const { views, name, version, distPath, icon, type, label, permissions, } = module.default ?? {};
40
+ // build manifest file
41
+ const manifest = {
42
+ name,
43
+ version,
44
+ views: {},
45
+ label,
46
+ icon,
47
+ permissions,
48
+ type: type || 'platform', // default to 'platform' if not specified
49
+ };
50
+ const client = Util.getClientForProfile();
51
+ // get base url of the platform client
52
+ const baseUrl = client.getPlatformBaseURL();
53
+ const base = `${baseUrl}/luma/appservice/v1/forge/static/bundle/${name}/${version}/`;
54
+ manifest.icon = `${base}/${icon}`;
55
+ const buildViews = Object.keys(views).map((view) => {
56
+ manifest.views[view] = `${view}.bundle.js`;
57
+ return build({
58
+ root: path,
59
+ base,
60
+ build: {
61
+ rollupOptions: {
62
+ input: views[view],
63
+ output: {
64
+ format: 'esm',
65
+ entryFileNames: `[name].bundle.js`,
66
+ assetFileNames: (assetInfo) => {
67
+ return '[name].[ext]'; // Example: Customize the output file name format
68
+ },
69
+ manualChunks: undefined,
70
+ inlineDynamicImports: true,
71
+ }
72
+ },
65
73
  },
66
- }
67
- });
68
- });
69
- await Promise.allSettled(buildViews);
70
- console.log("Packaging app...");
71
- // // write manifest file
72
- const manifestPath = `${distPath}/manifest.json`;
73
- writeFileSync(manifestPath, JSON.stringify(manifest, null, 4));
74
- if (upload) {
75
- let buffer = Buffer.alloc(0);
76
- const bufferStream = new Writable({
77
- write(chunk, encoding, callback) {
78
- buffer = Buffer.concat([buffer, chunk]);
79
- callback();
80
- },
81
- });
82
- c({ gzip: true, cwd: distPath }, ['.']).pipe(bufferStream).on('finish', () => {
83
- client.forge().bundleUpload(buffer).then(() => {
84
- console.log('Bundle uploaded successfully');
74
+ plugins: [
75
+ {
76
+ name: 'transform-dynamic-imports',
77
+ generateBundle(options, bundle) {
78
+ // Transform after bundling is complete
79
+ for (const fileName in bundle) {
80
+ const chunk = bundle[fileName];
81
+ if (chunk.type === 'chunk' && chunk.code) {
82
+ // Transform dynamic imports in the final bundled code
83
+ chunk.code = chunk.code.replace(/import\(['"`]\.\/([^'"`]+)['"`]\)/g, `dynamicImport('${base}$1')`);
84
+ // Also handle relative paths without ./
85
+ chunk.code = chunk.code.replace(/import\(['"`]([^'"`\/]+\.js)['"`]\)/g, `dynamicImport('${base}$1')`);
86
+ }
87
+ }
88
+ }
89
+ },
90
+ ]
85
91
  });
86
92
  });
87
- }
88
- else {
89
- try {
90
- await c({ gzip: true, cwd: distPath, file: join(distPath, `/../bundle-${manifest.version}.tar.gz`) }, ['.']);
91
- console.log('Bundle created successfully');
93
+ await Promise.allSettled(buildViews);
94
+ console.log("Packaging app...");
95
+ // // write manifest file
96
+ const manifestPath = `${distPath}/manifest.json`;
97
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 4));
98
+ if (upload) {
99
+ let buffer = Buffer.alloc(0);
100
+ const bufferStream = new Writable({
101
+ write(chunk, encoding, callback) {
102
+ buffer = Buffer.concat([buffer, chunk]);
103
+ callback();
104
+ },
105
+ });
106
+ c({ gzip: true, cwd: distPath }, ['.']).pipe(bufferStream).on('finish', () => {
107
+ client.forge().bundleUpload(buffer).then(() => {
108
+ console.log('Bundle uploaded successfully');
109
+ });
110
+ });
92
111
  }
93
- catch (error) {
94
- throw error;
112
+ else {
113
+ try {
114
+ await c({ gzip: true, cwd: distPath, file: join(distPath, `/../bundle-${manifest.version}.tar.gz`) }, ['.']);
115
+ console.log('Bundle created successfully');
116
+ }
117
+ catch (error) {
118
+ throw error;
119
+ }
95
120
  }
96
121
  }
122
+ finally {
123
+ // Always restore the original working directory
124
+ process.chdir(originalCwd);
125
+ }
97
126
  }
98
127
  async runDev(options) {
99
128
  const { path } = options;
@@ -1,7 +1,7 @@
1
1
  import { Command } from "commander";
2
2
  import util from "../lib/util.js";
3
3
  import cli from "../lib/cli.js";
4
- import { APIUser } from "@ptkl/sdk";
4
+ import { APIUser, User } from "@ptkl/sdk";
5
5
  class ProfileCommand {
6
6
  register() {
7
7
  return new Command('profile')
@@ -44,21 +44,34 @@ class ProfileCommand {
44
44
  async new(options) {
45
45
  // try to find profile with the name
46
46
  const { name, username, password, project, host } = options;
47
+ let token = "";
48
+ // if username is email then login to platform as user
49
+ if (username && username.includes('@')) {
50
+ const user = new User({
51
+ username,
52
+ password,
53
+ host,
54
+ });
55
+ const { data } = await user.auth(username, password, project);
56
+ token = "SESSION:" + data.token;
57
+ }
58
+ else {
59
+ const user = new APIUser({
60
+ host,
61
+ });
62
+ const { data } = await user.auth(username, password, project);
63
+ token = data.Token;
64
+ }
47
65
  const profiles = util.getProfiles() ?? [];
48
66
  // try to find that the profile with the name already exist
49
67
  const profile = profiles.find((p) => p.name == name);
50
68
  if (profile) {
51
69
  throw new Error(`Profile with ${name} already exist`);
52
70
  }
53
- const user = new APIUser({
54
- host,
55
- });
56
- // authenticate to protokol
57
- const { data } = await user.auth(username, password, project);
58
71
  profiles.push({
59
72
  name,
60
73
  username,
61
- token: data.Token,
74
+ token,
62
75
  host
63
76
  });
64
77
  util.updateProfiles(profiles);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "scripts": {
5
5
  "test": "echo \"Error: no test specified\" && exit 1",
6
6
  "build": "npx tsc",
@@ -13,7 +13,7 @@
13
13
  "type": "module",
14
14
  "dependencies": {
15
15
  "@babel/standalone": "^7.26.10",
16
- "@ptkl/sdk": "^0.4.0",
16
+ "@ptkl/sdk": "^0.9.0",
17
17
  "@types/axios": "^0.14.0",
18
18
  "@types/commander": "^2.12.2",
19
19
  "@types/js-yaml": "^4.0.9",
@@ -1,74 +0,0 @@
1
- import { Command } from "commander";
2
- import { basename } from "path";
3
- import * as readlinePromises from "readline/promises";
4
- import { stdin, stdout } from "process";
5
- import { existsSync, writeFileSync } from "fs";
6
- class Pull {
7
- register() {
8
- return new Command("pull")
9
- .description("Pull resources with latest api Verison")
10
- .version("0.1.0")
11
- .requiredOption("-r, --resource <resource>", "Resource to pull data from ")
12
- .option("--ref <ref>", "Resource identifier")
13
- .requiredOption("-o --output <output>", "file path to store output yaml")
14
- .action((opts) => this.pull(opts));
15
- }
16
- async pull(opts) {
17
- console.log("not implemented");
18
- // const { ref, output, resource } = opts;
19
- // const profile = util.getCurrentProfile();
20
- // const client = new Api({ project: profile.project, token: profile.token, host: profile.host }).resource(resource);
21
- // // await client.pull(ref,output)
22
- // // const resourceConfig = (config as any).resources[this.resourceType];
23
- // let data;
24
- // let resData, modifiedDoc, modifiedDocsArr;
25
- // let dirFlag = false;
26
- // let pullCount = 0;
27
- // if (ref) {
28
- // resData = await client.single(ref);
29
- // console.log(`Resource : ${resource} with Ref: ${ref} pulled`)
30
- // modifiedDoc = client.modifyDoc(resData);
31
- // data = yaml.dump(modifiedDoc);
32
- // } else {
33
- // resData = await client.all();
34
- // pullCount= resData.length
35
- // console.log(`Resource : ${resource}'s pulled with count: (${pullCount})`)
36
- // modifiedDocsArr = resData.map((doc: any) => {
37
- // let modifiedDoc = client.modifyDoc(doc);
38
- // return yaml.dump(modifiedDoc);
39
- // });
40
- // if (extname(output) === ".yaml") {
41
- // data = modifiedDocsArr.join("---\n");
42
- // } else {
43
- // if (!existsSync(output)) {
44
- // mkdirSync(output, { recursive: true });
45
- // }
46
- // dirFlag = true;
47
- // data = modifiedDocsArr;
48
- // }
49
- // }
50
- // if (dirFlag) {
51
- // for (const [index, doc] of data.entries()) {
52
- // let filepath = join(output, `${resData[index].uuid}.yaml`);
53
- // await this.writeToFile(filepath, doc);
54
- // console.log(`Resource : ${resource} with UUID: ${resData[index].uuid} written to file` )
55
- // }
56
- // } else {
57
- // await this.writeToFile(output, data);
58
- // console.log(`Resource : ${resource}'s pulled and wriiten to file with count:(${pullCount})`)
59
- // }
60
- }
61
- async writeToFile(path, doc) {
62
- if (existsSync(path)) {
63
- let rl = readlinePromises.createInterface(stdin, stdout);
64
- let ans = await rl.question(`Do You want override the output file: ${basename(path)} -(y,n):`);
65
- if (ans.trim() === "y")
66
- writeFileSync(path, doc);
67
- rl.close();
68
- }
69
- else {
70
- writeFileSync(path, doc);
71
- }
72
- }
73
- }
74
- export default new Pull;