-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_typescript_boundaries.py
More file actions
572 lines (435 loc) · 16.5 KB
/
Copy pathtest_typescript_boundaries.py
File metadata and controls
572 lines (435 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
"""
Boundary lint for Solid.js import restrictions.
Solid import boundary (from plan refactored-drifting-narwhal.md, M1/WS-M1-B):
Solid ALLOWED: src/shell/, src/scene_runtime/renderer/,
src/scene_runtime/state/
Solid FORBIDDEN: src/scene_runtime/layout/, pipeline/, validation/,
generated/, src/scene_runtime/protocol/
(the stepper; type-only imports from state permitted).
The stepper (protocol/) calls store operations through a small runtime bridge,
never as a Solid component dependency. Type-only imports (import type ...) of
Solid types from the state layer into protocol/ are explicitly allowed.
Additional boundary rules:
- No src/shell/ or src/launcher/ imported in scene_runtime/layout/ or
scene_runtime/renderer/ (shell/adapter/types is the seam exception).
Approach: scan every .ts/.tsx file in the protected directories, extract
imports, and assert no violations. A negative test creates a known-bad fixture,
asserts it would be caught, then cleans up.
"""
import os
import re
# PIP3 modules
import pytest
# local repo modules
import file_utils
#============================================
def _resolve_repo_root() -> str:
"""
Resolve the repository root.
Delegates to the propagated shared helper (tests/file_utils.py), the
same resolver other tests use, instead of re-implementing the git rev-parse
subprocess call here.
Returns:
str: Absolute path to repository root.
"""
return file_utils.get_repo_root()
#============================================
def _read_marker() -> str:
"""
Read REPO_TYPE marker from repository root.
Returns:
str: Marker token (e.g., "typescript"), or None if missing.
"""
repo_root = _resolve_repo_root()
marker_path = os.path.join(repo_root, "REPO_TYPE")
if not os.path.exists(marker_path):
return None
with open(marker_path, "r", encoding="utf-8") as handle:
content = handle.read().strip()
return content if content else None
#============================================
def _extract_imports(file_content: str) -> list[str]:
"""
Extract all import paths from TypeScript/TSX file content.
Matches patterns like:
import { x } from "path"
import x from 'path'
import * as x from "path"
import type { T } from "path"
Args:
file_content: Raw TypeScript/TSX source code
Returns:
List of import paths (the string inside quotes)
"""
# Match import statements (including type-only) with any quote style
pattern = r'import\s+(?:type\s+)?(?:\{[^}]*\}|[\w\s*,]+)\s+from\s+["\']([^"\']+)["\']'
matches = re.findall(pattern, file_content)
return matches
#============================================
def _extract_type_only_imports(file_content: str) -> list[str]:
"""
Extract only type-only import paths (import type ... from ...).
Args:
file_content: Raw TypeScript/TSX source code
Returns:
List of import paths that are type-only imports
"""
# Match only "import type { ... } from '...'" forms
pattern = r'import\s+type\s+(?:\{[^}]*\}|[\w\s*,]+)\s+from\s+["\']([^"\']+)["\']'
matches = re.findall(pattern, file_content)
return matches
#============================================
def _is_solid_import(import_path: str) -> bool:
"""
Return True if import_path is a solid-js import.
Args:
import_path: The import string (e.g., "solid-js", "solid-js/store")
Returns:
True if this is a solid-js or solid-js/* import
"""
return import_path == "solid-js" or import_path.startswith("solid-js/")
#============================================
def _check_import_violation(import_path: str) -> str | None:
"""
Check if a single import violates the boundary rules for layout/ and renderer/.
Rule 1: no 'solid-js' or 'solid-js/*'
Rule 2: no absolute or relative paths resolving to src/shell/ or src/launcher/
Args:
import_path: The import string (e.g., "solid-js", "./../../shell/foo")
Returns:
Violation reason string if violated, None if OK.
"""
# Rule 1: Reject solid-js and solid-js subpaths
if _is_solid_import(import_path):
return f"forbidden solid-js import: {import_path}"
# Rule 2: Reject relative/absolute paths pointing to shell/ or launcher/.
# Exception: src/shell/adapter/types is the typed seam contract; the
# protocol runtime imports it deliberately. Type-only imports stay
# free of any runtime dependency.
is_seam_types = (
"shell/adapter/types" in import_path
or import_path.endswith("/shell/adapter/types")
)
if not is_seam_types:
if "/shell/" in import_path or import_path.endswith("/shell"):
return f"forbidden shell import: {import_path}"
if "/launcher/" in import_path or import_path.endswith("/launcher"):
return f"forbidden launcher import: {import_path}"
return None
#============================================
def _check_solid_violation_strict(import_path: str) -> str | None:
"""
Check if an import is a forbidden solid-js import (strict: no exceptions).
Used for pipeline/, validation/, generated/, and layout/ directories
where solid-js is never allowed.
Args:
import_path: The import string
Returns:
Violation reason string if violated, None if OK.
"""
if _is_solid_import(import_path):
return f"forbidden solid-js import: {import_path}"
return None
#============================================
def _check_solid_violation_protocol(
import_path: str,
is_type_only: bool,
) -> str | None:
"""
Check if an import violates the solid-js rule for the protocol/ stepper.
The stepper (protocol/) must not depend on solid-js as a runtime import.
Type-only imports of Solid types (import type ...) from the state layer
are explicitly permitted so the stepper can reference state types.
Args:
import_path: The import string
is_type_only: True if this import is an 'import type' statement
Returns:
Violation reason string if violated, None if OK.
"""
if not _is_solid_import(import_path):
return None
# Type-only imports are allowed in protocol/ (for state type references)
if is_type_only:
return None
return f"forbidden runtime solid-js import in protocol/: {import_path}"
#============================================
def _scan_directory_for_violations(
directory: str,
repo_root: str,
) -> list[tuple[str, str]]:
"""
Scan a directory for .ts/.tsx files and check for import violations.
Applies the layout/renderer boundary rules (both solid-js and shell/launcher).
Args:
directory: Path to scan (e.g., src/scene_runtime/layout/)
repo_root: Repository root for absolute path handling
Returns:
List of (filepath, violation_reason) tuples for files with violations
"""
violations: list[tuple[str, str]] = []
# Walk all .ts and .tsx files in the directory
for root, _dirs, files in os.walk(directory):
for filename in files:
if not (filename.endswith(".ts") or filename.endswith(".tsx")):
continue
filepath = os.path.join(root, filename)
rel_path = os.path.relpath(filepath, repo_root)
try:
with open(filepath, "r", encoding="utf-8") as handle:
content = handle.read()
except OSError as err:
violations.append((rel_path, f"read error: {err}"))
continue
imports = _extract_imports(content)
for imp in imports:
violation = _check_import_violation(imp)
if violation:
violations.append((rel_path, violation))
return violations
#============================================
def _scan_directory_for_solid_violations_strict(
directory: str,
repo_root: str,
) -> list[tuple[str, str]]:
"""
Scan a directory for solid-js imports (strict: no type-only exception).
Used for pipeline/, validation/, generated/ where solid-js is never allowed
regardless of import form.
Args:
directory: Path to scan
repo_root: Repository root
Returns:
List of (filepath, violation_reason) tuples
"""
violations: list[tuple[str, str]] = []
for root, _dirs, files in os.walk(directory):
for filename in files:
if not (filename.endswith(".ts") or filename.endswith(".tsx")):
continue
filepath = os.path.join(root, filename)
rel_path = os.path.relpath(filepath, repo_root)
try:
with open(filepath, "r", encoding="utf-8") as handle:
content = handle.read()
except OSError as err:
violations.append((rel_path, f"read error: {err}"))
continue
imports = _extract_imports(content)
for imp in imports:
violation = _check_solid_violation_strict(imp)
if violation:
violations.append((rel_path, violation))
return violations
#============================================
def _scan_protocol_directory_for_solid_violations(
directory: str,
repo_root: str,
) -> list[tuple[str, str]]:
"""
Scan the protocol/ directory for forbidden solid-js imports.
Type-only imports of solid-js types are permitted (for state type references).
Runtime solid-js imports are forbidden.
Args:
directory: Path to the protocol/ directory
repo_root: Repository root
Returns:
List of (filepath, violation_reason) tuples
"""
violations: list[tuple[str, str]] = []
for root, _dirs, files in os.walk(directory):
for filename in files:
if not (filename.endswith(".ts") or filename.endswith(".tsx")):
continue
filepath = os.path.join(root, filename)
rel_path = os.path.relpath(filepath, repo_root)
try:
with open(filepath, "r", encoding="utf-8") as handle:
content = handle.read()
except OSError as err:
violations.append((rel_path, f"read error: {err}"))
continue
# Gather type-only imports separately so we can exempt them
type_only_imports = set(_extract_type_only_imports(content))
all_imports = _extract_imports(content)
for imp in all_imports:
is_type_only = imp in type_only_imports
violation = _check_solid_violation_protocol(imp, is_type_only)
if violation:
violations.append((rel_path, violation))
return violations
#============================================
def test_no_solid_js_in_layout() -> None:
"""
Solid.js is FORBIDDEN in src/scene_runtime/layout/.
The layout engine is a pure pipeline that must not depend on the
reactive framework. Solid owns rendering; the layout engine owns geometry.
"""
import pytest
marker = _read_marker()
repo_root = _resolve_repo_root()
if marker != "typescript":
pytest.skip("repo is not typescript-typed")
layout_dir = os.path.join(repo_root, "src", "scene_runtime", "layout")
violations: list[tuple[str, str]] = []
# Only check if the directory exists; absence is not a failure
if os.path.isdir(layout_dir):
violations.extend(
_scan_directory_for_solid_violations_strict(layout_dir, repo_root)
)
if violations:
msg_lines = ["Solid.js boundary lint violations in layout/:"]
for filepath, reason in violations:
msg_lines.append(f" {filepath}: {reason}")
raise AssertionError("\n".join(msg_lines))
#============================================
def test_no_solid_js_in_pipeline() -> None:
"""
Solid.js is FORBIDDEN in pipeline/.
The build pipeline emits generated data; it must never depend on the
reactive framework.
"""
import pytest
marker = _read_marker()
repo_root = _resolve_repo_root()
if marker != "typescript":
pytest.skip("repo is not typescript-typed")
pipeline_dir = os.path.join(repo_root, "pipeline")
violations: list[tuple[str, str]] = []
# Only check if the directory exists; absence is not a failure
if os.path.isdir(pipeline_dir):
violations.extend(
_scan_directory_for_solid_violations_strict(pipeline_dir, repo_root)
)
if violations:
msg_lines = ["Solid.js boundary lint violations in pipeline/:"]
for filepath, reason in violations:
msg_lines.append(f" {filepath}: {reason}")
raise AssertionError("\n".join(msg_lines))
#============================================
def test_no_solid_js_in_validation() -> None:
"""
Solid.js is FORBIDDEN in validation/.
YAML validators and protocol stepper simulation are pure Python/TS;
they must not depend on the reactive framework.
"""
import pytest
marker = _read_marker()
repo_root = _resolve_repo_root()
if marker != "typescript":
pytest.skip("repo is not typescript-typed")
validation_dir = os.path.join(repo_root, "validation")
violations: list[tuple[str, str]] = []
# Only check if the directory exists; absence is not a failure
if os.path.isdir(validation_dir):
violations.extend(
_scan_directory_for_solid_violations_strict(validation_dir, repo_root)
)
if violations:
msg_lines = ["Solid.js boundary lint violations in validation/:"]
for filepath, reason in violations:
msg_lines.append(f" {filepath}: {reason}")
raise AssertionError("\n".join(msg_lines))
#============================================
def test_no_solid_js_in_generated() -> None:
"""
Solid.js is FORBIDDEN in generated/.
Generated data files carry YAML-compiled runtime data; they must not
import Solid.js. If a generated file starts importing Solid, a pipeline
generator has violated the layer boundary.
"""
import pytest
marker = _read_marker()
repo_root = _resolve_repo_root()
if marker != "typescript":
pytest.skip("repo is not typescript-typed")
generated_dir = os.path.join(repo_root, "generated")
violations: list[tuple[str, str]] = []
# Only check if the directory exists; absence is not a failure
if os.path.isdir(generated_dir):
violations.extend(
_scan_directory_for_solid_violations_strict(generated_dir, repo_root)
)
if violations:
msg_lines = ["Solid.js boundary lint violations in generated/:"]
for filepath, reason in violations:
msg_lines.append(f" {filepath}: {reason}")
raise AssertionError("\n".join(msg_lines))
#============================================
def test_no_solid_js_runtime_import_in_protocol() -> None:
"""
Runtime solid-js imports are FORBIDDEN in src/scene_runtime/protocol/.
The stepper (protocol/) calls store operations through a small runtime
bridge, never as a Solid component dependency. Type-only imports of
Solid types (import type ...) from the state layer are permitted so the
stepper can reference state types without a runtime dependency.
"""
import pytest
marker = _read_marker()
repo_root = _resolve_repo_root()
if marker != "typescript":
pytest.skip("repo is not typescript-typed")
protocol_dir = os.path.join(repo_root, "src", "scene_runtime", "protocol")
violations: list[tuple[str, str]] = []
# Only check if the directory exists; absence is not a failure
if os.path.isdir(protocol_dir):
violations.extend(
_scan_protocol_directory_for_solid_violations(protocol_dir, repo_root)
)
if violations:
msg_lines = [
"Solid.js runtime boundary lint violations in src/scene_runtime/protocol/:",
"(type-only imports are permitted; runtime imports are forbidden)",
]
for filepath, reason in violations:
msg_lines.append(f" {filepath}: {reason}")
raise AssertionError("\n".join(msg_lines))
#============================================
def test_no_shell_launcher_in_scene_runtime() -> None:
"""
No src/shell/ or src/launcher/ import in scene_runtime/layout/.
The layout engine must not depend on the shell or launcher layers.
shell/adapter/types is the one permitted seam exception (typed contract).
"""
import pytest
marker = _read_marker()
repo_root = _resolve_repo_root()
if marker != "typescript":
pytest.skip("repo is not typescript-typed")
layout_dir = os.path.join(repo_root, "src", "scene_runtime", "layout")
violations: list[tuple[str, str]] = []
if os.path.isdir(layout_dir):
violations.extend(_scan_directory_for_violations(layout_dir, repo_root))
if violations:
msg_lines = ["Boundary lint violations found:"]
for filepath, reason in violations:
msg_lines.append(f" {filepath}: {reason}")
raise AssertionError("\n".join(msg_lines))
#============================================
def test_solid_boundary_distinguishes_runtime_and_type_imports() -> None:
"""
Verify runtime Solid imports fail while type-only protocol imports remain valid.
"""
marker = _read_marker()
if marker != "typescript":
pytest.skip("repo is not typescript-typed")
runtime_violation = _check_solid_violation_protocol("solid-js", is_type_only=False)
type_violation = _check_solid_violation_protocol("solid-js", is_type_only=True)
assert (runtime_violation is not None, type_violation) == (True, None)
@pytest.mark.parametrize(
("module_parts", "expected_violation"),
[
(("src", "shell", "hud", "protocol_hud"), True),
(("src", "shell", "adapter", "types"), False),
(("src", "launcher", "launcher"), True),
],
)
def test_import_boundary_classifies_repo_modules(
module_parts: tuple[str, ...],
expected_violation: bool,
) -> None:
"""
Classify protected modules from paths anchored at the repository root.
"""
module_path = os.path.join(file_utils.get_repo_root(), *module_parts)
actual_violation = _check_import_violation(module_path) is not None
assert actual_violation is expected_violation