tywrap 0.6.0 → 0.7.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.
Files changed (118) hide show
  1. package/dist/core/annotation-parser.d.ts.map +1 -1
  2. package/dist/core/annotation-parser.js +19 -14
  3. package/dist/core/annotation-parser.js.map +1 -1
  4. package/dist/core/discovery.d.ts +17 -0
  5. package/dist/core/discovery.d.ts.map +1 -1
  6. package/dist/core/discovery.js +59 -49
  7. package/dist/core/discovery.js.map +1 -1
  8. package/dist/core/generator.d.ts.map +1 -1
  9. package/dist/core/generator.js +40 -9
  10. package/dist/core/generator.js.map +1 -1
  11. package/dist/core/validation.d.ts +23 -0
  12. package/dist/core/validation.d.ts.map +1 -1
  13. package/dist/core/validation.js +52 -48
  14. package/dist/core/validation.js.map +1 -1
  15. package/dist/dev.d.ts.map +1 -1
  16. package/dist/dev.js +175 -133
  17. package/dist/dev.js.map +1 -1
  18. package/dist/runtime/base-bridge.d.ts +57 -0
  19. package/dist/runtime/base-bridge.d.ts.map +1 -0
  20. package/dist/runtime/base-bridge.js +72 -0
  21. package/dist/runtime/base-bridge.js.map +1 -0
  22. package/dist/runtime/bridge-codec.d.ts +15 -0
  23. package/dist/runtime/bridge-codec.d.ts.map +1 -1
  24. package/dist/runtime/bridge-codec.js +45 -48
  25. package/dist/runtime/bridge-codec.js.map +1 -1
  26. package/dist/runtime/http-transport.d.ts +11 -1
  27. package/dist/runtime/http-transport.d.ts.map +1 -1
  28. package/dist/runtime/http-transport.js +19 -0
  29. package/dist/runtime/http-transport.js.map +1 -1
  30. package/dist/runtime/http.d.ts +5 -12
  31. package/dist/runtime/http.d.ts.map +1 -1
  32. package/dist/runtime/http.js +6 -29
  33. package/dist/runtime/http.js.map +1 -1
  34. package/dist/runtime/index.d.ts +1 -1
  35. package/dist/runtime/index.d.ts.map +1 -1
  36. package/dist/runtime/index.js.map +1 -1
  37. package/dist/runtime/node.d.ts +12 -19
  38. package/dist/runtime/node.d.ts.map +1 -1
  39. package/dist/runtime/node.js +14 -34
  40. package/dist/runtime/node.js.map +1 -1
  41. package/dist/runtime/pooled-transport.d.ts +21 -2
  42. package/dist/runtime/pooled-transport.d.ts.map +1 -1
  43. package/dist/runtime/pooled-transport.js +16 -0
  44. package/dist/runtime/pooled-transport.js.map +1 -1
  45. package/dist/runtime/pyodide-bootstrap-core.generated.d.ts.map +1 -1
  46. package/dist/runtime/pyodide-bootstrap-core.generated.js +1 -1
  47. package/dist/runtime/pyodide-bootstrap-core.generated.js.map +1 -1
  48. package/dist/runtime/pyodide-transport.d.ts +12 -1
  49. package/dist/runtime/pyodide-transport.d.ts.map +1 -1
  50. package/dist/runtime/pyodide-transport.js +20 -0
  51. package/dist/runtime/pyodide-transport.js.map +1 -1
  52. package/dist/runtime/pyodide.d.ts +5 -12
  53. package/dist/runtime/pyodide.d.ts.map +1 -1
  54. package/dist/runtime/pyodide.js +6 -29
  55. package/dist/runtime/pyodide.js.map +1 -1
  56. package/dist/runtime/rpc-client.d.ts +32 -1
  57. package/dist/runtime/rpc-client.d.ts.map +1 -1
  58. package/dist/runtime/rpc-client.js +45 -24
  59. package/dist/runtime/rpc-client.js.map +1 -1
  60. package/dist/runtime/subprocess-transport.d.ts +26 -1
  61. package/dist/runtime/subprocess-transport.d.ts.map +1 -1
  62. package/dist/runtime/subprocess-transport.js +72 -35
  63. package/dist/runtime/subprocess-transport.js.map +1 -1
  64. package/dist/runtime/transport.d.ts +59 -0
  65. package/dist/runtime/transport.d.ts.map +1 -1
  66. package/dist/runtime/transport.js +1 -0
  67. package/dist/runtime/transport.js.map +1 -1
  68. package/dist/types/index.d.ts +35 -0
  69. package/dist/types/index.d.ts.map +1 -1
  70. package/dist/tywrap.d.ts +0 -5
  71. package/dist/tywrap.d.ts.map +1 -1
  72. package/dist/tywrap.js +212 -169
  73. package/dist/tywrap.js.map +1 -1
  74. package/dist/utils/cache.d.ts +11 -0
  75. package/dist/utils/cache.d.ts.map +1 -1
  76. package/dist/utils/cache.js +50 -58
  77. package/dist/utils/cache.js.map +1 -1
  78. package/dist/utils/codec.d.ts +2 -0
  79. package/dist/utils/codec.d.ts.map +1 -1
  80. package/dist/utils/codec.js +53 -2
  81. package/dist/utils/codec.js.map +1 -1
  82. package/dist/utils/python.d.ts.map +1 -1
  83. package/dist/utils/python.js +28 -17
  84. package/dist/utils/python.js.map +1 -1
  85. package/dist/utils/runtime.d.ts.map +1 -1
  86. package/dist/utils/runtime.js +22 -16
  87. package/dist/utils/runtime.js.map +1 -1
  88. package/dist/version.js +1 -1
  89. package/package.json +7 -1
  90. package/runtime/__pycache__/_tywrap_member_fixtures.cpython-311.pyc +0 -0
  91. package/runtime/__pycache__/safe_codec.cpython-311.pyc +0 -0
  92. package/runtime/__pycache__/tywrap_bridge_core.cpython-311.pyc +0 -0
  93. package/runtime/tywrap_bridge_core.py +55 -3
  94. package/src/core/annotation-parser.ts +23 -18
  95. package/src/core/discovery.ts +70 -54
  96. package/src/core/generator.ts +50 -11
  97. package/src/core/validation.ts +84 -48
  98. package/src/dev.ts +237 -153
  99. package/src/runtime/base-bridge.ts +106 -0
  100. package/src/runtime/bridge-codec.ts +58 -70
  101. package/src/runtime/http-transport.ts +21 -1
  102. package/src/runtime/http.ts +7 -51
  103. package/src/runtime/index.ts +1 -0
  104. package/src/runtime/node.ts +17 -52
  105. package/src/runtime/pooled-transport.ts +25 -2
  106. package/src/runtime/pyodide-bootstrap-core.generated.ts +1 -1
  107. package/src/runtime/pyodide-transport.ts +22 -0
  108. package/src/runtime/pyodide.ts +7 -52
  109. package/src/runtime/rpc-client.ts +56 -32
  110. package/src/runtime/subprocess-transport.ts +89 -40
  111. package/src/runtime/transport.ts +71 -0
  112. package/src/types/index.ts +37 -0
  113. package/src/tywrap.ts +274 -187
  114. package/src/utils/cache.ts +59 -61
  115. package/src/utils/codec.ts +61 -4
  116. package/src/utils/python.ts +33 -20
  117. package/src/utils/runtime.ts +24 -13
  118. package/src/version.ts +1 -1
@@ -195,60 +195,96 @@ export class ValidationEngine {
195
195
  errors: AnalysisError[],
196
196
  warnings: AnalysisWarning[]
197
197
  ): void {
198
- // Check return type (skip __init__ methods as they conventionally don't need return type annotations)
199
- if (this.isEmptyType(func.returnType) && func.name !== '__init__') {
200
- if (this.config.allowMissingTypeHints) {
201
- warnings.push({
202
- type: 'missing-type',
203
- message: `Function '${func.name}' is missing return type annotation`,
204
- });
205
- } else if (this.config.strictTypeChecking) {
206
- // In strict mode without allowMissingTypeHints, we warn first then error
207
- warnings.push({
208
- type: 'missing-type',
209
- message: `Function '${func.name}' is missing return type annotation`,
210
- });
211
- errors.push({
212
- type: 'type',
213
- message: `Function '${func.name}' requires return type annotation`,
214
- });
215
- }
216
- }
198
+ this.checkReturnTypeHint(func, errors, warnings);
217
199
 
218
200
  // Check parameter types (skip 'self' and 'cls' parameters)
219
201
  for (const param of func.parameters) {
220
- if (this.isEmptyType(param.type) && param.name !== 'self' && param.name !== 'cls') {
221
- if (this.config.allowMissingTypeHints) {
222
- warnings.push({
223
- type: 'missing-type',
224
- message: `Parameter '${param.name}' in function '${func.name}' is missing type annotation`,
225
- });
226
- } else if (this.config.strictTypeChecking) {
227
- // In strict mode without allowMissingTypeHints, we warn first then error
228
- warnings.push({
229
- type: 'missing-type',
230
- message: `Parameter '${param.name}' in function '${func.name}' is missing type annotation`,
231
- });
232
- errors.push({
233
- type: 'type',
234
- message: `Parameter '${param.name}' in function '${func.name}' requires type annotation`,
235
- });
236
- }
237
- }
202
+ this.checkParameterTypeHint(func, param, errors, warnings);
203
+ this.checkParameterTypeStructure(param, errors);
204
+ }
238
205
 
239
- // Validate type structure only in strict mode (skip 'self' and 'cls' parameters)
240
- if (
241
- this.config.strictTypeChecking &&
242
- !this.config.allowMissingTypeHints &&
243
- param.name !== 'self' &&
244
- param.name !== 'cls'
245
- ) {
246
- const typeErrors = this.validateTypeAnnotation(param.type, `parameter '${param.name}'`);
247
- errors.push(...typeErrors);
248
- }
206
+ this.checkReturnTypeStructure(func, errors);
207
+ }
208
+
209
+ /**
210
+ * Emit a missing-type warning, and—in strict mode—an accompanying error.
211
+ * In strict mode without allowMissingTypeHints, we warn first then error.
212
+ */
213
+ private reportMissingType(
214
+ warningMessage: string,
215
+ errorMessage: string,
216
+ warnings: AnalysisWarning[],
217
+ errors: AnalysisError[]
218
+ ): void {
219
+ if (this.config.allowMissingTypeHints) {
220
+ warnings.push({ type: 'missing-type', message: warningMessage });
221
+ } else if (this.config.strictTypeChecking) {
222
+ warnings.push({ type: 'missing-type', message: warningMessage });
223
+ errors.push({ type: 'type', message: errorMessage });
249
224
  }
225
+ }
250
226
 
251
- // Validate return type structure only in strict mode
227
+ /**
228
+ * Check the function return type annotation (skip __init__ methods as they
229
+ * conventionally don't need return type annotations).
230
+ */
231
+ private checkReturnTypeHint(
232
+ func: PythonFunction,
233
+ errors: AnalysisError[],
234
+ warnings: AnalysisWarning[]
235
+ ): void {
236
+ if (this.isEmptyType(func.returnType) && func.name !== '__init__') {
237
+ this.reportMissingType(
238
+ `Function '${func.name}' is missing return type annotation`,
239
+ `Function '${func.name}' requires return type annotation`,
240
+ warnings,
241
+ errors
242
+ );
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Check a single parameter's type annotation (skip 'self' and 'cls').
248
+ */
249
+ private checkParameterTypeHint(
250
+ func: PythonFunction,
251
+ param: PythonFunction['parameters'][number],
252
+ errors: AnalysisError[],
253
+ warnings: AnalysisWarning[]
254
+ ): void {
255
+ if (this.isEmptyType(param.type) && param.name !== 'self' && param.name !== 'cls') {
256
+ this.reportMissingType(
257
+ `Parameter '${param.name}' in function '${func.name}' is missing type annotation`,
258
+ `Parameter '${param.name}' in function '${func.name}' requires type annotation`,
259
+ warnings,
260
+ errors
261
+ );
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Validate a single parameter's type structure only in strict mode
267
+ * (skip 'self' and 'cls' parameters).
268
+ */
269
+ private checkParameterTypeStructure(
270
+ param: PythonFunction['parameters'][number],
271
+ errors: AnalysisError[]
272
+ ): void {
273
+ if (
274
+ this.config.strictTypeChecking &&
275
+ !this.config.allowMissingTypeHints &&
276
+ param.name !== 'self' &&
277
+ param.name !== 'cls'
278
+ ) {
279
+ const typeErrors = this.validateTypeAnnotation(param.type, `parameter '${param.name}'`);
280
+ errors.push(...typeErrors);
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Validate the return type structure only in strict mode.
286
+ */
287
+ private checkReturnTypeStructure(func: PythonFunction, errors: AnalysisError[]): void {
252
288
  if (this.config.strictTypeChecking && !this.config.allowMissingTypeHints) {
253
289
  const returnTypeErrors = this.validateTypeAnnotation(func.returnType, 'return type');
254
290
  errors.push(...returnTypeErrors);
package/src/dev.ts CHANGED
@@ -335,42 +335,44 @@ async function listExistingManagedFiles(outputDir: string): Promise<Set<string>>
335
335
  return managedFiles;
336
336
  }
337
337
 
338
+ async function listChildDirectories(current: string): Promise<string[]> {
339
+ let entries;
340
+ try {
341
+ entries = await readdir(current, { withFileTypes: true });
342
+ } catch {
343
+ return [];
344
+ }
345
+
346
+ return entries
347
+ .filter(entry => entry.isDirectory())
348
+ .map(entry => join(current, entry.name));
349
+ }
350
+
351
+ async function isWatchableDirectory(current: string, ignoredPaths: string[]): Promise<boolean> {
352
+ if (shouldIgnoreWatchPath(current, ignoredPaths)) {
353
+ return false;
354
+ }
355
+
356
+ try {
357
+ const currentStats = await stat(current);
358
+ return currentStats.isDirectory();
359
+ } catch {
360
+ return false;
361
+ }
362
+ }
363
+
338
364
  async function collectWatchDirectories(root: string, ignoredPaths: string[]): Promise<string[]> {
339
365
  const queue = [resolve(root)];
340
366
  const directories: string[] = [];
341
367
 
342
368
  while (queue.length > 0) {
343
369
  const current = queue.shift()!;
344
- if (shouldIgnoreWatchPath(current, ignoredPaths)) {
345
- continue;
346
- }
347
-
348
- let currentStats;
349
- try {
350
- currentStats = await stat(current);
351
- } catch {
352
- continue;
353
- }
354
-
355
- if (!currentStats.isDirectory()) {
370
+ if (!(await isWatchableDirectory(current, ignoredPaths))) {
356
371
  continue;
357
372
  }
358
373
 
359
374
  directories.push(current);
360
-
361
- let entries;
362
- try {
363
- entries = await readdir(current, { withFileTypes: true });
364
- } catch {
365
- continue;
366
- }
367
-
368
- for (const entry of entries) {
369
- if (!entry.isDirectory()) {
370
- continue;
371
- }
372
- queue.push(join(current, entry.name));
373
- }
375
+ queue.push(...(await listChildDirectories(current)));
374
376
  }
375
377
 
376
378
  return normalizePaths(directories);
@@ -444,7 +446,51 @@ async function promoteManagedFiles(
444
446
  }
445
447
  }
446
448
 
447
- async function resolveWatchTargets(config: TywrapOptions): Promise<WatchTarget[]> {
449
+ interface WatchTargetPayload {
450
+ missing?: boolean;
451
+ origin?: string | null;
452
+ locations?: string[];
453
+ has_location?: boolean;
454
+ }
455
+
456
+ interface WatchPythonEnv {
457
+ pythonPath: string;
458
+ env: { PYTHONPATH: string } | undefined;
459
+ timeoutMs: number;
460
+ }
461
+
462
+ const WATCH_TARGET_RESOLUTION_SCRIPT = [
463
+ 'import importlib',
464
+ 'import importlib.util',
465
+ 'import json',
466
+ 'import sys',
467
+ '',
468
+ 'module_name = sys.argv[1]',
469
+ 'spec = importlib.util.find_spec(module_name)',
470
+ 'if spec is None:',
471
+ " print(json.dumps({'missing': True}))",
472
+ ' raise SystemExit(0)',
473
+ '',
474
+ 'module_path = None',
475
+ 'module_origin = spec.origin',
476
+ 'if spec.submodule_search_locations:',
477
+ ' try:',
478
+ ' module = importlib.import_module(module_name)',
479
+ ' except Exception:',
480
+ ' module = None',
481
+ ' if module is not None:',
482
+ ' module_path = getattr(module, "__path__", None)',
483
+ ' module_origin = getattr(module, "__file__", None) or spec.origin',
484
+ 'payload = {',
485
+ " 'missing': False,",
486
+ " 'origin': module_origin,",
487
+ " 'locations': list(module_path) if module_path is not None else list(spec.submodule_search_locations or []),",
488
+ " 'has_location': bool(spec.has_location),",
489
+ '}',
490
+ 'print(json.dumps(payload))',
491
+ ].join('\n');
492
+
493
+ async function resolveWatchPythonEnv(config: TywrapOptions): Promise<WatchPythonEnv> {
448
494
  const pythonPath = await resolvePythonExecutable({
449
495
  pythonPath: config.runtime?.node?.pythonPath,
450
496
  virtualEnv: config.runtime?.node?.virtualEnv,
@@ -460,104 +506,100 @@ async function resolveWatchTargets(config: TywrapOptions): Promise<WatchTarget[]
460
506
  const env = mergedPyPath ? { PYTHONPATH: mergedPyPath } : undefined;
461
507
  const timeoutMs = config.runtime?.node?.timeout ?? 30000;
462
508
 
463
- const watchTargets: WatchTarget[] = [];
464
-
465
- for (const moduleName of Object.keys(config.pythonModules ?? {})) {
466
- const resolutionScript = [
467
- 'import importlib',
468
- 'import importlib.util',
469
- 'import json',
470
- 'import sys',
471
- '',
472
- 'module_name = sys.argv[1]',
473
- 'spec = importlib.util.find_spec(module_name)',
474
- 'if spec is None:',
475
- " print(json.dumps({'missing': True}))",
476
- ' raise SystemExit(0)',
477
- '',
478
- 'module_path = None',
479
- 'module_origin = spec.origin',
480
- 'if spec.submodule_search_locations:',
481
- ' try:',
482
- ' module = importlib.import_module(module_name)',
483
- ' except Exception:',
484
- ' module = None',
485
- ' if module is not None:',
486
- ' module_path = getattr(module, "__path__", None)',
487
- ' module_origin = getattr(module, "__file__", None) or spec.origin',
488
- 'payload = {',
489
- " 'missing': False,",
490
- " 'origin': module_origin,",
491
- " 'locations': list(module_path) if module_path is not None else list(spec.submodule_search_locations or []),",
492
- " 'has_location': bool(spec.has_location),",
493
- '}',
494
- 'print(json.dumps(payload))',
495
- ].join('\n');
496
-
497
- const result = await processUtils.exec(pythonPath, ['-c', resolutionScript, moduleName], {
498
- timeoutMs,
499
- env,
500
- });
509
+ return { pythonPath, env, timeoutMs };
510
+ }
501
511
 
502
- if (result.code !== 0) {
503
- throw new Error(
504
- `Failed to resolve watch target for module "${moduleName}": ${result.stderr.trim() || result.stdout.trim() || 'unknown error'}`
505
- );
512
+ async function resolveWatchTargetPayload(
513
+ moduleName: string,
514
+ pythonEnv: WatchPythonEnv
515
+ ): Promise<WatchTargetPayload> {
516
+ const result = await processUtils.exec(
517
+ pythonEnv.pythonPath,
518
+ ['-c', WATCH_TARGET_RESOLUTION_SCRIPT, moduleName],
519
+ {
520
+ timeoutMs: pythonEnv.timeoutMs,
521
+ env: pythonEnv.env,
506
522
  }
523
+ );
507
524
 
508
- let payload: {
509
- missing?: boolean;
510
- origin?: string | null;
511
- locations?: string[];
512
- has_location?: boolean;
513
- };
514
- try {
515
- payload = JSON.parse(result.stdout) as {
516
- missing?: boolean;
517
- origin?: string | null;
518
- locations?: string[];
519
- has_location?: boolean;
520
- };
521
- } catch (error) {
525
+ if (result.code !== 0) {
526
+ throw new Error(
527
+ `Failed to resolve watch target for module "${moduleName}": ${result.stderr.trim() || result.stdout.trim() || 'unknown error'}`
528
+ );
529
+ }
530
+
531
+ try {
532
+ return JSON.parse(result.stdout) as WatchTargetPayload;
533
+ } catch (error) {
534
+ throw new Error(
535
+ `Failed to parse watch target for module "${moduleName}": ${(error as Error).message}`
536
+ );
537
+ }
538
+ }
539
+
540
+ async function resolvePackageWatchTargets(
541
+ moduleName: string,
542
+ packageLocations: string[]
543
+ ): Promise<WatchTarget[]> {
544
+ const targets: WatchTarget[] = [];
545
+ for (const location of packageLocations) {
546
+ const packageDir = resolve(location);
547
+ const stats = await stat(packageDir);
548
+ if (!stats.isDirectory()) {
522
549
  throw new Error(
523
- `Failed to parse watch target for module "${moduleName}": ${(error as Error).message}`
550
+ `Module "${moduleName}" resolved to "${packageDir}", but it is not a package directory`
524
551
  );
525
552
  }
553
+ targets.push({ moduleName, path: packageDir, kind: 'directory' });
554
+ }
555
+ return targets;
556
+ }
526
557
 
527
- if (payload.missing) {
528
- throw new Error(`Module "${moduleName}" could not be resolved for watching`);
529
- }
558
+ async function resolveFileWatchTarget(
559
+ moduleName: string,
560
+ payload: WatchTargetPayload
561
+ ): Promise<WatchTarget> {
562
+ if (typeof payload.origin !== 'string' || !payload.origin.endsWith('.py')) {
563
+ throw new Error(
564
+ `Module "${moduleName}" is not backed by a local Python source file or package directory and cannot be watched`
565
+ );
566
+ }
530
567
 
531
- const packageLocations = Array.isArray(payload.locations) ? payload.locations : [];
532
- if (packageLocations.length > 0) {
533
- for (const location of packageLocations) {
534
- const packageDir = resolve(location);
535
- const stats = await stat(packageDir);
536
- if (!stats.isDirectory()) {
537
- throw new Error(
538
- `Module "${moduleName}" resolved to "${packageDir}", but it is not a package directory`
539
- );
540
- }
541
- watchTargets.push({ moduleName, path: packageDir, kind: 'directory' });
542
- }
543
- continue;
544
- }
568
+ const modulePath = resolve(payload.origin);
569
+ const stats = await stat(modulePath);
570
+ if (!stats.isFile()) {
571
+ throw new Error(
572
+ `Module "${moduleName}" resolved to "${modulePath}", but it is not a Python source file`
573
+ );
574
+ }
545
575
 
546
- if (typeof payload.origin !== 'string' || !payload.origin.endsWith('.py')) {
547
- throw new Error(
548
- `Module "${moduleName}" is not backed by a local Python source file or package directory and cannot be watched`
549
- );
550
- }
576
+ return { moduleName, path: modulePath, kind: 'file' };
577
+ }
551
578
 
552
- const modulePath = resolve(payload.origin);
553
- const stats = await stat(modulePath);
554
- if (!stats.isFile()) {
555
- throw new Error(
556
- `Module "${moduleName}" resolved to "${modulePath}", but it is not a Python source file`
557
- );
558
- }
579
+ async function resolveModuleWatchTargets(
580
+ moduleName: string,
581
+ pythonEnv: WatchPythonEnv
582
+ ): Promise<WatchTarget[]> {
583
+ const payload = await resolveWatchTargetPayload(moduleName, pythonEnv);
584
+
585
+ if (payload.missing) {
586
+ throw new Error(`Module "${moduleName}" could not be resolved for watching`);
587
+ }
559
588
 
560
- watchTargets.push({ moduleName, path: modulePath, kind: 'file' });
589
+ const packageLocations = Array.isArray(payload.locations) ? payload.locations : [];
590
+ if (packageLocations.length > 0) {
591
+ return resolvePackageWatchTargets(moduleName, packageLocations);
592
+ }
593
+
594
+ return [await resolveFileWatchTarget(moduleName, payload)];
595
+ }
596
+
597
+ async function resolveWatchTargets(config: TywrapOptions): Promise<WatchTarget[]> {
598
+ const pythonEnv = await resolveWatchPythonEnv(config);
599
+
600
+ const watchTargets: WatchTarget[] = [];
601
+ for (const moduleName of Object.keys(config.pythonModules ?? {})) {
602
+ watchTargets.push(...(await resolveModuleWatchTargets(moduleName, pythonEnv)));
561
603
  }
562
604
 
563
605
  return watchTargets;
@@ -786,6 +828,28 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
786
828
  return watcherRefreshPromise;
787
829
  };
788
830
 
831
+ interface ReloadState {
832
+ stage: StageResult | null;
833
+ nextBridge: T | null;
834
+ preparedWatchers: PreparedWatchers | null;
835
+ }
836
+
837
+ interface PreparedReload {
838
+ stage: StageResult;
839
+ preparedWatchers: PreparedWatchers;
840
+ nextIgnoredPaths: string[];
841
+ watchPaths: string[];
842
+ }
843
+
844
+ const disposeReloadFailure = async (state: ReloadState): Promise<void> => {
845
+ if (state.preparedWatchers) {
846
+ closePreparedWatchers(state.preparedWatchers);
847
+ }
848
+ if (state.nextBridge) {
849
+ await state.nextBridge.dispose().catch(() => {});
850
+ }
851
+ };
852
+
789
853
  const runReload = async (trigger: { path?: string; manual: boolean }): Promise<boolean> => {
790
854
  if (closed) {
791
855
  return false;
@@ -793,20 +857,18 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
793
857
 
794
858
  emit({ type: 'reload-start', path: trigger.path, manual: trigger.manual });
795
859
 
796
- let stage: StageResult | null = null;
797
- let nextBridge: T | null = null;
798
- let preparedWatchers: PreparedWatchers | null = null;
860
+ const state: ReloadState = { stage: null, nextBridge: null, preparedWatchers: null };
799
861
 
800
862
  const abortReload = async (
801
863
  managerToDispose: ManagedBridgeReloader<T> | null = null
802
864
  ): Promise<boolean> => {
803
- if (preparedWatchers) {
804
- closePreparedWatchers(preparedWatchers);
805
- preparedWatchers = null;
865
+ if (state.preparedWatchers) {
866
+ closePreparedWatchers(state.preparedWatchers);
867
+ state.preparedWatchers = null;
806
868
  }
807
- if (nextBridge) {
808
- await nextBridge.dispose().catch(() => {});
809
- nextBridge = null;
869
+ if (state.nextBridge) {
870
+ await state.nextBridge.dispose().catch(() => {});
871
+ state.nextBridge = null;
810
872
  }
811
873
  if (managerToDispose) {
812
874
  await managerToDispose.dispose().catch(() => {});
@@ -814,10 +876,13 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
814
876
  return false;
815
877
  };
816
878
 
817
- try {
818
- stage = await generateToStage(configFile);
879
+ // Generate the next stage, prepare watchers, and warm the next bridge.
880
+ // Returns null when the session closed mid-flight (caller aborts).
881
+ const prepareReload = async (): Promise<PreparedReload | null> => {
882
+ const stage = await generateToStage(configFile);
883
+ state.stage = stage;
819
884
  if (closed) {
820
- return abortReload();
885
+ return null;
821
886
  }
822
887
  currentBridgeConfig = stage.config;
823
888
  const nextIgnoredPaths = buildIgnoredPaths(stage.outputDir);
@@ -828,17 +893,50 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
828
893
  ...extraWatchSources,
829
894
  ]);
830
895
  const watchPaths = normalizePaths(watchSources.map(source => source.path));
831
- preparedWatchers = await prepareWatchers(watchSources, nextIgnoredPaths);
896
+ const preparedWatchers = await prepareWatchers(watchSources, nextIgnoredPaths);
897
+ state.preparedWatchers = preparedWatchers;
832
898
  if (closed) {
833
- return abortReload();
899
+ return null;
834
900
  }
835
901
 
836
902
  if (bridgeManager) {
837
- nextBridge = await bridgeManager.prepareNextBridge();
903
+ state.nextBridge = await bridgeManager.prepareNextBridge();
904
+ if (closed) {
905
+ return null;
906
+ }
907
+ }
908
+
909
+ return { stage, preparedWatchers, nextIgnoredPaths, watchPaths };
910
+ };
911
+
912
+ // Activate (or create) the bridge for the freshly prepared stage.
913
+ // Returns the manager to dispose (or null) when the session closed
914
+ // mid-flight, otherwise null; sets `closedDuringActivation` accordingly.
915
+ let closedDuringActivation = false;
916
+ const activateReloadBridge = async (): Promise<ManagedBridgeReloader<T> | null> => {
917
+ if (bridgeManager && state.nextBridge) {
918
+ await bridgeManager.activatePreparedBridge(state.nextBridge);
919
+ state.nextBridge = null;
920
+ closedDuringActivation = closed;
921
+ return null;
922
+ }
923
+ if (!bridgeManager) {
924
+ const createdBridgeManager = await ManagedBridgeReloader.create(createBridgeForSession);
838
925
  if (closed) {
839
- return abortReload();
926
+ closedDuringActivation = true;
927
+ return createdBridgeManager;
840
928
  }
929
+ bridgeManager = createdBridgeManager;
930
+ }
931
+ return null;
932
+ };
933
+
934
+ try {
935
+ const prepared = await prepareReload();
936
+ if (!prepared) {
937
+ return abortReload();
841
938
  }
939
+ const { stage } = prepared;
842
940
 
843
941
  const previousManagedFiles =
844
942
  activeOutputDir === stage.outputDir
@@ -853,29 +951,20 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
853
951
  return abortReload();
854
952
  }
855
953
 
856
- if (bridgeManager && nextBridge) {
857
- await bridgeManager.activatePreparedBridge(nextBridge);
858
- nextBridge = null;
859
- if (closed) {
860
- return abortReload();
861
- }
862
- } else if (!bridgeManager) {
863
- const createdBridgeManager = await ManagedBridgeReloader.create(createBridgeForSession);
864
- if (closed) {
865
- return abortReload(createdBridgeManager);
866
- }
867
- bridgeManager = createdBridgeManager;
954
+ const managerToDispose = await activateReloadBridge();
955
+ if (closedDuringActivation) {
956
+ return abortReload(managerToDispose);
868
957
  }
869
958
 
870
959
  managedFiles = promotedManagedFiles;
871
960
  activeOutputDir = stage.outputDir;
872
- ignoredPaths = nextIgnoredPaths;
873
- commitWatchers(preparedWatchers);
961
+ ignoredPaths = prepared.nextIgnoredPaths;
962
+ commitWatchers(prepared.preparedWatchers);
874
963
  emit({
875
964
  type: 'reload-success',
876
965
  path: trigger.path,
877
966
  manual: trigger.manual,
878
- paths: watchPaths,
967
+ paths: prepared.watchPaths,
879
968
  written: [...stage.files.keys()].sort(),
880
969
  warnings: stage.warnings,
881
970
  });
@@ -883,12 +972,7 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
883
972
  return true;
884
973
  } catch (error) {
885
974
  lastReloadError = error instanceof Error ? error : new Error(String(error));
886
- if (preparedWatchers) {
887
- closePreparedWatchers(preparedWatchers);
888
- }
889
- if (nextBridge) {
890
- await nextBridge.dispose().catch(() => {});
891
- }
975
+ await disposeReloadFailure(state);
892
976
  emit({
893
977
  type: 'reload-error',
894
978
  path: trigger.path,
@@ -897,8 +981,8 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
897
981
  });
898
982
  return false;
899
983
  } finally {
900
- if (stage) {
901
- await rm(stage.tempDir, { recursive: true, force: true });
984
+ if (state.stage) {
985
+ await rm(state.stage.tempDir, { recursive: true, force: true });
902
986
  }
903
987
  }
904
988
  };