@makano/rew 1.2.87 → 1.2.89

Sign up to get free protection for your applications and to get access to all the features.
@@ -42,6 +42,11 @@ yargs(hideBin(process.argv))
42
42
  describe: 'Watch the file for changes',
43
43
  type: 'boolean',
44
44
  })
45
+ .option('strace', {
46
+ alias: 's',
47
+ describe: 'Log everything',
48
+ type: 'boolean',
49
+ })
45
50
  .option('compile', {
46
51
  alias: 'c',
47
52
  describe: 'Compile and output the javascript',
@@ -49,6 +54,9 @@ yargs(hideBin(process.argv))
49
54
  });
50
55
  },
51
56
  (argv) => {
57
+ if(argv.strace){
58
+ process.straceMode = true;
59
+ }
52
60
  const filePath = path.resolve(process.cwd(), argv.file);
53
61
  if (!existsSync(filePath)) {
54
62
  log('File not found:'.red.bold, argv.file, ':end');
@@ -371,7 +371,7 @@ module.exports = {
371
371
 
372
372
  const appPath = findAppInfo(filePath);
373
373
 
374
- const compiled = argv.translate ? compile({ content }, {}) : to_qrew(`"initFile ${filePath}"\n${path.basename(content)}`, appPath?.config?.manifest?.package || path.basename(filePath).split('.').slice(0, -1).join('.'));
374
+ const compiled = argv.translate ? compile({ content }, {}) : to_qrew(`"initFile ${path.basename(filePath)}"\n${content}`, appPath?.config?.manifest?.package || path.basename(filePath).split('.').slice(0, -1).join('.'));
375
375
  writeCompiledFile(filePath, compiled);
376
376
  }
377
377
 
@@ -4,7 +4,7 @@
4
4
  const JSX_FRAGMENT_SYMBOL = Symbol('fragment');
5
5
  module.exports.USING_DEFAULT = {
6
6
  JSX: {
7
- param: (param, fragment) => ({ createElement: param, Fragment: fragment || param(JSX_FRAGMENT_SYMBOL, { isFragment: true }), fragmentSymbol: JSX_FRAGMENT_SYMBOL }),
7
+ param: (param, fragment) => param ? ({ createElement: param, Fragment: fragment || param(JSX_FRAGMENT_SYMBOL, { isFragment: true }), fragmentSymbol: JSX_FRAGMENT_SYMBOL }) : {},
8
8
  use: (options) => options.jsx = true
9
9
  },
10
10
  TYPES: {
@@ -7,12 +7,14 @@ const conf = require('../pkgs/conf');
7
7
  const jsYaml = require('js-yaml');
8
8
  const { execOptions } = require('../const/opt');
9
9
  const { REW_FILE_TYPE } = require('../const/ext');
10
+ const { straceLog } = require('../misc/strace');
10
11
 
11
12
  const cachedFiles = [];
12
13
  module.exports.cleanCache = () => {
13
14
  while(cachedFiles.length) cachedFiles.pop();
14
15
  };
15
16
  const lookUpInOtherApps = (fullPath) => {
17
+ straceLog('===> WARN: LOOKUP SLOWS PROCESS');
16
18
  const con = conf({});
17
19
  const name = fullPath.indexOf('/') ? fullPath.split('/')[0] : fullPath;
18
20
  let dpath = fullPath.indexOf('/') ? fullPath.split('/')[1] : '';
@@ -39,7 +41,10 @@ module.exports.imp = function (runPath, context) {
39
41
  let exports,
40
42
  ispkg = findPackage(filename);
41
43
 
44
+ straceLog('IMPORT for', filename, 'as', type);
45
+
42
46
  if (filename.startsWith('@') && context.app) {
47
+ straceLog('===> FROM APP ROOT');
43
48
  filename = filename.replace('@', context.app.path);
44
49
  }
45
50
 
@@ -47,6 +52,7 @@ module.exports.imp = function (runPath, context) {
47
52
  if(path.extname(filepath) == '.qrew') options.qrew = true;
48
53
 
49
54
  const lookUp = () => {
55
+ straceLog('===> LOOKUP()');
50
56
  const otherPath = lookUpInOtherApps(filename);
51
57
  if (!otherPath) throw new Error('Module "' + filename + '" not found');
52
58
  else filepath = otherPath;
@@ -64,6 +70,7 @@ module.exports.imp = function (runPath, context) {
64
70
  typeof ext == 'string' ? existsSync(filepath + ext) : existsSync(filepath + (ext.ext || '')),
65
71
  );
66
72
  if (resolve) {
73
+ straceLog('===> RESOLVE()');
67
74
  filepath += typeof resolve == 'string' ? resolve : resolve.ext;
68
75
  if (typeof resolve == 'object' && resolve.options) {
69
76
  if (resolve.options.type) type = resolve.options.type;
@@ -74,6 +81,7 @@ module.exports.imp = function (runPath, context) {
74
81
  }
75
82
 
76
83
  const exec = (coptions = {}) => {
84
+ straceLog('===> EXECUTE() IMPORTFILE');
77
85
  const r = runPath(
78
86
  filepath,
79
87
  {
@@ -95,6 +103,7 @@ module.exports.imp = function (runPath, context) {
95
103
  }
96
104
 
97
105
  if (ispkg) {
106
+ straceLog('===> FIND_PACKAGE()');
98
107
  const pkg = getPackage(filename)(context, options);
99
108
  exports = pkg._onImport ? pkg._onImport() : pkg;
100
109
  if(options.useDefaultForPackages) exports = { default: exports };
@@ -104,16 +113,20 @@ module.exports.imp = function (runPath, context) {
104
113
  } else if (type == 'js') {
105
114
  exports = exec({ compile: false });
106
115
  } else if (type == 'yaml' || type == 'json' || type == 'text') {
116
+ straceLog('===> GET_RAW_FILE()');
107
117
  const f = getFile(filepath);
108
118
  if (type == 'yaml') {
119
+ straceLog('===> FROM_YAML()');
109
120
  exports = importYaml(f.path, f);
110
121
  } else if (type == 'json') {
122
+ straceLog('===>');
111
123
  try {
112
124
  exports = JSON.parse(f.content);
113
125
  } catch (e) {
114
126
  exports = {};
115
127
  }
116
128
  } else {
129
+ straceLog('===> FROM_TEXT');
117
130
  exports = f.content;
118
131
  }
119
132
  }
@@ -28,7 +28,6 @@ module.exports.customRequire = function customRequire(modulePath, filePath, esm)
28
28
  } catch(e){
29
29
  if(e.code === 'ERR_REQUIRE_ESM') {
30
30
  isEsm = true;
31
- console.log('Trying with esm');
32
31
  r = get_file();
33
32
  } else {
34
33
  throw e;
@@ -2,11 +2,15 @@ const jsYaml = require('js-yaml');
2
2
  const { findAppPath } = require('./findAppPath');
3
3
  const path = require('path');
4
4
  const { readFileSync } = require('fs');
5
+ const { straceLog } = require('./strace');
5
6
 
6
7
  module.exports.findAppInfo = function (filepath) {
7
8
  const appPath = findAppPath(path.dirname(filepath));
9
+ straceLog('FINDAPPINFO() for', filepath);
8
10
  if (appPath) {
9
11
  const config = jsYaml.load(readFileSync(path.join(appPath, 'app.yaml')));
12
+ straceLog('==> FOUND CONFIG AT', appPath);
13
+ straceLog('==> APP PACKAGE', config?.manifest?.package);
10
14
  return {
11
15
  path: appPath,
12
16
  config,
@@ -1,10 +1,14 @@
1
1
  const path = require('path'); // Import the 'path' module
2
2
  const fs = require('fs'); // Import the 'path' module
3
+ const { straceLog } = require('./strace');
3
4
 
4
5
  module.exports.findAppPath = (currentDir = __dirname) => {
5
6
  // Check if app.yaml exists in the current directory
7
+ straceLog('FINDAPP() for', currentDir);
6
8
  const appYamlPath = path.join(currentDir, 'app.yaml');
7
9
  if (fs.existsSync(appYamlPath)) {
10
+
11
+ straceLog('==> FOUND PATH', appYamlPath);
8
12
  return currentDir;
9
13
  }
10
14
 
@@ -0,0 +1,5 @@
1
+ module.exports.straceLog = function(...logs){
2
+ if(process.straceMode){
3
+ console.log(`[${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} ${new Date().getDate()}/${new Date().getMonth()}/${new Date().getFullYear()}] [${process.pid}]`, ...logs);
4
+ }
5
+ }
@@ -10,6 +10,8 @@ const { readFileSync, existsSync } = require('fs');
10
10
  const { wait } = require('../functions/wait');
11
11
  const { REW_FILE_TYPE } = require('../const/ext');
12
12
  const { USING_DEFAULT } = require('../const/usage');
13
+ const { CONFIG_PATH } = require('../const/config_path');
14
+ const { straceLog } = require('../misc/strace');
13
15
 
14
16
 
15
17
 
@@ -74,7 +76,7 @@ function tokenizeCoffeeScript(code) {
74
76
  } else {
75
77
  tokens.push({ type: 'WHITESPACE', value: char });
76
78
  }
77
- } else if (/[a-zA-Z_$]/.test(char)) {
79
+ } else if (/[a-zA-Z_$@]/.test(char)) {
78
80
  // Identifier
79
81
  let identifier = char;
80
82
  i++;
@@ -105,7 +107,7 @@ const ValueIfy = (val) => {
105
107
  }
106
108
 
107
109
  const gnextToken = (i, n, tokens) => {
108
- return tokens[i + n] ? (tokens[i + n].type == 'WHITESPACE' ? gnextToken(i, n + 1, tokens) : { token: tokens[i + n], n }) : null;
110
+ return tokens[i + n] ? (tokens[i + n].type == 'WHITESPACE' ? gnextToken(i, n + 1, tokens) : { token: tokens[i + n], n, ti: i + n }) : null;
109
111
  };
110
112
 
111
113
  const fnextToken = (i, tokens, type, value) => {
@@ -126,28 +128,135 @@ const fnextToken = (i, tokens, type, value) => {
126
128
  function declareAlias(aliases, token) {
127
129
  const regex = /^#declare(\*)?\s+(\w+)\s+"([^"]+)"\s*=\s*([\s\S]*);$/;
128
130
  const match = token.value.trim().match(regex);
131
+ straceLog('DECLARECASE()');
132
+ straceLog('==> EXPERIMENTAL FEATURE DETECTED');
129
133
 
130
134
  if (match) {
131
135
  const isPublic = !!match[1];
132
136
  const type = match[2] == "key" ? 'IDENTIFIER' : match[2];
133
- const name = match[3];
134
- const value = match[4].trim();
137
+ let name = match[3];
138
+ let value = match[4].trim();
139
+ straceLog('==> DECLARE', name, 'as', value);
135
140
 
136
- const aliasValue = value.startsWith('${')
137
- ? new Function('token', 'tokens', 'code', value.slice(2, -1))
141
+ let aliasValue = value.startsWith('${')
142
+ ? new Function('token', 'tokens', 'code', 'hooks', value.slice(2, -1))
138
143
  : value;
144
+
145
+
146
+ if(name.startsWith('=')){
147
+ name = name.slice(1);
148
+ let isDecOnly = false;
149
+ if(name.endsWith('*')) {
150
+ name = name.slice(0, -1);
151
+ isDecOnly = true;
152
+ }
153
+ aliasValue = (token, tokens, code, hooks, index, setIndex) => {
154
+ const nextToken = tokens[index+1]
155
+ let nextToken2 = gnextToken(index, 3, tokens);
156
+ if (nextToken.value == '(' || tokens[index+2]?.value == '(') {
157
+ let params = '';
158
+ index += 2;
159
+ let openBrackets = 1;
160
+ while (index < tokens.length && openBrackets > 0) {
161
+ const char = tokens[index].value;
162
+ if (char === '(') openBrackets++;
163
+ if (char === ')') openBrackets--;
164
+ if (openBrackets > 0) params += char;
165
+ index++;
166
+ }
167
+ const { token: nextToken2, n: n2, ti } = gnextToken(index, 1, tokens) || {};
168
+ let offset = 1;
169
+ if(tokens[ti+1].type == 'WHITESPACE') offset += 2;
170
+ if(tokens[ti+3].type == 'WHITESPACE') offset += 1;
171
+
172
+ let nextToken = gnextToken(index, offset+1, tokens);
173
+ const args = nextToken.token.value;
174
+ setIndex(ti + offset);
175
+ return `${nextToken2.value} = ${token.value}(${args}, ${params.trim()})`;
176
+ } else if(nextToken?.value == ' ' && (isDecOnly || nextToken2?.token.value == '=' || nextToken2?.token.value == ':')){
177
+ nextToken.value = '';
178
+ if(isDecOnly){
179
+ nextToken2 = {
180
+ token: { value: ':' },
181
+ ti: index+2
182
+ }
183
+ value = '= ' + value + '()';
184
+ }
185
+ if(nextToken2.token.value == ':') nextToken2.token.value = '=';
186
+ hooks.push({
187
+ index: nextToken2.ti,
188
+ value: ' ' + value
189
+ })
190
+ return "";
191
+ }
192
+ return token.value;
193
+ }
194
+ }
139
195
 
140
196
  aliases[type] = aliases[type] || {};
141
197
  aliases[type][name] = aliasValue;
142
198
 
143
199
  if(isPublic){
200
+ straceLog('==>', 'DECLARATION GLOBALIZED');
144
201
  execOptions._syntaxAliases[type] = execOptions._syntaxAliases[type] || {};
145
202
  execOptions._syntaxAliases[type][name] = aliasValue;
146
203
  }
147
204
  }
148
205
  }
149
206
 
207
+
208
+ const includeFile = (includeContent, options) => {
209
+ straceLog('INCLUDE()', includeContent);
210
+ const dontInclude = includeContent.startsWith('*');
211
+ if(dontInclude) {
212
+ includeContent = includeContent.slice(1);
213
+ straceLog('==> IGNORING OUTPUT', includeContent);
214
+ };
215
+ let filename = options.filename ? path.resolve(path.dirname(options.filename), includeContent) : includeContent;
216
+ const _inc = (filename) => '\n'+ compileRewStuff(readFileSync(filename).toString(), {
217
+ ...options,
218
+ filename,
219
+ included: true
220
+ })+'\n';
221
+ let r = '';
222
+ if (existsSync(filename)) {
223
+ straceLog('==> INCLUDE FILE', filename);
224
+ r = _inc(filename);
225
+ } else {
226
+ const packageName = includeContent.match('/') ? includeContent.split('/')[0] : includeContent;
227
+ const headerFile = includeContent.match('/') ? includeContent.replace(packageName+'/', '') : 'main.h.coffee';
228
+ const pathname = path.join(CONFIG_PATH, packageName, 'app', headerFile);
229
+ straceLog('==> INCLUDE PACKAGE', filename);
230
+ if(existsSync(pathname)) r = _inc(pathname);
231
+ }
232
+ if(!dontInclude){
233
+ return r;
234
+ }
235
+ return "";
236
+ }
237
+
238
+ function useImp(token, options){
239
+ if(token.type == 'STRING' && (
240
+ token.value.startsWith('"#') ||
241
+ token.value.startsWith("'#")
242
+ )){
243
+ straceLog('==> IMP Uses HEADER');
244
+ const dem = token.value.slice(0, 1);
245
+ const value = token.value.slice(1, -1);
246
+ let packageName = value.slice(1);
247
+ token.value = dem+packageName+dem;
248
+ const file = packageName.startsWith('./') || packageName.startsWith('../');
249
+ if(!(file) && packageName.match('/')) packageName = packageName.split('/').pop();
250
+ if(file) packageName = path.extname(packageName) ? packageName.replace(path.extname(packageName), '.h.coffee') : packageName;
251
+ if(file && !packageName.endsWith('.h.coffee')) packageName += '.h.coffee';
252
+ straceLog('IMP() with HEADER for', packageName);
253
+ return includeFile(packageName, options);
254
+ }
255
+ return '';
256
+ }
257
+
150
258
  function compileRewStuff(content, options) {
259
+ straceLog('TOKENIZE() for CURRENTFILE');
151
260
  const tokens = tokenizeCoffeeScript(content);
152
261
  let result = '';
153
262
  let multilineDeclareBuffer = [];
@@ -156,7 +265,7 @@ function compileRewStuff(content, options) {
156
265
  let hooks = [];
157
266
 
158
267
 
159
- const aliases = {
268
+ let aliases = {
160
269
  ...execOptions._syntaxAliases
161
270
  }
162
271
 
@@ -199,16 +308,42 @@ function compileRewStuff(content, options) {
199
308
  execOptions.jsxPragma = nextLastToken.value.slice(1).slice(0, -1);
200
309
  }
201
310
  }
311
+
312
+ if (token.type === 'IDENTIFIER' && token.value === 'imp') {
313
+ straceLog('IMP() Detected');
314
+ let { token: t1 } = gnextToken(i, 1, tokens) || {};
315
+ let { token: t2 } = gnextToken(i, 2, tokens) || {};
316
+ let r = '';
317
+
318
+ if(t1.value == '('){
319
+ if(t2.type == 'STRING'){
320
+ r = useImp(t2, options);
321
+ }
322
+ } else if(t1.type == 'STRING'){
323
+ r = useImp(t1, options);
324
+ }
325
+
326
+ if(r) {
327
+ aliases = {
328
+ ...aliases,
329
+ ...execOptions._syntaxAliases
330
+ }
331
+ }
332
+ }
202
333
 
203
334
  if (token.type === 'COMMENT' && token.value.slice(1).trim().startsWith('@jsx')) {
204
335
  options.jsx = true;
336
+ straceLog('JSX() ENABLE WITH COMMENTS');
205
337
  if(token.value.split('@jsx')[1].trim()){
206
338
  options.jsxPragma = token.value.split('@jsx')[1].trim();
339
+ straceLog('JSX() PRAGMA WITH', options.jsxPragma);
207
340
  }
208
341
  }
209
342
 
210
343
  if (token.type === 'COMMENT' && token.value.slice(1).trim() === '@cls') {
211
344
  options.cls = true;
345
+ straceLog('CLITOKENIZATION() ENABLE');
346
+ straceLog('===> HIGHLY EXPERIMENTAL FEATURE DETECTED');
212
347
  }
213
348
 
214
349
  if (options.cls && token.type === 'OTHER' && token.value === '-' && nextToken.value == '-' && tokens[i-1]?.type == 'WHITESPACE') {
@@ -228,26 +363,32 @@ function compileRewStuff(content, options) {
228
363
 
229
364
  if (token.type === 'IDENTIFIER' && token.value === 'export' && !options.keepImports) {
230
365
  token.value = 'pub';
366
+ straceLog('EXPORT() => TRANSLATING TO pub');
231
367
  }
232
368
 
233
369
  if (token.type === 'IDENTIFIER' && token.value === 'using' && !options.disableUse) {
370
+ straceLog('USING()');
234
371
  const next = nextToken.value;
235
372
  if(next in USING_DEFAULT) {
236
373
  const { use } = USING_DEFAULT[next];
237
374
  use?.(options);
375
+ straceLog('==>', nextToken.value);
238
376
  nextToken.value = `"${nextToken.value}"`
239
377
 
240
378
  const { token: nextNextToken } = gnextToken(i, 3, tokens) || {};
241
379
  if(nextNextToken.value == "as") nextNextToken.value = ",";
242
- }
380
+ } else straceLog('==> UNKNOWN');
243
381
  }
244
382
 
245
383
  if (token.type === 'IDENTIFIER' && token.value === 'import' && !options.keepImports) {
246
384
  // console.log(nextToken.type);
385
+ straceLog('IMPORT()');
386
+ straceLog('==> WARN: SLOWS DOWN TOKENIZATION');
247
387
  let ind = i + n + 2;
248
388
 
249
389
  let defaultName;
250
390
  if (nextToken.type === 'STRING') {
391
+ straceLog('==> SIMPLE');
251
392
  result += `inc ${nextToken.value}`;
252
393
  i += n;
253
394
  } else if (nextToken.value === '{') {
@@ -261,6 +402,8 @@ function compileRewStuff(content, options) {
261
402
  .flat(1)
262
403
  .filter((t, i, arr) => !arr[i+1]?.match(':') && !arr[i-1]?.match(':'))
263
404
  .join(', ');
405
+
406
+ straceLog('==>', exports, 'from', nameToken.value);
264
407
 
265
408
  result += `{ ${exports} } ${options.type == 'coffee' ? '=' : ':='} inc ${nameToken.value}`;
266
409
  i = nameToken.ti;
@@ -271,6 +414,7 @@ function compileRewStuff(content, options) {
271
414
  if (asToken) {
272
415
  const nextToken = fnextToken(asToken.ti + 1, tokens, 'IDENTIFIER');
273
416
  defaultName = nextToken.value;
417
+ straceLog('==>', defaultName, 'from', nameToken.value);
274
418
  result += `${defaultName} ${options.type == 'coffee' ? '=' : ':='} inc ${nameToken.value}`;
275
419
  i = ind + 6;
276
420
  }
@@ -288,6 +432,7 @@ function compileRewStuff(content, options) {
288
432
  .flat(1)
289
433
  .filter((t, i, arr) => !arr[i+1]?.match(':') && !arr[i-1]?.match(':'))
290
434
  .join(', ');
435
+ straceLog('==>', defaultName, 'and', exports, 'from', nameToken.value);
291
436
  result += `{ default: ${defaultName}, ${exports} } ${options.type == 'coffee' ? '=' : ':='} inc ${nameToken?.value || ''}`;
292
437
  i = closingBraceToken.ti + 4;
293
438
  }
@@ -302,6 +447,7 @@ function compileRewStuff(content, options) {
302
447
  if (nextLastToken?.value == 'assert') {
303
448
  result += ', ';
304
449
  const assertionToken = gnextToken(nextLastToken.ti, 2, tokens);
450
+ straceLog('==> ASSERT', assertionToken);
305
451
  if(assertionToken.token.type == 'OTHER' && assertionToken.token.value == '{'){
306
452
  hooks.push({
307
453
  index: assertionToken.token.ti,
@@ -326,6 +472,7 @@ function compileRewStuff(content, options) {
326
472
  nextToken.value &&
327
473
  nextToken.value !== 'undefined' && !options.keepImports
328
474
  ) {
475
+ straceLog('PUB() Detected');
329
476
  let next = {...nextToken}, isClass = false;
330
477
  if(next.value == 'default'){
331
478
  i += 2;
@@ -334,6 +481,7 @@ function compileRewStuff(content, options) {
334
481
  next.value = gnextToken(i, n + 1, tokens)?.token.value || "default";
335
482
  isClass = true;
336
483
  }
484
+ straceLog('==> PUBLIC', next.value);
337
485
  hooks.push({
338
486
  index: i + 1,
339
487
  value: `"${next.value}", ${isClass ? `${next.value} = ` : ''}`,
@@ -341,20 +489,20 @@ function compileRewStuff(content, options) {
341
489
  }
342
490
 
343
491
  const aliasType = aliases[token.type];
344
- if (aliasType && aliasType[token.value]) {
492
+ // if(token.value == 'sidewest') console.log(aliases, token.value, token.type);
493
+ if (aliasType && Object.keys(aliasType).includes(token.value)) {
494
+ straceLog('ALIAS()', token.type);
345
495
  const aliasValue = aliasType[token.value];
346
496
  if (typeof aliasValue === 'function') {
347
- result += aliasValue(token, tokens, result) || "";
497
+ straceLog('==> EXECUTE ALIAS', token.value);
498
+ result += aliasValue(token, tokens, result, hooks, i, (n) => i = n) || "";
348
499
  } else {
500
+ straceLog('==> LITERAL ALIAS', token.value);
349
501
  result += aliasValue;
350
502
  }
351
503
  continue;
352
504
  }
353
505
 
354
- // if(token.type === 'TRIPLE_STRING'){
355
- // token.value = '```'+token.value.slice(3).slice(0, -3).replace(/\#\{/g, '${')+'```';
356
- // }
357
-
358
506
  // process.stdout.write(token.value);
359
507
  result += token.value;
360
508
  if (hooks.length) {
@@ -367,29 +515,33 @@ function compileRewStuff(content, options) {
367
515
  }
368
516
 
369
517
  if (token.type === "COMMENT" && token.value.startsWith('#include')) {
370
- const includeContent = token.value.split(' ')[1] || '';
371
- const filename = options.filename ? path.resolve(path.dirname(options.filename), includeContent) : includeContent;
372
- if (existsSync(filename)) {
373
- result += '\n'+ compileRewStuff(readFileSync(filename).toString(), {
374
- ...options,
375
- filename
376
- });
377
- }
518
+ const includeContent = token.value.split(' ')[1].trim() || '';
519
+ const r = includeFile(includeContent, options);
520
+ if(r){
521
+ result += r;
522
+ aliases = {
523
+ ...aliases,
524
+ ...execOptions._syntaxAliases
525
+ }
526
+ }
378
527
  }
379
528
  }
380
-
529
+ // console.log(aliases);
381
530
  // console.log(result);
382
-
383
531
  return result;
384
532
  }
385
533
 
386
534
  const compileCivetStuff = (file, options) => {
535
+ straceLog('COMPILE_CIVET() for CURRENTFILE');
387
536
  const preCompileOptions = {
388
537
  filename: file.path,
389
538
  ...options
390
539
  };
540
+ straceLog('OPTION_PREPARE() for CURRENTFILE as', preCompileOptions);
391
541
  const prepared = compileRewStuff(file.content, preCompileOptions);
392
542
 
543
+ // console.log(prepared);
544
+
393
545
  const compileOptions = {
394
546
  ...preCompileOptions,
395
547
  bare: true,
@@ -399,6 +551,7 @@ const compileCivetStuff = (file, options) => {
399
551
  };
400
552
 
401
553
  let compiled = options.async ? compileCivet(prepared, compileOptions) : wait(compileCivet, prepared, compileOptions);
554
+ straceLog('==> CIVET COMPILE <>');
402
555
 
403
556
  return {
404
557
  compiled,
@@ -418,14 +571,21 @@ const cpl = (module.exports.compile = function (file, options = {}) {
418
571
  options = result.options;
419
572
  compiledCode = result.compiled;
420
573
 
421
- const babelify = (code, options) => babel.transformSync(code, {
422
- presets: [
423
- ...(doJSX ? [[babelReact, { throwIfNamespace: false, pragmaFrag: options.jsxPragmaFrag || execOptions.jsxPragmaFrag, pragma: options.jsxPragma || execOptions.jsxPragma }]] : [])
424
- ],
425
- plugins: [
426
- ...(doDecorators ? [[require('@babel/plugin-proposal-decorators'), { version: '2023-05' }], [require('@babel/plugin-proposal-class-properties'), { loose: true }], [require('@babel/plugin-transform-class-static-block'), {}]] : [])
427
- ],
428
- }).code;
574
+ const babelify = (code, options) => {
575
+ straceLog('BABEL()');
576
+ if(doJSX) straceLog('==> WITH JSX');
577
+ if(doTypes) straceLog('==> WITH TYPES');
578
+ if(doDecorators) straceLog('==> WITH DECORATORS');
579
+ return babel.transformSync(code, {
580
+ presets: [
581
+ ...(doJSX ? [[babelReact, { throwIfNamespace: false, pragmaFrag: options.jsxPragmaFrag || execOptions.jsxPragmaFrag, pragma: options.jsxPragma || execOptions.jsxPragma }]] : [])
582
+ ],
583
+ plugins: [
584
+ ...(doDecorators ? [[require('@babel/plugin-proposal-decorators'), { version: '2023-05' }], [require('@babel/plugin-proposal-class-properties'), { loose: true }], [require('@babel/plugin-transform-class-static-block'), {}]] : []),
585
+ // doJSX ? require('./jsx') : null
586
+ ].filter(Boolean),
587
+ }).code;
588
+ }
429
589
 
430
590
  const doJSX = execOptions.jsx || options.jsx;
431
591
  const doTypes = execOptions.typescript || options.typescript;
@@ -449,6 +609,7 @@ const cpl = (module.exports.compile = function (file, options = {}) {
449
609
  });
450
610
 
451
611
  module.exports.compileFile = function (filepath, options = {}) {
612
+ straceLog('COMPILE() for CURRENTFILE');
452
613
  const f = typeof filepath == "object" ? filepath : getFile(filepath);
453
614
  if(typeof filepath == "object") filepath = filepath.path;
454
615
  let qrew = false;
@@ -457,11 +618,13 @@ module.exports.compileFile = function (filepath, options = {}) {
457
618
  qrew = true
458
619
  f.content = from_qrew(readFileSync(f.path), options.package || findAppInfo(filepath)?.config.manifest.package || path.basename(filepath).split('.').slice(0, -1).join('.')).toString();
459
620
  options.type = f.content.split('\n')[0]?.match(/"initFile (.+)"/)?.[1]?.split('.').pop();
621
+ straceLog('QREW_DECODE() as', options.type, 'for CURRENTFILE');
460
622
  }
461
623
 
462
624
  let compiled_code = cpl(f, { ...options });
463
625
 
464
626
  if(options.onlyCompile && !qrew){
627
+ straceLog('WRITE_AND_QUIT() for COMPILEDATA');
465
628
  if(compiled_code instanceof Promise){
466
629
  compiled_code.then((r) => {
467
630
  console.log(r);
@@ -11,6 +11,7 @@ const { findAppInfo } = require("../misc/findAppInfo");
11
11
  const { USING_DEFAULT, Usage, Namespace } = require("../const/usage");
12
12
  const runtime = require("./runtime");
13
13
  const { permission } = require("process");
14
+ const { straceLog } = require("../misc/strace");
14
15
 
15
16
  let mainFile = "";
16
17
  const isMainFile = (filepath) => filepath == mainFile;
@@ -20,6 +21,7 @@ module.exports.prepareContext = function (
20
21
  filepath = "",
21
22
  runPath = () => {},
22
23
  ) {
24
+ straceLog('PREPARE() NEW CONTEXT');
23
25
  if (mainFile == "") mainFile = filepath;
24
26
  /** @type {Record<string, any>} */
25
27
  let context = {
@@ -97,16 +99,20 @@ module.exports.prepareContext = function (
97
99
  throw new Error("");
98
100
  return context.imp(package, asserts);
99
101
  } catch (e) {
100
- let pname = package.startsWith("pkg:") ? package.split("pkg:")[1] : package;
101
- if(pname.endsWith('#esm')){
102
- pname = pname.slice(0, -4);
103
- if(!asserts) asserts = { esm: true };
104
- else asserts.esm = true;
102
+ if(e.message.match('Module') && e.message.match('not found')){
103
+ let pname = package.startsWith("pkg:") ? package.split("pkg:")[1] : package;
104
+ if(pname.endsWith('#esm')){
105
+ pname = pname.slice(0, -4);
106
+ if(!asserts) asserts = { esm: true };
107
+ else asserts.esm = true;
108
+ }
109
+ return context.require(
110
+ pname,
111
+ asserts?.esm
112
+ );
113
+ } else {
114
+ throw e;
105
115
  }
106
- return context.require(
107
- pname,
108
- asserts?.esm
109
- );
110
116
  }
111
117
  };
112
118
  context.pub = pubFunction(context);
@@ -144,12 +150,14 @@ module.exports.prepareContext = function (
144
150
  if(context.app?.config?.exec?.['auto import']){
145
151
  const autoipath = path.join(context.app.path, context.app.config?.exec?.['auto import']);
146
152
  if(autoipath !== filepath){
153
+ straceLog('==> AUTOIMPORT()', autoipath);
147
154
  const all = context.imp(path.relative(path.dirname(filepath), autoipath));
148
155
  for(let i in all) context[i] = all[i];
149
156
  }
150
157
  }
151
158
 
152
159
  if(!context.app){
160
+ straceLog('==> APP NOT FOUND');
153
161
  context.appPackage = (packageName) => context.app = { config: { manifest: { package: packageName } } }
154
162
  }
155
163
 
@@ -163,6 +171,7 @@ module.exports.prepareContext = function (
163
171
  context.module.main ||
164
172
  (options.fromMain == true && options.as == "main")
165
173
  ) {
174
+ straceLog('==> RUNTIME() as MAIN for', filepath);
166
175
  context.opt = {
167
176
  set: (key, value) => (execOptions[key] = value),
168
177
  get: (key) => execOptions[key],
@@ -0,0 +1,67 @@
1
+ // customJSXIdentifierPlugin.js
2
+ module.exports = function customJSXIdentifierPlugin({ types: t }) {
3
+ return {
4
+ visitor: {
5
+ FunctionDeclaration(path) {
6
+ if (containsJSXReturn(path.node.body.body, t)) {
7
+ addJSXReturnFlag(path, path.node.id.name, t);
8
+ }
9
+ },
10
+ FunctionExpression(path) {
11
+ if (containsJSXReturn(path.node.body.body, t)) {
12
+ handleFunctionExpressionOrArrow(path, t);
13
+ }
14
+ },
15
+ ArrowFunctionExpression(path) {
16
+ if (t.isJSXElement(path.node.body) || (t.isBlockStatement(path.node.body) && containsJSXReturn(path.node.body.body, t))) {
17
+ handleFunctionExpressionOrArrow(path, t);
18
+ }
19
+ },
20
+ }
21
+ };
22
+ };
23
+
24
+ function containsJSXReturn(body, t) {
25
+ return body.some(statement => t.isReturnStatement(statement) && t.isJSXElement(statement.argument));
26
+ }
27
+
28
+ function addJSXReturnFlag(path, functionName, t) {
29
+ path.insertAfter(
30
+ t.expressionStatement(
31
+ t.assignmentExpression(
32
+ '=',
33
+ t.memberExpression(t.identifier(functionName), t.identifier('__returnsJSX')),
34
+ t.booleanLiteral(true)
35
+ )
36
+ )
37
+ );
38
+ }
39
+
40
+ function handleFunctionExpressionOrArrow(path, t) {
41
+ // Check for variable declaration
42
+ if (t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id)) {
43
+ const functionName = path.parent.id.name;
44
+ path.findParent(p => p.isVariableDeclaration()).insertAfter(
45
+ t.expressionStatement(
46
+ t.assignmentExpression(
47
+ '=',
48
+ t.memberExpression(t.identifier(functionName), t.identifier('__returnsJSX')),
49
+ t.booleanLiteral(true)
50
+ )
51
+ )
52
+ );
53
+ }
54
+ // Check for variable assignment
55
+ else if (t.isAssignmentExpression(path.parent) && t.isIdentifier(path.parent.left)) {
56
+ const functionName = path.parent.left.name;
57
+ path.parentPath.insertAfter(
58
+ t.expressionStatement(
59
+ t.assignmentExpression(
60
+ '=',
61
+ t.memberExpression(t.identifier(functionName), t.identifier('__returnsJSX')),
62
+ t.booleanLiteral(true)
63
+ )
64
+ )
65
+ );
66
+ }
67
+ }
@@ -4,6 +4,7 @@ const { prepareContext } = require('./context');
4
4
  const { existsSync, readFileSync } = require('fs');
5
5
  const { CONFIG_PATH } = require('../const/config_path');
6
6
  const path = require('path');
7
+ const { straceLog } = require('../misc/strace');
7
8
 
8
9
  const preScript = readFileSync(path.join(__dirname, '../const/pre-exec.js'), { encoding: 'utf-8' });
9
10
 
@@ -20,12 +21,17 @@ module.exports.runPath = function runPath(filepath, options = {}, custom_context
20
21
  if(filepath.endsWith('.coffee')) options.type = 'coffee';
21
22
  if(filepath.endsWith('.qrew')) options.type = 'qrew';
22
23
 
24
+ straceLog('RUN() CURRENTFILE = ', filepath, 'as', options.type || 'UNKNOWN');
25
+
23
26
  if(options.import?.async) options.async = true;
27
+ if(options.async) straceLog('ASYNCMODE() for CURRENTFILE');
24
28
  let { compiled_code, file } = compileFile(options.code ? { content: options.code, path: filepath } : filepath, options);
29
+ straceLog('COMPILE_DONE() with COMPILEDATA');
25
30
  // context.module.compiled = compiled_code;
26
31
  // context.process.exit = (int) => process.exit(int);
27
32
 
28
33
  const doCode = () => {
34
+ straceLog('RUNCODE() COMPILEDATA');
29
35
  const context = options.import?.takeThisContext ? custom_context : prepareContext(custom_context, options, file.path, runPath);
30
36
 
31
37
  if(context.app){
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makano/rew",
3
- "version": "1.2.87",
3
+ "version": "1.2.89",
4
4
  "description": "A simple coffescript runtime and app manager",
5
5
  "main": "main.js",
6
6
  "directories": {