@jitar/plugin-vite 0.7.6 → 0.8.1

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/dist/index.d.ts CHANGED
@@ -1,2 +1,11 @@
1
1
  import { PluginOption } from 'vite';
2
- export default function viteJitar(sourcePath: string, jitarPath: string, jitarUrl: string, segments?: string[], middlewares?: string[]): PluginOption;
2
+ type PluginConfig = {
3
+ sourceDir: string;
4
+ targetDir: string;
5
+ jitarDir: string;
6
+ jitarUrl: string;
7
+ segments?: string[];
8
+ middleware?: string[];
9
+ };
10
+ export type { PluginConfig as JitarConfig };
11
+ export default function viteJitar(pluginConfig: PluginConfig): PluginOption;
package/dist/index.js CHANGED
@@ -1,86 +1,150 @@
1
+ import fs from 'fs';
1
2
  import path from 'path';
2
3
  import { normalizePath } from 'vite';
3
- import { Reflector, ReflectionFunction } from '@jitar/reflection';
4
- const reflector = new Reflector();
5
- function formatPath(path) {
6
- path = normalizePath(path);
7
- if (path.startsWith('/')) {
8
- path = path.substring(1);
4
+ const JITAR_SOURCE_ID = 'jitar';
5
+ const JITAR_CLIENT_ID = 'jitar/client';
6
+ const JITAR_BUNDLE_ID = 'jitar-bundle';
7
+ function formatDir(dir) {
8
+ dir = normalizePath(dir);
9
+ if (dir.startsWith('/')) {
10
+ dir = dir.substring(1);
9
11
  }
10
- if (path.endsWith('/')) {
11
- path = path.substring(0, path.length - 1);
12
+ if (dir.endsWith('/')) {
13
+ dir = dir.substring(0, dir.length - 1);
12
14
  }
13
- return path;
15
+ return dir;
14
16
  }
15
- function createServerConfig(jitarUrl) {
16
- return {
17
- build: {
18
- target: 'esnext'
19
- },
20
- server: {
21
- proxy: {
22
- '/rpc': jitarUrl,
23
- '/jitar': jitarUrl,
24
- '/modules': jitarUrl,
25
- }
26
- }
27
- };
28
- }
29
- function createBootstrapCode(segments, middlewares) {
30
- const segmentString = segments.map(segment => `'${segment}'`).join(', ');
31
- const middlewareString = middlewares.map(middleware => `'${middleware}'`).join(', ');
32
- return `<script type="module">const jitar = await import("/jitar/client.js"); await jitar.startClient(document.location.origin, [${segmentString}], [${middlewareString}]);</script>`;
33
- }
34
- async function createImportCode(code, id, jitarFullPath, jitarPath) {
35
- const relativeId = id
36
- .replace(jitarFullPath, '')
37
- .replace('.ts', '.js');
38
- const module = reflector.parse(code);
39
- const exported = module.exported;
40
- const allKeys = [...exported.keys()];
41
- const functionKeys = allKeys.filter(key => key !== 'default' && exported.get(key) instanceof ReflectionFunction);
42
- let importCode = '';
43
- let exportCode = '';
44
- if (exported.has('default')) {
45
- importCode += `const defaultExport = module.default;\n`;
46
- exportCode += `export default defaultExport;\n`;
17
+ function assureExtension(filename) {
18
+ if (filename.endsWith('.js')) {
19
+ return filename;
47
20
  }
48
- if (functionKeys.length > 0) {
49
- importCode += functionKeys.map(key => `const ${key} = module.${key};`).join('\n');
50
- exportCode += `export { ${functionKeys.join(', ')} };\n`;
51
- }
52
- return 'import { getClient } from "/jitar/client.js";\n'
53
- + `const module = await (await getClient()).import("./${jitarPath}${relativeId}");\n`
54
- + importCode
55
- + exportCode;
21
+ return `${filename}.js`;
22
+ }
23
+ function makeShared(filename) {
24
+ return assureExtension(filename).replace('.js', '.shared.js');
56
25
  }
57
- export default function viteJitar(sourcePath, jitarPath, jitarUrl, segments = [], middlewares = []) {
58
- sourcePath = formatPath(sourcePath);
59
- jitarPath = formatPath(jitarPath);
60
- let jitarFullPath = undefined;
26
+ export default function viteJitar(pluginConfig) {
27
+ const sourceDir = formatDir(pluginConfig.sourceDir);
28
+ const targetDir = formatDir(pluginConfig.targetDir);
29
+ const jitarDir = formatDir(pluginConfig.jitarDir);
30
+ const jitarUrl = pluginConfig.jitarUrl;
31
+ const segments = pluginConfig.segments ?? [];
32
+ const middlewares = pluginConfig.middleware ?? [];
33
+ const scopes = ['shared', ...segments, 'remote'];
34
+ let rootPath;
35
+ let sourcePath;
36
+ let targetPath;
37
+ let outputPath;
38
+ let jitarPath;
39
+ let jitarBundleFilename;
40
+ let jitarBundleImported = false;
61
41
  return {
62
42
  name: 'jitar-plugin-vite',
63
- enforce: 'post',
64
43
  config() {
65
- return createServerConfig(jitarUrl);
44
+ return {
45
+ build: { target: 'esnext' },
46
+ server: { proxy: { '/rpc': jitarUrl } }
47
+ };
66
48
  },
67
49
  configResolved(resolvedConfig) {
68
- jitarFullPath = path.join(resolvedConfig.root, sourcePath, jitarPath);
50
+ rootPath = path.join(resolvedConfig.root);
51
+ sourcePath = path.join(rootPath, sourceDir);
52
+ targetPath = path.join(rootPath, targetDir);
53
+ outputPath = path.join(targetPath, resolvedConfig.build.assetsDir);
54
+ jitarPath = path.join(sourcePath, jitarDir);
69
55
  },
70
- resolveId(source) {
71
- if (source === '/jitar/client.js') {
72
- return { id: source, external: 'absolute' };
56
+ options(options) {
57
+ if (options.input === undefined) {
58
+ options.input = JITAR_BUNDLE_ID;
59
+ }
60
+ else if (typeof options.input === 'string') {
61
+ options.input = [options.input, JITAR_BUNDLE_ID];
62
+ }
63
+ else if (Array.isArray(options.input)) {
64
+ options.input.push(JITAR_BUNDLE_ID);
65
+ }
66
+ else if (typeof options.input === 'object') {
67
+ options.input.additionalEntry = JITAR_BUNDLE_ID;
68
+ }
69
+ return options;
70
+ },
71
+ resolveId: {
72
+ order: 'pre',
73
+ async handler(source, importer, options) {
74
+ if (source === JITAR_BUNDLE_ID) {
75
+ return source;
76
+ }
77
+ if (source === JITAR_SOURCE_ID) {
78
+ if (importer?.endsWith('.segment.js') === false) {
79
+ jitarBundleImported = true;
80
+ }
81
+ return JITAR_BUNDLE_ID;
82
+ }
83
+ const resolution = await this.resolve(source, importer, options);
84
+ if (resolution === null || jitarPath === undefined || resolution.id.includes(jitarPath) === false) {
85
+ return null;
86
+ }
87
+ const cacheId = resolution.id.replace(`/${sourceDir}/`, `/${targetDir}/`);
88
+ for (const scope of scopes) {
89
+ const scopeId = cacheId.replace('.ts', `.${scope}.js`);
90
+ if (fs.existsSync(scopeId)) {
91
+ return scopeId;
92
+ }
93
+ }
94
+ return resolution.id;
73
95
  }
74
- return null;
75
96
  },
76
- async transform(code, id) {
77
- if (jitarFullPath === undefined || id.includes(jitarFullPath) === false) {
78
- return code;
97
+ load(id) {
98
+ if (id !== JITAR_BUNDLE_ID) {
99
+ return null;
100
+ }
101
+ const segmentFiles = segments.map(name => `${targetPath}/${name}.segment.js`);
102
+ const middlewareFiles = middlewares.map(name => makeShared(`${targetPath}/${name}`));
103
+ const jitarImport = `import { ClientBuilder, HttpRemoteBuilder } from "${JITAR_CLIENT_ID}";`;
104
+ const segmentImports = segmentFiles.map((filename, index) => `import { default as $S${index} } from "${filename}";`).join('');
105
+ const middlewareImports = middlewareFiles.map((filename, index) => `import { default as $M${index} } from "${filename}";`).join('');
106
+ const imports = [jitarImport, segmentImports, middlewareImports].join('\n');
107
+ const remoteUrl = 'const remoteUrl = document.location.origin;';
108
+ const segmentsItems = segments.map((_, index) => `$S${index}`).join(', ');
109
+ const segmentsArray = `const segments = [${segmentsItems}];`;
110
+ const middlewareItems = middlewares.map((_, index) => `$M${index}`).join(', ');
111
+ const middlewareArray = `const middleware = [${middlewareItems}];`;
112
+ const declarations = [remoteUrl, segmentsArray, middlewareArray].join('\n');
113
+ const remoteBuilder = 'const remoteBuilder = new HttpRemoteBuilder();';
114
+ const clientBuilder = 'const clientBuilder = new ClientBuilder(remoteBuilder);';
115
+ const build = 'clientBuilder.build({remoteUrl, segments, middleware});';
116
+ const client = [remoteBuilder, clientBuilder, build].join('\n');
117
+ const exports = `export * from "${JITAR_CLIENT_ID}";`;
118
+ return [imports, declarations, client, exports].join('\n');
119
+ },
120
+ generateBundle(options, bundle) {
121
+ const bundles = Object.entries(bundle);
122
+ for (const [fileName, chunk] of bundles) {
123
+ if (chunk.type === 'chunk' && chunk.name === JITAR_BUNDLE_ID) {
124
+ jitarBundleFilename = fileName;
125
+ break;
126
+ }
79
127
  }
80
- return createImportCode(code, id, jitarFullPath, jitarPath);
81
128
  },
82
129
  transformIndexHtml(html) {
83
- return html.replace('<head>', `<head>${createBootstrapCode(segments, middlewares)}`);
130
+ if (jitarBundleImported === true) {
131
+ return html;
132
+ }
133
+ if (jitarBundleFilename === undefined) {
134
+ if (outputPath === undefined) {
135
+ console.warn('Output path not found!');
136
+ return html;
137
+ }
138
+ const filenames = fs.readdirSync(outputPath);
139
+ const jitarFilename = filenames.find(fileName => fileName.startsWith(JITAR_BUNDLE_ID) && fileName.endsWith('.js'));
140
+ if (jitarFilename === undefined) {
141
+ console.warn('Jitar bundle not found! Did you build the application first?');
142
+ return html;
143
+ }
144
+ const jitarBundle = fs.readFileSync(path.join(outputPath, jitarFilename), 'utf-8');
145
+ return html.replace('<script', `<script type="module">${jitarBundle}</script>\n <script`);
146
+ }
147
+ return html.replace('<script', `<script type="module" crossorigin src="/${jitarBundleFilename}"></script>\n <script`);
84
148
  }
85
149
  };
86
150
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jitar/plugin-vite",
3
- "version": "0.7.6",
3
+ "version": "0.8.1",
4
4
  "description": "Vite plugin for Jitar.",
5
5
  "author": "Masking Technology <info@masking.tech> (https://jitar.dev)",
6
6
  "license": "MIT",
@@ -26,9 +26,6 @@
26
26
  "publishConfig": {
27
27
  "access": "public"
28
28
  },
29
- "dependencies": {
30
- "@jitar/reflection": "^0.7.6"
31
- },
32
29
  "peerDependencies": {
33
30
  "vite": ">=4.0.0 || >=5.0.0"
34
31
  },
@@ -50,5 +47,5 @@
50
47
  "vite-plugin",
51
48
  "jitar"
52
49
  ],
53
- "gitHead": "0a9289db7787cfafdcc9a198b87cadb8843a3d75"
50
+ "gitHead": "cb82f7e31ef4015e0d569a70f1e990859dc0f870"
54
51
  }