trickle-observe 0.2.25 → 0.2.27
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/observe-register.js +84 -7
- package/observe-esm-hooks.mjs +237 -5
- package/observe-esm.mjs +1 -0
- package/package.json +1 -1
- package/src/observe-register.ts +84 -7
package/dist/observe-register.js
CHANGED
|
@@ -166,11 +166,11 @@ function findClosingBrace(source, openBrace) {
|
|
|
166
166
|
* Handles: const x = ...; let x = ...; var x = ...;
|
|
167
167
|
* Skips: destructuring, for-loop vars, require() calls, imports.
|
|
168
168
|
*/
|
|
169
|
-
function findVarDeclarations(source) {
|
|
169
|
+
function findVarDeclarations(source, lineOffset = 0) {
|
|
170
170
|
const varInsertions = [];
|
|
171
|
-
// Match: const/let/var <identifier> = <something>
|
|
172
|
-
//
|
|
173
|
-
const varRegex = /^([ \t]*)(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)
|
|
171
|
+
// Match: const/let/var <identifier>[: TypeAnnotation] = <something>
|
|
172
|
+
// Handles both JS (no annotation) and TS (with annotation like `: string` or `: MyType`)
|
|
173
|
+
const varRegex = /^([ \t]*)(?:export\s+)?(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)(?:\s*:[^=]+?)?\s*=[^=]/gm;
|
|
174
174
|
let vmatch;
|
|
175
175
|
while ((vmatch = varRegex.exec(source)) !== null) {
|
|
176
176
|
const varName = vmatch[3];
|
|
@@ -186,11 +186,13 @@ function findVarDeclarations(source) {
|
|
|
186
186
|
if (/^\s*require\s*\(/.test(restOfLine))
|
|
187
187
|
continue;
|
|
188
188
|
// Calculate line number (count newlines before this position)
|
|
189
|
+
// Subtract lineOffset to map compiled line numbers back to original source lines
|
|
189
190
|
let lineNo = 1;
|
|
190
191
|
for (let i = 0; i < vmatch.index; i++) {
|
|
191
192
|
if (source[i] === '\n')
|
|
192
193
|
lineNo++;
|
|
193
194
|
}
|
|
195
|
+
lineNo = Math.max(1, lineNo - lineOffset);
|
|
194
196
|
// Find the end of this statement — look for the semicolon at depth 0
|
|
195
197
|
// or the end of the line for semicolon-free code
|
|
196
198
|
const startPos = vmatch.index + vmatch[0].length - 1; // position of the '='
|
|
@@ -257,7 +259,7 @@ function findVarDeclarations(source) {
|
|
|
257
259
|
/**
|
|
258
260
|
* Find destructured variable declarations: const { a, b } = ... and const [a, b] = ...
|
|
259
261
|
*/
|
|
260
|
-
function findDestructuredDeclarations(source) {
|
|
262
|
+
function findDestructuredDeclarations(source, lineOffset = 0) {
|
|
261
263
|
const results = [];
|
|
262
264
|
const destructRegex = /^[ \t]*(?:export\s+)?(?:const|let|var)\s+(\{[^}]*\}|\[[^\]]*\])\s*(?::\s*[^=]+?)?\s*=[^=]/gm;
|
|
263
265
|
let match;
|
|
@@ -274,6 +276,7 @@ function findDestructuredDeclarations(source) {
|
|
|
274
276
|
if (source[i] === '\n')
|
|
275
277
|
lineNo++;
|
|
276
278
|
}
|
|
279
|
+
lineNo = Math.max(1, lineNo - lineOffset);
|
|
277
280
|
const startPos = match.index + match[0].length - 1;
|
|
278
281
|
let pos = startPos;
|
|
279
282
|
let depth = 0;
|
|
@@ -417,8 +420,82 @@ function transformCjsSource(source, filename, moduleName, env) {
|
|
|
417
420
|
}
|
|
418
421
|
// Also find variable declarations for tracing
|
|
419
422
|
const varTraceEnabled = process.env.TRICKLE_TRACE_VARS !== '0';
|
|
420
|
-
|
|
421
|
-
|
|
423
|
+
// For TypeScript files (compiled by ts-node/tsc), type declarations (interfaces, type aliases)
|
|
424
|
+
// are stripped from the compiled JS, shifting line numbers. The only accurate way to get correct
|
|
425
|
+
// line numbers is to read the original .ts source file and parse it directly.
|
|
426
|
+
// For plain JS files, we parse the source directly.
|
|
427
|
+
let varInsertions = [];
|
|
428
|
+
let destructInsertions = [];
|
|
429
|
+
if (varTraceEnabled) {
|
|
430
|
+
const isTsFile = /\.[mc]?tsx?$/.test(filename);
|
|
431
|
+
if (isTsFile) {
|
|
432
|
+
try {
|
|
433
|
+
// Read original TypeScript source to get correct line numbers
|
|
434
|
+
const fs = require('fs');
|
|
435
|
+
const originalSource = fs.readFileSync(filename, 'utf8');
|
|
436
|
+
const tsVarInsertions = findVarDeclarations(originalSource);
|
|
437
|
+
const tsDestructInsertions = findDestructuredDeclarations(originalSource);
|
|
438
|
+
// Map TypeScript variable names → correct line numbers (by occurrence order)
|
|
439
|
+
// Use a counter map to handle duplicate variable names in different scopes
|
|
440
|
+
const tsLineByVarAndOccurrence = new Map();
|
|
441
|
+
for (const { varName, lineNo } of tsVarInsertions) {
|
|
442
|
+
if (!tsLineByVarAndOccurrence.has(varName))
|
|
443
|
+
tsLineByVarAndOccurrence.set(varName, []);
|
|
444
|
+
tsLineByVarAndOccurrence.get(varName).push(lineNo);
|
|
445
|
+
}
|
|
446
|
+
// Find positions in compiled JS (for inserting trace calls),
|
|
447
|
+
// but use line numbers from original TypeScript source
|
|
448
|
+
const compiledInsertions = findVarDeclarations(source);
|
|
449
|
+
const varOccurrenceCounter = new Map();
|
|
450
|
+
for (const ins of compiledInsertions) {
|
|
451
|
+
const occCount = (varOccurrenceCounter.get(ins.varName) || 0);
|
|
452
|
+
varOccurrenceCounter.set(ins.varName, occCount + 1);
|
|
453
|
+
const tsLines = tsLineByVarAndOccurrence.get(ins.varName);
|
|
454
|
+
const correctLineNo = tsLines ? (tsLines[occCount] ?? tsLines[tsLines.length - 1]) : undefined;
|
|
455
|
+
varInsertions.push({ ...ins, lineNo: correctLineNo ?? ins.lineNo });
|
|
456
|
+
}
|
|
457
|
+
const compiledDestructInsertions = findDestructuredDeclarations(source);
|
|
458
|
+
destructInsertions = compiledDestructInsertions; // Keep compiled line numbers as fallback
|
|
459
|
+
// Try to fix destructured line numbers too
|
|
460
|
+
const tsDestructByKey = new Map();
|
|
461
|
+
for (const { varNames, lineNo } of tsDestructInsertions) {
|
|
462
|
+
const key = varNames.join(',');
|
|
463
|
+
if (!tsDestructByKey.has(key))
|
|
464
|
+
tsDestructByKey.set(key, []);
|
|
465
|
+
tsDestructByKey.get(key).push(lineNo);
|
|
466
|
+
}
|
|
467
|
+
const destructOccCounter = new Map();
|
|
468
|
+
destructInsertions = compiledDestructInsertions.map(ins => {
|
|
469
|
+
const key = ins.varNames.join(',');
|
|
470
|
+
const occ = destructOccCounter.get(key) || 0;
|
|
471
|
+
destructOccCounter.set(key, occ + 1);
|
|
472
|
+
const tsLines = tsDestructByKey.get(key);
|
|
473
|
+
const correctLineNo = tsLines ? (tsLines[occ] ?? tsLines[tsLines.length - 1]) : undefined;
|
|
474
|
+
return { ...ins, lineNo: correctLineNo ?? ins.lineNo };
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
// Fallback: use compiled line numbers with prologue offset
|
|
479
|
+
let lineOffset = 0;
|
|
480
|
+
const lines = source.split('\n');
|
|
481
|
+
for (const line of lines) {
|
|
482
|
+
const trimmed = line.trim();
|
|
483
|
+
if (trimmed === '"use strict";' || trimmed === "'use strict';" || trimmed === '') {
|
|
484
|
+
lineOffset++;
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
varInsertions = findVarDeclarations(source, lineOffset);
|
|
491
|
+
destructInsertions = findDestructuredDeclarations(source, lineOffset);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
varInsertions = findVarDeclarations(source);
|
|
496
|
+
destructInsertions = findDestructuredDeclarations(source);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
422
499
|
if (insertions.length === 0 && varInsertions.length === 0 && destructInsertions.length === 0)
|
|
423
500
|
return source;
|
|
424
501
|
// Resolve the path to the wrap helper (compiled JS)
|
package/observe-esm-hooks.mjs
CHANGED
|
@@ -17,6 +17,7 @@ let config = {
|
|
|
17
17
|
wrapperPath: '',
|
|
18
18
|
transportPath: '',
|
|
19
19
|
envDetectPath: '',
|
|
20
|
+
traceVarPath: '',
|
|
20
21
|
backendUrl: 'http://localhost:4888',
|
|
21
22
|
debug: false,
|
|
22
23
|
includePatterns: [],
|
|
@@ -171,14 +172,234 @@ function lineOffset(source, lineIdx) {
|
|
|
171
172
|
return off;
|
|
172
173
|
}
|
|
173
174
|
|
|
175
|
+
/**
|
|
176
|
+
* Find variable declarations in ESM source for tracing.
|
|
177
|
+
* Returns {varName, lineNo, insertAfterLine} for each declaration.
|
|
178
|
+
* insertAfterLine = the line number AFTER the full statement ends (for multi-line).
|
|
179
|
+
*/
|
|
180
|
+
function findVarDeclarationsESM(source) {
|
|
181
|
+
const results = [];
|
|
182
|
+
// Match const/let/var <name>[: Type] = <value>
|
|
183
|
+
// Also handles export const <name>[: Type] = <value>
|
|
184
|
+
const varRegex = /^([ \t]*)(?:export\s+)?(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)(?:\s*:[^=]+?)?\s*=[^=]/gm;
|
|
185
|
+
let match;
|
|
186
|
+
|
|
187
|
+
while ((match = varRegex.exec(source)) !== null) {
|
|
188
|
+
const varName = match[3];
|
|
189
|
+
// Skip trickle-injected vars and transpiler-generated vars (start with __ or single _)
|
|
190
|
+
if (varName.startsWith('__') || varName === '_a' || varName === '_b') continue;
|
|
191
|
+
|
|
192
|
+
// Skip require() calls
|
|
193
|
+
const restOfLine = source.slice(match.index + match[0].length - 1, match.index + match[0].length + 200);
|
|
194
|
+
if (/^\s*require\s*\(/.test(restOfLine)) continue;
|
|
195
|
+
|
|
196
|
+
// Calculate line number where the declaration starts
|
|
197
|
+
let lineNo = 1;
|
|
198
|
+
for (let i = 0; i < match.index; i++) {
|
|
199
|
+
if (source[i] === '\n') lineNo++;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Find the end of the statement (semicolon at depth 0 or significant newline)
|
|
203
|
+
const startPos = match.index + match[0].length - 1;
|
|
204
|
+
let pos = startPos;
|
|
205
|
+
let depth = 0;
|
|
206
|
+
let foundEnd = -1;
|
|
207
|
+
|
|
208
|
+
while (pos < source.length) {
|
|
209
|
+
const ch = source[pos];
|
|
210
|
+
if (ch === '(' || ch === '[' || ch === '{') depth++;
|
|
211
|
+
else if (ch === ')' || ch === ']' || ch === '}') {
|
|
212
|
+
depth--;
|
|
213
|
+
if (depth < 0) break;
|
|
214
|
+
} else if (ch === ';' && depth === 0) {
|
|
215
|
+
foundEnd = pos;
|
|
216
|
+
break;
|
|
217
|
+
} else if (ch === '\n' && depth === 0) {
|
|
218
|
+
const nextNonWs = source.slice(pos + 1).match(/^\s*(\S)/);
|
|
219
|
+
if (nextNonWs && !'.+=-|&?:,'.includes(nextNonWs[1])) {
|
|
220
|
+
foundEnd = pos;
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
} else if (ch === '"' || ch === "'" || ch === '`') {
|
|
224
|
+
const quote = ch; pos++;
|
|
225
|
+
while (pos < source.length) {
|
|
226
|
+
if (source[pos] === '\\') pos++;
|
|
227
|
+
else if (source[pos] === quote) break;
|
|
228
|
+
pos++;
|
|
229
|
+
}
|
|
230
|
+
} else if (ch === '/' && pos + 1 < source.length && source[pos + 1] === '/') {
|
|
231
|
+
while (pos < source.length && source[pos] !== '\n') pos++;
|
|
232
|
+
continue;
|
|
233
|
+
} else if (ch === '/' && pos + 1 < source.length && source[pos + 1] === '*') {
|
|
234
|
+
pos += 2;
|
|
235
|
+
while (pos < source.length - 1 && !(source[pos] === '*' && source[pos + 1] === '/')) pos++;
|
|
236
|
+
pos++;
|
|
237
|
+
}
|
|
238
|
+
pos++;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (foundEnd === -1) continue;
|
|
242
|
+
|
|
243
|
+
// Calculate line number after the statement end
|
|
244
|
+
let insertAfterLine = 1;
|
|
245
|
+
for (let i = 0; i <= foundEnd && i < source.length; i++) {
|
|
246
|
+
if (source[i] === '\n') insertAfterLine++;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
results.push({ varName, lineNo, insertAfterLine });
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return results;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Find destructured variable declarations in ESM source.
|
|
257
|
+
*/
|
|
258
|
+
function findDestructuredDeclarationsESM(source) {
|
|
259
|
+
const results = [];
|
|
260
|
+
const destructRegex = /^[ \t]*(?:export\s+)?(?:const|let|var)\s+(\{[^}]*\}|\[[^\]]*\])\s*(?::\s*[^=]+?)?\s*=[^=]/gm;
|
|
261
|
+
let match;
|
|
262
|
+
|
|
263
|
+
while ((match = destructRegex.exec(source)) !== null) {
|
|
264
|
+
const pattern = match[1];
|
|
265
|
+
const varNames = extractDestructuredNamesESM(pattern).filter(n => !n.startsWith('__'));
|
|
266
|
+
if (varNames.length === 0) continue;
|
|
267
|
+
|
|
268
|
+
let lineNo = 1;
|
|
269
|
+
for (let i = 0; i < match.index; i++) {
|
|
270
|
+
if (source[i] === '\n') lineNo++;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const startPos = match.index + match[0].length - 1;
|
|
274
|
+
let pos = startPos;
|
|
275
|
+
let depth = 0;
|
|
276
|
+
let foundEnd = -1;
|
|
277
|
+
|
|
278
|
+
while (pos < source.length) {
|
|
279
|
+
const ch = source[pos];
|
|
280
|
+
if (ch === '(' || ch === '[' || ch === '{') depth++;
|
|
281
|
+
else if (ch === ')' || ch === ']' || ch === '}') {
|
|
282
|
+
depth--;
|
|
283
|
+
if (depth < 0) break;
|
|
284
|
+
} else if (ch === ';' && depth === 0) {
|
|
285
|
+
foundEnd = pos;
|
|
286
|
+
break;
|
|
287
|
+
} else if (ch === '\n' && depth === 0) {
|
|
288
|
+
const nextNonWs = source.slice(pos + 1).match(/^\s*(\S)/);
|
|
289
|
+
if (nextNonWs && !'.+=-|&?:,'.includes(nextNonWs[1])) {
|
|
290
|
+
foundEnd = pos;
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
} else if (ch === '"' || ch === "'" || ch === '`') {
|
|
294
|
+
const quote = ch; pos++;
|
|
295
|
+
while (pos < source.length) {
|
|
296
|
+
if (source[pos] === '\\') pos++;
|
|
297
|
+
else if (source[pos] === quote) break;
|
|
298
|
+
pos++;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
pos++;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (foundEnd === -1) continue;
|
|
305
|
+
|
|
306
|
+
let insertAfterLine = 1;
|
|
307
|
+
for (let i = 0; i <= foundEnd && i < source.length; i++) {
|
|
308
|
+
if (source[i] === '\n') insertAfterLine++;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
results.push({ varNames, lineNo, insertAfterLine });
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return results;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function extractDestructuredNamesESM(pattern) {
|
|
318
|
+
const names = [];
|
|
319
|
+
const inner = pattern.slice(1, -1).trim();
|
|
320
|
+
if (!inner) return names;
|
|
321
|
+
|
|
322
|
+
const parts = [];
|
|
323
|
+
let depth = 0, current = '';
|
|
324
|
+
for (const ch of inner) {
|
|
325
|
+
if (ch === '{' || ch === '[') depth++;
|
|
326
|
+
else if (ch === '}' || ch === ']') depth--;
|
|
327
|
+
else if (ch === ',' && depth === 0) { parts.push(current.trim()); current = ''; continue; }
|
|
328
|
+
current += ch;
|
|
329
|
+
}
|
|
330
|
+
if (current.trim()) parts.push(current.trim());
|
|
331
|
+
|
|
332
|
+
for (const part of parts) {
|
|
333
|
+
if (part.startsWith('...')) {
|
|
334
|
+
const n = part.slice(3).trim().split(/[\s:]/)[0];
|
|
335
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)) names.push(n);
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
const colonIdx = part.indexOf(':');
|
|
339
|
+
if (colonIdx !== -1) {
|
|
340
|
+
const after = part.slice(colonIdx + 1).trim();
|
|
341
|
+
if (after.startsWith('{') || after.startsWith('[')) {
|
|
342
|
+
names.push(...extractDestructuredNamesESM(after));
|
|
343
|
+
} else {
|
|
344
|
+
const n = after.split(/[\s=]/)[0].trim();
|
|
345
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)) names.push(n);
|
|
346
|
+
}
|
|
347
|
+
} else {
|
|
348
|
+
const n = part.split(/[\s=]/)[0].trim();
|
|
349
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)) names.push(n);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return names;
|
|
353
|
+
}
|
|
354
|
+
|
|
174
355
|
function transformSource(source, url) {
|
|
175
356
|
const moduleName = moduleNameFromUrl(url);
|
|
357
|
+
let filePath = url;
|
|
358
|
+
try { filePath = fileURLToPath(url); } catch {}
|
|
359
|
+
|
|
176
360
|
const lines = source.split('\n');
|
|
177
361
|
const exportedFunctions = []; // { name, paramNames }
|
|
178
362
|
const exportedDefaults = []; // { name, paramNames }
|
|
179
363
|
const namedExports = []; // from `export { name }` statements
|
|
180
364
|
const result = [];
|
|
181
365
|
|
|
366
|
+
// Find variable declarations for tracing
|
|
367
|
+
const varTraceEnabled = process.env.TRICKLE_TRACE_VARS !== '0' && config.traceVarPath;
|
|
368
|
+
const varDecls = varTraceEnabled ? findVarDeclarationsESM(source) : [];
|
|
369
|
+
const destructDecls = varTraceEnabled ? findDestructuredDeclarationsESM(source) : [];
|
|
370
|
+
|
|
371
|
+
// Build a map: line number → trace calls to insert AFTER that line
|
|
372
|
+
const traceAfterLine = new Map();
|
|
373
|
+
for (const { varName, lineNo, insertAfterLine } of varDecls) {
|
|
374
|
+
if (!traceAfterLine.has(insertAfterLine)) traceAfterLine.set(insertAfterLine, []);
|
|
375
|
+
traceAfterLine.get(insertAfterLine).push(
|
|
376
|
+
`try{__trickle_tv(${varName},${JSON.stringify(varName)},${lineNo})}catch(__e){}`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
for (const { varNames, lineNo, insertAfterLine } of destructDecls) {
|
|
380
|
+
if (!traceAfterLine.has(insertAfterLine)) traceAfterLine.set(insertAfterLine, []);
|
|
381
|
+
const calls = varNames.map(n => `__trickle_tv(${n},${JSON.stringify(n)},${lineNo})`).join(';');
|
|
382
|
+
traceAfterLine.get(insertAfterLine).push(`try{${calls}}catch(__e){}`);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const hasVarTracing = varDecls.length > 0 || destructDecls.length > 0;
|
|
386
|
+
|
|
387
|
+
// Prepend var tracer setup BEFORE user code.
|
|
388
|
+
// In ESM, import declarations are hoisted regardless of position, so
|
|
389
|
+
// `import { createRequire }` here runs before any user code even though
|
|
390
|
+
// it appears before user imports in the source text.
|
|
391
|
+
// The `const` declarations run in order, so they're available when
|
|
392
|
+
// the inline trace calls (injected after var declarations) execute.
|
|
393
|
+
if (hasVarTracing && config.traceVarPath) {
|
|
394
|
+
const tvPath = config.traceVarPath.replace(/\\/g, '\\\\');
|
|
395
|
+
const fpEscaped = filePath.replace(/\\/g, '\\\\');
|
|
396
|
+
result.push(`import { createRequire as __cr_tv } from 'node:module';`);
|
|
397
|
+
result.push(`const __require_tv = __cr_tv(import.meta.url);`);
|
|
398
|
+
result.push(`const __tv_mod = __require_tv('${tvPath}');`);
|
|
399
|
+
result.push(`if (typeof __tv_mod.initVarTracer === 'function') __tv_mod.initVarTracer({});`);
|
|
400
|
+
result.push(`const __trickle_tv = (v, n, l) => { try { __tv_mod.traceVar(v, n, l, ${JSON.stringify(moduleName)}, '${fpEscaped}'); } catch(__e) {} };`);
|
|
401
|
+
}
|
|
402
|
+
|
|
182
403
|
for (let i = 0; i < lines.length; i++) {
|
|
183
404
|
const line = lines[i];
|
|
184
405
|
const trimmed = line.trimStart();
|
|
@@ -274,10 +495,18 @@ function transformSource(source, url) {
|
|
|
274
495
|
|
|
275
496
|
// export class, export type, export interface — leave as-is
|
|
276
497
|
result.push(line);
|
|
498
|
+
|
|
499
|
+
// Inject variable trace calls after this line (if any)
|
|
500
|
+
if (hasVarTracing) {
|
|
501
|
+
const calls = traceAfterLine.get(i + 1); // i+1 = 1-based line number
|
|
502
|
+
if (calls) {
|
|
503
|
+
for (const call of calls) result.push(call);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
277
506
|
}
|
|
278
507
|
|
|
279
|
-
// If nothing to wrap, return original
|
|
280
|
-
if (exportedFunctions.length === 0 && exportedDefaults.length === 0 && namedExports.length === 0) {
|
|
508
|
+
// If nothing to wrap or trace, return original
|
|
509
|
+
if (exportedFunctions.length === 0 && exportedDefaults.length === 0 && namedExports.length === 0 && !hasVarTracing) {
|
|
281
510
|
return source;
|
|
282
511
|
}
|
|
283
512
|
|
|
@@ -323,7 +552,8 @@ function transformSource(source, url) {
|
|
|
323
552
|
|
|
324
553
|
if (config.debug) {
|
|
325
554
|
const fnCount = exportedFunctions.length + exportedDefaults.length + namedExports.length;
|
|
326
|
-
|
|
555
|
+
const varCount = varDecls.length + destructDecls.length;
|
|
556
|
+
console.log(`[trickle/esm] Transformed ${fnCount} exports, ${varCount} vars from ${moduleName}`);
|
|
327
557
|
}
|
|
328
558
|
|
|
329
559
|
return transformed;
|
|
@@ -348,8 +578,10 @@ export async function load(url, context, nextLoad) {
|
|
|
348
578
|
? source
|
|
349
579
|
: Buffer.from(source).toString('utf-8');
|
|
350
580
|
|
|
351
|
-
// Only transform if the module has exports
|
|
352
|
-
|
|
581
|
+
// Only transform if the module has exports or variable declarations to trace
|
|
582
|
+
const varTraceEnabled = process.env.TRICKLE_TRACE_VARS !== '0' && config.traceVarPath;
|
|
583
|
+
const hasVarDecls = varTraceEnabled && /^[ \t]*(?:export\s+)?(?:const|let|var)\s+[a-zA-Z_$]/m.test(sourceStr);
|
|
584
|
+
if (!sourceStr.includes('export ') && !hasVarDecls) return result;
|
|
353
585
|
|
|
354
586
|
try {
|
|
355
587
|
const transformed = transformSource(sourceStr, url);
|
package/observe-esm.mjs
CHANGED
|
@@ -28,6 +28,7 @@ register(pathToFileURL(hooksPath).href, {
|
|
|
28
28
|
wrapperPath: join(__dirname, 'dist', 'wrap.js'),
|
|
29
29
|
transportPath: join(__dirname, 'dist', 'transport.js'),
|
|
30
30
|
envDetectPath: join(__dirname, 'dist', 'env-detect.js'),
|
|
31
|
+
traceVarPath: join(__dirname, 'dist', 'trace-var.js'),
|
|
31
32
|
backendUrl,
|
|
32
33
|
debug,
|
|
33
34
|
includePatterns: process.env.TRICKLE_OBSERVE_INCLUDE
|
package/package.json
CHANGED
package/src/observe-register.ts
CHANGED
|
@@ -153,12 +153,12 @@ function findClosingBrace(source: string, openBrace: number): number {
|
|
|
153
153
|
* Handles: const x = ...; let x = ...; var x = ...;
|
|
154
154
|
* Skips: destructuring, for-loop vars, require() calls, imports.
|
|
155
155
|
*/
|
|
156
|
-
function findVarDeclarations(source: string): Array<{ lineEnd: number; varName: string; lineNo: number }> {
|
|
156
|
+
function findVarDeclarations(source: string, lineOffset: number = 0): Array<{ lineEnd: number; varName: string; lineNo: number }> {
|
|
157
157
|
const varInsertions: Array<{ lineEnd: number; varName: string; lineNo: number }> = [];
|
|
158
158
|
|
|
159
|
-
// Match: const/let/var <identifier> = <something>
|
|
160
|
-
//
|
|
161
|
-
const varRegex = /^([ \t]*)(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)
|
|
159
|
+
// Match: const/let/var <identifier>[: TypeAnnotation] = <something>
|
|
160
|
+
// Handles both JS (no annotation) and TS (with annotation like `: string` or `: MyType`)
|
|
161
|
+
const varRegex = /^([ \t]*)(?:export\s+)?(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)(?:\s*:[^=]+?)?\s*=[^=]/gm;
|
|
162
162
|
let vmatch;
|
|
163
163
|
|
|
164
164
|
while ((vmatch = varRegex.exec(source)) !== null) {
|
|
@@ -174,10 +174,12 @@ function findVarDeclarations(source: string): Array<{ lineEnd: number; varName:
|
|
|
174
174
|
if (/^\s*require\s*\(/.test(restOfLine)) continue;
|
|
175
175
|
|
|
176
176
|
// Calculate line number (count newlines before this position)
|
|
177
|
+
// Subtract lineOffset to map compiled line numbers back to original source lines
|
|
177
178
|
let lineNo = 1;
|
|
178
179
|
for (let i = 0; i < vmatch.index; i++) {
|
|
179
180
|
if (source[i] === '\n') lineNo++;
|
|
180
181
|
}
|
|
182
|
+
lineNo = Math.max(1, lineNo - lineOffset);
|
|
181
183
|
|
|
182
184
|
// Find the end of this statement — look for the semicolon at depth 0
|
|
183
185
|
// or the end of the line for semicolon-free code
|
|
@@ -237,7 +239,7 @@ function findVarDeclarations(source: string): Array<{ lineEnd: number; varName:
|
|
|
237
239
|
/**
|
|
238
240
|
* Find destructured variable declarations: const { a, b } = ... and const [a, b] = ...
|
|
239
241
|
*/
|
|
240
|
-
function findDestructuredDeclarations(source: string): Array<{ lineEnd: number; varNames: string[]; lineNo: number }> {
|
|
242
|
+
function findDestructuredDeclarations(source: string, lineOffset: number = 0): Array<{ lineEnd: number; varNames: string[]; lineNo: number }> {
|
|
241
243
|
const results: Array<{ lineEnd: number; varNames: string[]; lineNo: number }> = [];
|
|
242
244
|
|
|
243
245
|
const destructRegex = /^[ \t]*(?:export\s+)?(?:const|let|var)\s+(\{[^}]*\}|\[[^\]]*\])\s*(?::\s*[^=]+?)?\s*=[^=]/gm;
|
|
@@ -255,6 +257,7 @@ function findDestructuredDeclarations(source: string): Array<{ lineEnd: number;
|
|
|
255
257
|
for (let i = 0; i < match.index; i++) {
|
|
256
258
|
if (source[i] === '\n') lineNo++;
|
|
257
259
|
}
|
|
260
|
+
lineNo = Math.max(1, lineNo - lineOffset);
|
|
258
261
|
|
|
259
262
|
const startPos = match.index + match[0].length - 1;
|
|
260
263
|
let pos = startPos;
|
|
@@ -388,8 +391,82 @@ function transformCjsSource(source: string, filename: string, moduleName: string
|
|
|
388
391
|
|
|
389
392
|
// Also find variable declarations for tracing
|
|
390
393
|
const varTraceEnabled = process.env.TRICKLE_TRACE_VARS !== '0';
|
|
391
|
-
|
|
392
|
-
|
|
394
|
+
|
|
395
|
+
// For TypeScript files (compiled by ts-node/tsc), type declarations (interfaces, type aliases)
|
|
396
|
+
// are stripped from the compiled JS, shifting line numbers. The only accurate way to get correct
|
|
397
|
+
// line numbers is to read the original .ts source file and parse it directly.
|
|
398
|
+
// For plain JS files, we parse the source directly.
|
|
399
|
+
let varInsertions: Array<{ lineEnd: number; varName: string; lineNo: number }> = [];
|
|
400
|
+
let destructInsertions: Array<{ lineEnd: number; varNames: string[]; lineNo: number }> = [];
|
|
401
|
+
|
|
402
|
+
if (varTraceEnabled) {
|
|
403
|
+
const isTsFile = /\.[mc]?tsx?$/.test(filename);
|
|
404
|
+
if (isTsFile) {
|
|
405
|
+
try {
|
|
406
|
+
// Read original TypeScript source to get correct line numbers
|
|
407
|
+
const fs = require('fs');
|
|
408
|
+
const originalSource: string = fs.readFileSync(filename, 'utf8');
|
|
409
|
+
const tsVarInsertions = findVarDeclarations(originalSource);
|
|
410
|
+
const tsDestructInsertions = findDestructuredDeclarations(originalSource);
|
|
411
|
+
|
|
412
|
+
// Map TypeScript variable names → correct line numbers (by occurrence order)
|
|
413
|
+
// Use a counter map to handle duplicate variable names in different scopes
|
|
414
|
+
const tsLineByVarAndOccurrence = new Map<string, number[]>();
|
|
415
|
+
for (const { varName, lineNo } of tsVarInsertions) {
|
|
416
|
+
if (!tsLineByVarAndOccurrence.has(varName)) tsLineByVarAndOccurrence.set(varName, []);
|
|
417
|
+
tsLineByVarAndOccurrence.get(varName)!.push(lineNo);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// Find positions in compiled JS (for inserting trace calls),
|
|
421
|
+
// but use line numbers from original TypeScript source
|
|
422
|
+
const compiledInsertions = findVarDeclarations(source);
|
|
423
|
+
const varOccurrenceCounter = new Map<string, number>();
|
|
424
|
+
for (const ins of compiledInsertions) {
|
|
425
|
+
const occCount = (varOccurrenceCounter.get(ins.varName) || 0);
|
|
426
|
+
varOccurrenceCounter.set(ins.varName, occCount + 1);
|
|
427
|
+
const tsLines = tsLineByVarAndOccurrence.get(ins.varName);
|
|
428
|
+
const correctLineNo = tsLines ? (tsLines[occCount] ?? tsLines[tsLines.length - 1]) : undefined;
|
|
429
|
+
varInsertions.push({ ...ins, lineNo: correctLineNo ?? ins.lineNo });
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const compiledDestructInsertions = findDestructuredDeclarations(source);
|
|
433
|
+
destructInsertions = compiledDestructInsertions; // Keep compiled line numbers as fallback
|
|
434
|
+
// Try to fix destructured line numbers too
|
|
435
|
+
const tsDestructByKey = new Map<string, number[]>();
|
|
436
|
+
for (const { varNames, lineNo } of tsDestructInsertions) {
|
|
437
|
+
const key = varNames.join(',');
|
|
438
|
+
if (!tsDestructByKey.has(key)) tsDestructByKey.set(key, []);
|
|
439
|
+
tsDestructByKey.get(key)!.push(lineNo);
|
|
440
|
+
}
|
|
441
|
+
const destructOccCounter = new Map<string, number>();
|
|
442
|
+
destructInsertions = compiledDestructInsertions.map(ins => {
|
|
443
|
+
const key = ins.varNames.join(',');
|
|
444
|
+
const occ = destructOccCounter.get(key) || 0;
|
|
445
|
+
destructOccCounter.set(key, occ + 1);
|
|
446
|
+
const tsLines = tsDestructByKey.get(key);
|
|
447
|
+
const correctLineNo = tsLines ? (tsLines[occ] ?? tsLines[tsLines.length - 1]) : undefined;
|
|
448
|
+
return { ...ins, lineNo: correctLineNo ?? ins.lineNo };
|
|
449
|
+
});
|
|
450
|
+
} catch {
|
|
451
|
+
// Fallback: use compiled line numbers with prologue offset
|
|
452
|
+
let lineOffset = 0;
|
|
453
|
+
const lines = source.split('\n');
|
|
454
|
+
for (const line of lines) {
|
|
455
|
+
const trimmed = line.trim();
|
|
456
|
+
if (trimmed === '"use strict";' || trimmed === "'use strict';" || trimmed === '') {
|
|
457
|
+
lineOffset++;
|
|
458
|
+
} else {
|
|
459
|
+
break;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
varInsertions = findVarDeclarations(source, lineOffset);
|
|
463
|
+
destructInsertions = findDestructuredDeclarations(source, lineOffset);
|
|
464
|
+
}
|
|
465
|
+
} else {
|
|
466
|
+
varInsertions = findVarDeclarations(source);
|
|
467
|
+
destructInsertions = findDestructuredDeclarations(source);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
393
470
|
|
|
394
471
|
if (insertions.length === 0 && varInsertions.length === 0 && destructInsertions.length === 0) return source;
|
|
395
472
|
|