@windwalker-io/core 4.2.4 → 4.2.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.
@@ -1,300 +1,300 @@
1
- import {
2
- type BuildTask,
3
- type ConfigBuilder,
4
- js,
5
- type MaybePromise,
6
- plugin as addPlugin,
7
- type ProcessorInterface,
8
- type ProcessorPreview,
9
- shortHash,
10
- } from '@windwalker-io/fusion-next';
11
- import fs from 'fs-extra';
12
- import { parse } from 'node-html-parser';
13
- import crypto from 'node:crypto';
14
- import { normalize, resolve } from 'node:path';
15
- import { type FindFileResult, findFilesFromGlobArray, findModules, findPackages, stripUrlQuery } from '../../utilities';
16
-
17
- export interface JsModulizeOptions {
18
- tmpPath?: string;
19
- cleanTmp?: boolean;
20
- }
21
-
22
- export function jsModulize(entry: string, dest: string, options: JsModulizeOptions = {}) {
23
- return new JsModulizeProcessor(js(entry, dest), options);
24
- }
25
-
26
- export interface JsModulizeDeepOptions extends JsModulizeOptions {
27
- mergeScripts?: boolean;
28
- parseBlades?: boolean;
29
- }
30
-
31
- export function jsModulizeDeep(stage: string, entry: string, dest: string, options: JsModulizeDeepOptions = {}) {
32
- const processor = jsModulize(entry, dest, options)
33
- .stage(stage.toLowerCase());
34
-
35
- if (options.mergeScripts ?? true) {
36
- processor.mergeScripts(
37
- findModules(`${stage}/**/assets/*.ts`),
38
- );
39
- }
40
-
41
- if (options.parseBlades ?? true) {
42
- processor.parseBlades(
43
- findModules(`${stage}/**/*.blade.php`),
44
- findPackages('views/**/*.blade.php'),
45
- );
46
- }
47
-
48
- return processor;
49
- }
50
-
51
- export class JsModulizeProcessor implements ProcessorInterface {
52
- protected scriptPatterns: string[] = [];
53
- protected bladePatterns: string[] = [];
54
- protected stagePrefix: string = '';
55
-
56
- constructor(protected processor: ReturnType<typeof js>, protected options: JsModulizeOptions = {}) {
57
- }
58
-
59
- config(taskName: string, builder: ConfigBuilder) {
60
- const tasks = this.processor.config(taskName, builder) as BuildTask[];
61
- const task = tasks[0];
62
- const inputFile = resolve(task.input);
63
- const tmpPath = this.options.tmpPath ?? resolve('./tmp/fusion/jsmodules/').replace(/\\/g, '/');
64
- const clean = this.options.cleanTmp ?? true;
65
-
66
- if (clean) {
67
- builder.postBuildCallbacks.push((options, bundle) => {
68
- fs.removeSync(tmpPath);
69
- });
70
- builder.serverStopCallbacks.push((options, bundle) => {
71
- fs.removeSync(tmpPath);
72
- });
73
- }
74
-
75
- this.ignoreMainImport(task);
76
-
77
- builder.resolveIdCallbacks.push((id) => {
78
- if (id === '@main') {
79
- return { id, external: true };
80
- }
81
- });
82
-
83
- // Todo: Must dynamic changes in load() hook
84
- const scriptFiles = findFilesFromGlobArray(this.scriptPatterns);
85
- const bladeFiles = findBladeFiles(this.bladePatterns);
86
-
87
- // Watches
88
- // Currently we don't watch blade files because not necessary to reload full-pages.
89
- // for (const bladeFile of bladeScripts) {
90
- // builder.watches.push({
91
- // file: resolve(bladeFile.file.fullpath),
92
- // moduleFile: inputFile,
93
- // updateType: 'js-update',
94
- // } satisfies WatchTask);
95
- // }
96
-
97
- builder.loadCallbacks.push((src, options) => {
98
- const srcFile = stripUrlQuery(src);
99
- const scripts: Record<string, string> = {};
100
-
101
- // if (src === appSrcFileName) {
102
- if (normalize(srcFile) === inputFile) {
103
- const bladeScripts = parseScriptsFromBlades(bladeFiles);
104
-
105
- // Merge standalone ts files
106
- for (const scriptFile of scriptFiles) {
107
- let fullpath = scriptFile.fullpath;
108
-
109
- if (fullpath.endsWith('.d.ts')) {
110
- continue;
111
- }
112
-
113
- let key = scriptFile.relativePath.replace(/assets\//, '').toLowerCase();
114
- fullpath = resolve(fullpath).replace(/\\/g, '/');
115
-
116
- key = key.substring(0, key.lastIndexOf('.'));
117
-
118
- if (this.stagePrefix) {
119
- key = this.stagePrefix + '/' + key;
120
- }
121
-
122
- // md5
123
- key = 'view:' + crypto.createHash('md5').update(key).digest('hex');
124
-
125
- scripts[key] = fullpath;
126
- }
127
-
128
- // Parse from blades
129
- const listens: string[] = [];
130
-
131
- fs.ensureDirSync(tmpPath);
132
-
133
- for (const result of bladeScripts) {
134
- let key = result.as;
135
- const filename = result.path
136
- .split(/\\|\//g)
137
- .pop()
138
- .replace(/\\|\//g, '_');
139
-
140
- const tmpFile = tmpPath + '/' + filename + '__' + result.as.replace(/\./g, '-') + '.ts';
141
-
142
- if (!fs.existsSync(tmpFile) || fs.readFileSync(tmpFile, 'utf8') !== result.code) {
143
- fs.writeFileSync(tmpFile, result.code);
144
- }
145
-
146
- scripts[`inline:${key}`] = tmpFile;
147
-
148
- const fullpath = resolve(result.file.fullpath).replace(/\\/g, '/');
149
-
150
- if (!listens.includes(fullpath)) {
151
- listens.push(fullpath);
152
- }
153
- }
154
-
155
- let listJS = `{\n`;
156
-
157
- for (const key in scripts) {
158
- const fullpath = scripts[key];
159
- listJS += `'${key}': () => import('${fullpath}'),\n`;
160
- }
161
-
162
- listJS += `}`;
163
-
164
- // Listen extra files
165
- builder.watches.push(...listens);
166
-
167
- let { code, comments } = stripComments(fs.readFileSync(srcFile, 'utf-8'));
168
-
169
- // Replace `defineJsModules(...)`
170
- code = code.replace(/defineJsModules\((.*?)\)/g, listJS);
171
-
172
- return restoreComments(code, comments);
173
- }
174
- });
175
-
176
- return undefined;
177
- }
178
-
179
- /**
180
- * @see https://github.com/vitejs/vite/issues/6393#issuecomment-1006819717
181
- * @see https://stackoverflow.com/questions/76259677/vite-dev-server-throws-error-when-resolving-external-path-from-importmap
182
- */
183
- private ignoreMainImport(task: BuildTask) {
184
- const VALID_ID_PREFIX = `/@id/`;
185
- const importKeys = ['@main'];
186
- const reg = new RegExp(
187
- `${VALID_ID_PREFIX}(${importKeys.join("|")})`,
188
- "g"
189
- );
190
-
191
- addPlugin({
192
- name: 'keep-main-external-' + task.id,
193
- transform(code) {
194
- return reg.test(code) ? code.replace(reg, (m, s1) => s1) : code;
195
- }
196
- });
197
- }
198
-
199
- preview(): MaybePromise<ProcessorPreview[]> {
200
- return [];
201
- }
202
-
203
- mergeScripts(...patterns: (string | string[])[]) {
204
- this.scriptPatterns = this.scriptPatterns.concat(patterns.flat());
205
-
206
- return this;
207
- }
208
-
209
- parseBlades(...bladePatterns: (string[] | string)[]) {
210
- this.bladePatterns = this.bladePatterns.concat(bladePatterns.flat());
211
-
212
- return this;
213
- }
214
-
215
- stage(stage: string) {
216
- this.stagePrefix = stage;
217
-
218
- return this;
219
- }
220
- }
221
-
222
- interface ScriptResult {
223
- as: string;
224
- file: FindFileResult;
225
- path: string;
226
- code: string;
227
- }
228
-
229
- // function parseScriptsFromBlade(file: string, service: Record<string, ParsedModule>): string[] {
230
- // const bladeText = fs.readFileSync(file, 'utf8');
231
- //
232
- // const html = parse(bladeText);
233
- //
234
- // return html.querySelectorAll('script[lang]')
235
- // .filter(
236
- // (el) => ['ts', 'typescript'].includes(el.getAttribute('lang') || '')
237
- // )
238
- // .map((el) => el.innerHTML)
239
- // .filter((c) => c.trim() !== '');
240
- // }
241
-
242
- function findBladeFiles(patterns: string | string[]) {
243
- return findFilesFromGlobArray(Array.isArray(patterns) ? patterns : [patterns]);
244
- }
245
-
246
- function parseScriptsFromBlades(files: FindFileResult[]): ScriptResult[] {
247
- return files.map((file) => {
248
- const bladeText = fs.readFileSync(file.fullpath, 'utf8');
249
-
250
- const html = parse(bladeText);
251
- // const key = file.relativePath.replace(/.blade.php$/, '').toLowerCase();
252
-
253
- return html.querySelectorAll('script[lang][data-macro]')
254
- .filter(
255
- (el) => ['ts', 'typescript'].includes(el.getAttribute('lang') || '')
256
- )
257
- .map((el) => ({
258
- as: el.getAttribute('data-macro') || '',
259
- file: file,
260
- path: file.relativePath.replace(/.blade.php$/, ''),
261
- code: el.innerHTML
262
- }))
263
- .filter((c) => c.code.trim() !== '');
264
- })
265
- .flat();
266
- }
267
-
268
- type CommentPlaceholder = { key: string; value: string; };
269
-
270
- function stripComments(code: string): { code: string; comments: CommentPlaceholder[] } {
271
- const comments: CommentPlaceholder[] = [];
272
- let i = 0;
273
-
274
- code = code
275
- // Multi-line /* */
276
- .replace(/\/\*[\s\S]*?\*\//g, match => {
277
- const key = `__COMMENT_BLOCK_${i}__`;
278
- comments.push({ key, value: match });
279
- i++;
280
- return key;
281
- })
282
- // Single-line //
283
- .replace(/\/\/.*$/gm, match => {
284
- const key = `__COMMENT_LINE_${i}__`;
285
- comments.push({ key, value: match });
286
- i++;
287
- return key;
288
- });
289
-
290
- return { code, comments };
291
- }
292
-
293
- function restoreComments(code: string, comments: CommentPlaceholder[]): string {
294
- for (const { key, value } of comments) {
295
- const re = new RegExp(key, 'g');
296
- code = code.replace(re, value);
297
- }
298
-
299
- return code;
300
- }
1
+ import {
2
+ type BuildTask,
3
+ type ConfigBuilder,
4
+ js,
5
+ type MaybePromise,
6
+ plugin as addPlugin,
7
+ type ProcessorInterface,
8
+ type ProcessorPreview,
9
+ shortHash,
10
+ } from '@windwalker-io/fusion-next';
11
+ import fs from 'fs-extra';
12
+ import { parse } from 'node-html-parser';
13
+ import crypto from 'node:crypto';
14
+ import { normalize, resolve } from 'node:path';
15
+ import { type FindFileResult, findFilesFromGlobArray, findModules, findPackages, stripUrlQuery } from '../../utilities';
16
+
17
+ export interface JsModulizeOptions {
18
+ tmpPath?: string;
19
+ cleanTmp?: boolean;
20
+ }
21
+
22
+ export function jsModulize(entry: string, dest: string, options: JsModulizeOptions = {}) {
23
+ return new JsModulizeProcessor(js(entry, dest), options);
24
+ }
25
+
26
+ export interface JsModulizeDeepOptions extends JsModulizeOptions {
27
+ mergeScripts?: boolean;
28
+ parseBlades?: boolean;
29
+ }
30
+
31
+ export function jsModulizeDeep(stage: string, entry: string, dest: string, options: JsModulizeDeepOptions = {}) {
32
+ const processor = jsModulize(entry, dest, options)
33
+ .stage(stage.toLowerCase());
34
+
35
+ if (options.mergeScripts ?? true) {
36
+ processor.mergeScripts(
37
+ findModules(`${stage}/**/assets/*.ts`),
38
+ );
39
+ }
40
+
41
+ if (options.parseBlades ?? true) {
42
+ processor.parseBlades(
43
+ findModules(`${stage}/**/*.blade.php`),
44
+ findPackages('views/**/*.blade.php'),
45
+ );
46
+ }
47
+
48
+ return processor;
49
+ }
50
+
51
+ export class JsModulizeProcessor implements ProcessorInterface {
52
+ protected scriptPatterns: string[] = [];
53
+ protected bladePatterns: string[] = [];
54
+ protected stagePrefix: string = '';
55
+
56
+ constructor(protected processor: ReturnType<typeof js>, protected options: JsModulizeOptions = {}) {
57
+ }
58
+
59
+ config(taskName: string, builder: ConfigBuilder) {
60
+ const tasks = this.processor.config(taskName, builder) as BuildTask[];
61
+ const task = tasks[0];
62
+ const inputFile = resolve(task.input);
63
+ const tmpPath = this.options.tmpPath ?? resolve('./tmp/fusion/jsmodules/').replace(/\\/g, '/');
64
+ const clean = this.options.cleanTmp ?? true;
65
+
66
+ if (clean) {
67
+ builder.postBuildCallbacks.push((options, bundle) => {
68
+ fs.removeSync(tmpPath);
69
+ });
70
+ builder.serverStopCallbacks.push((options, bundle) => {
71
+ fs.removeSync(tmpPath);
72
+ });
73
+ }
74
+
75
+ this.ignoreMainImport(task);
76
+
77
+ builder.resolveIdCallbacks.push((id) => {
78
+ if (id === '@main') {
79
+ return { id, external: true };
80
+ }
81
+ });
82
+
83
+ // Todo: Must dynamic changes in load() hook
84
+ const scriptFiles = findFilesFromGlobArray(this.scriptPatterns);
85
+ const bladeFiles = findBladeFiles(this.bladePatterns);
86
+
87
+ // Watches
88
+ // Currently we don't watch blade files because not necessary to reload full-pages.
89
+ // for (const bladeFile of bladeScripts) {
90
+ // builder.watches.push({
91
+ // file: resolve(bladeFile.file.fullpath),
92
+ // moduleFile: inputFile,
93
+ // updateType: 'js-update',
94
+ // } satisfies WatchTask);
95
+ // }
96
+
97
+ builder.loadCallbacks.push((src, options) => {
98
+ const srcFile = stripUrlQuery(src);
99
+ const scripts: Record<string, string> = {};
100
+
101
+ // if (src === appSrcFileName) {
102
+ if (normalize(srcFile) === inputFile) {
103
+ const bladeScripts = parseScriptsFromBlades(bladeFiles);
104
+
105
+ // Merge standalone ts files
106
+ for (const scriptFile of scriptFiles) {
107
+ let fullpath = scriptFile.fullpath;
108
+
109
+ if (fullpath.endsWith('.d.ts')) {
110
+ continue;
111
+ }
112
+
113
+ let key = scriptFile.relativePath.replace(/assets\//, '').toLowerCase();
114
+ fullpath = resolve(fullpath).replace(/\\/g, '/');
115
+
116
+ key = key.substring(0, key.lastIndexOf('.'));
117
+
118
+ if (this.stagePrefix) {
119
+ key = this.stagePrefix + '/' + key;
120
+ }
121
+
122
+ // md5
123
+ key = 'view:' + crypto.createHash('md5').update(key).digest('hex');
124
+
125
+ scripts[key] = fullpath;
126
+ }
127
+
128
+ // Parse from blades
129
+ const listens: string[] = [];
130
+
131
+ fs.ensureDirSync(tmpPath);
132
+
133
+ for (const result of bladeScripts) {
134
+ let key = result.as;
135
+ const filename = result.path
136
+ .split(/\\|\//g)
137
+ .pop()
138
+ .replace(/\\|\//g, '_');
139
+
140
+ const tmpFile = tmpPath + '/' + filename + '__' + result.as.replace(/\./g, '-') + '.ts';
141
+
142
+ if (!fs.existsSync(tmpFile) || fs.readFileSync(tmpFile, 'utf8') !== result.code) {
143
+ fs.writeFileSync(tmpFile, result.code);
144
+ }
145
+
146
+ scripts[`inline:${key}`] = tmpFile;
147
+
148
+ const fullpath = resolve(result.file.fullpath).replace(/\\/g, '/');
149
+
150
+ if (!listens.includes(fullpath)) {
151
+ listens.push(fullpath);
152
+ }
153
+ }
154
+
155
+ let listJS = `{\n`;
156
+
157
+ for (const key in scripts) {
158
+ const fullpath = scripts[key];
159
+ listJS += `'${key}': () => import('${fullpath}'),\n`;
160
+ }
161
+
162
+ listJS += `}`;
163
+
164
+ // Listen extra files
165
+ builder.watches.push(...listens);
166
+
167
+ let { code, comments } = stripComments(fs.readFileSync(srcFile, 'utf-8'));
168
+
169
+ // Replace `defineJsModules(...)`
170
+ code = code.replace(/defineJsModules\((.*?)\)/g, listJS);
171
+
172
+ return restoreComments(code, comments);
173
+ }
174
+ });
175
+
176
+ return undefined;
177
+ }
178
+
179
+ /**
180
+ * @see https://github.com/vitejs/vite/issues/6393#issuecomment-1006819717
181
+ * @see https://stackoverflow.com/questions/76259677/vite-dev-server-throws-error-when-resolving-external-path-from-importmap
182
+ */
183
+ private ignoreMainImport(task: BuildTask) {
184
+ const VALID_ID_PREFIX = `/@id/`;
185
+ const importKeys = ['@main'];
186
+ const reg = new RegExp(
187
+ `${VALID_ID_PREFIX}(${importKeys.join("|")})`,
188
+ "g"
189
+ );
190
+
191
+ addPlugin({
192
+ name: 'keep-main-external-' + task.id,
193
+ transform(code) {
194
+ return reg.test(code) ? code.replace(reg, (m, s1) => s1) : code;
195
+ }
196
+ });
197
+ }
198
+
199
+ preview(): MaybePromise<ProcessorPreview[]> {
200
+ return [];
201
+ }
202
+
203
+ mergeScripts(...patterns: (string | string[])[]) {
204
+ this.scriptPatterns = this.scriptPatterns.concat(patterns.flat());
205
+
206
+ return this;
207
+ }
208
+
209
+ parseBlades(...bladePatterns: (string[] | string)[]) {
210
+ this.bladePatterns = this.bladePatterns.concat(bladePatterns.flat());
211
+
212
+ return this;
213
+ }
214
+
215
+ stage(stage: string) {
216
+ this.stagePrefix = stage;
217
+
218
+ return this;
219
+ }
220
+ }
221
+
222
+ interface ScriptResult {
223
+ as: string;
224
+ file: FindFileResult;
225
+ path: string;
226
+ code: string;
227
+ }
228
+
229
+ // function parseScriptsFromBlade(file: string, service: Record<string, ParsedModule>): string[] {
230
+ // const bladeText = fs.readFileSync(file, 'utf8');
231
+ //
232
+ // const html = parse(bladeText);
233
+ //
234
+ // return html.querySelectorAll('script[lang]')
235
+ // .filter(
236
+ // (el) => ['ts', 'typescript'].includes(el.getAttribute('lang') || '')
237
+ // )
238
+ // .map((el) => el.innerHTML)
239
+ // .filter((c) => c.trim() !== '');
240
+ // }
241
+
242
+ function findBladeFiles(patterns: string | string[]) {
243
+ return findFilesFromGlobArray(Array.isArray(patterns) ? patterns : [patterns]);
244
+ }
245
+
246
+ function parseScriptsFromBlades(files: FindFileResult[]): ScriptResult[] {
247
+ return files.map((file) => {
248
+ const bladeText = fs.readFileSync(file.fullpath, 'utf8');
249
+
250
+ const html = parse(bladeText);
251
+ // const key = file.relativePath.replace(/.blade.php$/, '').toLowerCase();
252
+
253
+ return html.querySelectorAll('script[lang][data-macro]')
254
+ .filter(
255
+ (el) => ['ts', 'typescript'].includes(el.getAttribute('lang') || '')
256
+ )
257
+ .map((el) => ({
258
+ as: el.getAttribute('data-macro') || '',
259
+ file: file,
260
+ path: file.relativePath.replace(/.blade.php$/, ''),
261
+ code: el.innerHTML
262
+ }))
263
+ .filter((c) => c.code.trim() !== '');
264
+ })
265
+ .flat();
266
+ }
267
+
268
+ type CommentPlaceholder = { key: string; value: string; };
269
+
270
+ function stripComments(code: string): { code: string; comments: CommentPlaceholder[] } {
271
+ const comments: CommentPlaceholder[] = [];
272
+ let i = 0;
273
+
274
+ code = code
275
+ // Multi-line /* */
276
+ .replace(/\/\*[\s\S]*?\*\//g, match => {
277
+ const key = `__COMMENT_BLOCK_${i}__`;
278
+ comments.push({ key, value: match });
279
+ i++;
280
+ return key;
281
+ })
282
+ // Single-line //
283
+ .replace(/\/\/.*$/gm, match => {
284
+ const key = `__COMMENT_LINE_${i}__`;
285
+ comments.push({ key, value: match });
286
+ i++;
287
+ return key;
288
+ });
289
+
290
+ return { code, comments };
291
+ }
292
+
293
+ function restoreComments(code: string, comments: CommentPlaceholder[]): string {
294
+ for (const { key, value } of comments) {
295
+ const re = new RegExp(key, 'g');
296
+ code = code.replace(re, value);
297
+ }
298
+
299
+ return code;
300
+ }
package/src/next/index.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './fusion';
2
- export * from './utilities';
1
+ export * from './fusion';
2
+ export * from './utilities';