Type-check index boundaries and add coverage gates
Browse filesFiles changed (18)
- .coveragercAdded+9
- .dockerignore+11-1
- .gitignore+1
- Dockerfile+34
- build_fulltext_db.py+42-6
- jsconfig.service-worker.jsonAdded+14
- package-lock.jsonAdded+421
- package.jsonAdded+13
- prepare_fulltext_index.py+62-22
- pyrightconfig.jsonAdded+5
- requirements-coverage.txtAdded+1
- static/sw.js+11-7
- tests/test_coverage_gate.pyAdded+37
- tests/test_prepare_fulltext_index.py+16-6
- tests/test_search.py+3-2
- tests/test_service_worker.cjsAdded+38
- tests/test_static_checks.pyAdded+67
- tests/test_typed_contracts.pyAdded+88
123456789[run]branch = Truesource = .omit = tests/*, node_modules/*, .cache/*, CCRD/*, CW/*, data/*
[report]show_missing = Trueskip_covered = Falseprecision = 27 unmodified lines891011127 unmodified lines**/*.before-rebuild__pycache__/**/__pycache__/tests/.git/7 unmodified lines89101112131415161718192021227 unmodified lines**/*.before-rebuild__pycache__/**/__pycache__/tests/*!tests/__init__.py!tests/test_static_checks.py!tests/test_coverage_gate.py!tests/test_service_worker.cjs!tests/test_search.py!tests/test_prepare_fulltext_index.py!tests/test_ocr_release.py!tests/test_integration.py!tests/test_typed_contracts.py!tests/support.py.git/
10 unmodified lines11121314151610 unmodified lines.pytest_cache/.mypy_cache/.venv/env/tests/benchmark-results.jsontests/benchmark-results*.json10 unmodified lines1112131415161710 unmodified lines.pytest_cache/.mypy_cache/.venv/node_modules/env/tests/benchmark-results.jsontests/benchmark-results*.json
12310 unmodified lines141516171819FROM node:26.11.1-bookworm-slim AS static-assetsARG ESBUILD_VERSION=0.28.210 unmodified lines&& esbuild static/style.css --minify --outfile=/out/style.css \&& esbuild static/sw.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/sw.jsFROM python:3.11.17-slimWORKDIR /app1234567891011121314151617181920212223242526272829303132333410 unmodified lines454647484950515253FROM node:26.11.1-bookworm-slim AS static-check-nodeWORKDIR /checkCOPY package.json package-lock.json ./RUN npm ci --ignore-scripts --no-audit --no-fundCOPY jsconfig.service-worker.json ./COPY static/sw.js static/sw.jsRUN ./node_modules/.bin/tsc --project jsconfig.service-worker.jsonFROM python:3.11.17-slim AS static-check-pythonWORKDIR /checkRUN apt-get update && apt-get install -y --no-install-recommends libatomic1 \&& rm -rf /var/lib/apt/lists/*COPY requirements.txt requirements-coverage.txt ./RUN pip install --no-cache-dir -r requirements.txt -r requirements-coverage.txtCOPY --from=static-check-node /usr/local/bin/node /usr/local/bin/nodeCOPY --from=static-check-node /check/node_modules/ /check/node_modules/COPY --from=static-check-node /check/jsconfig.service-worker.json ./COPY --from=static-check-node /check/static/sw.js static/sw.jsCOPY pyrightconfig.json app.py build_fulltext_db.py prepare_fulltext_index.py ocr_release.py ./COPY Dockerfile .coveragerc ./COPY tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py tests/test_service_worker.cjs tests/RUN node node_modules/pyright/index.js --project pyrightconfig.jsonRUN mkdir -p data/initial data/sidebarCOPY tests/test_search.py tests/test_prepare_fulltext_index.py tests/test_ocr_release.py tests/test_integration.py tests/test_typed_contracts.py tests/support.py tests/RUN python -B -m unittest tests.test_static_checks tests.test_coverage_gate -v \&& node tests/test_service_worker.cjs \&& python -m coverage run -m unittest -q tests.test_search.TokenizationTests tests.test_prepare_fulltext_index tests.test_ocr_release tests.test_integration.FulltextIntegrationTests tests.test_typed_contracts tests.test_coverage_gate \&& python -m coverage report --fail-under=65FROM node:26.11.1-bookworm-slim AS static-assetsARG ESBUILD_VERSION=0.28.210 unmodified lines&& esbuild static/style.css --minify --outfile=/out/style.css \&& esbuild static/sw.js --minify --target=es2019 --charset=utf8 --legal-comments=none --outfile=/out/sw.js# A stage dependency makes strict Python checks mandatory for the final image.COPY --from=static-check-python /check/pyrightconfig.json /tmp/verified-pyrightconfig.jsonFROM python:3.11.17-slimWORKDIR /app
5 unmodified lines67891011123 unmodified lines161718192021222315 unmodified lines3940414243444549 unmodified lines959697989910010142 unmodified lines14414514614714814915060 unmodified lines2112122132142152162175 unmodified linesimport sqlite3import unicodedatafrom collections import defaultdictfrom pathlib import PathBASE_DIR = Path(__file__).resolve().parentDATA_PATH = BASE_DIR / "data/search_data.json.gz"FULLTEXT_DIR = BASE_DIR / "data/fulltext"3 unmodified linesTOKENIZER_VERSION = "cjk-bigram-boundary-fts5-v6-snippet-anchors"LITERAL_PREFIX = "\0literal:"def load_json_gz(path: Path):return json.loads(gzip.decompress(path.read_bytes()).decode("utf-8"))def decode_source_text(data: bytes) -> str:"""Strict UTF-8 first; a complete strict GB18030 decode is the only fallback.15 unmodified linesreturn decode_source_text(path.read_bytes())def index_tokens(text: str) -> set[str]:tokens = set()normalized = unicodedata.normalize("NFKC", text or "").casefold()for part in TOKEN_RE.findall(normalized):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", part):49 unmodified linesexcept (IndexError, ValueError) as exc:raise ValueError(f"doc_id must end with ':<number>': {doc_id}") from excdef get_doc_storage_path(record: dict) -> Path:return BASE_DIR / record["storage_root"] / record["storage_rel_path"]def build_summary(text: str) -> str:42 unmodified linesexcept Exception:return Falsedef build_source_db(source: str, source_records: list[dict]) -> None:db_path = FULLTEXT_DIR / f"{source}.sqlite3"if database_ready(db_path, len(source_records)):print(f"{source}: current index already ready", flush=True)60 unmodified linespayload = load_json_gz(DATA_PATH)records = payload.get("records", [])FULLTEXT_DIR.mkdir(parents=True, exist_ok=True)records_by_source: dict[str, list[dict]] = defaultdict(list)for record in records:records_by_source[record["source"]].append(record)STATUS_PATH.write_text(json.dumps({"state": "building"}), encoding="utf-8")5 unmodified lines678910111213143 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585915 unmodified lines7576777879808149 unmodified lines13113213313413513613742 unmodified lines18018118218318418518660 unmodified lines2472482492502512522535 unmodified linesimport sqlite3import unicodedatafrom collections import defaultdictfrom collections.abc import Sequencefrom pathlib import Pathfrom typing import TypedDict, castBASE_DIR = Path(__file__).resolve().parentDATA_PATH = BASE_DIR / "data/search_data.json.gz"FULLTEXT_DIR = BASE_DIR / "data/fulltext"3 unmodified linesTOKENIZER_VERSION = "cjk-bigram-boundary-fts5-v6-snippet-anchors"LITERAL_PREFIX = "\0literal:"class SourceRecord(TypedDict):doc_id: strstorage_root: strstorage_rel_path: strclass IndexedSourceRecord(SourceRecord):source: strclass SourcePayload(TypedDict, total=False):records: list[IndexedSourceRecord]def load_json_gz(path: Path) -> SourcePayload:# JSON is an untrusted boundary: validate fields actually consumed by the# builder before using the records as paths or document identifiers.payload: object = json.loads(gzip.decompress(path.read_bytes()).decode("utf-8"))if not isinstance(payload, dict):raise ValueError("fulltext data must be an object")fields = cast(dict[object, object], payload)raw_records = fields.get("records", [])if not isinstance(raw_records, list):raise ValueError("fulltext records must be a list")for value in cast(list[object], raw_records):if not isinstance(value, dict):raise ValueError("fulltext record must be an object")record = cast(dict[object, object], value)source = record.get("source")doc_id = record.get("doc_id")storage_root = record.get("storage_root")storage_rel_path = record.get("storage_rel_path")if not (isinstance(source, str) and isinstance(doc_id, str)and isinstance(storage_root, str) and isinstance(storage_rel_path, str)):raise ValueError("fulltext record fields must be strings")return cast(SourcePayload, payload)def decode_source_text(data: bytes) -> str:"""Strict UTF-8 first; a complete strict GB18030 decode is the only fallback.15 unmodified linesreturn decode_source_text(path.read_bytes())def index_tokens(text: str) -> set[str]:tokens: set[str] = set()normalized = unicodedata.normalize("NFKC", text or "").casefold()for part in TOKEN_RE.findall(normalized):if re.fullmatch(r"[\u4e00-\u9fff\u3400-\u4dbf]+", part):49 unmodified linesexcept (IndexError, ValueError) as exc:raise ValueError(f"doc_id must end with ':<number>': {doc_id}") from excdef get_doc_storage_path(record: SourceRecord) -> Path:return BASE_DIR / record["storage_root"] / record["storage_rel_path"]def build_summary(text: str) -> str:42 unmodified linesexcept Exception:return Falsedef build_source_db(source: str, source_records: Sequence[SourceRecord]) -> None:db_path = FULLTEXT_DIR / f"{source}.sqlite3"if database_ready(db_path, len(source_records)):print(f"{source}: current index already ready", flush=True)60 unmodified linespayload = load_json_gz(DATA_PATH)records = payload.get("records", [])FULLTEXT_DIR.mkdir(parents=True, exist_ok=True)records_by_source: dict[str, list[IndexedSourceRecord]] = defaultdict(list)for record in records:records_by_source[record["source"]].append(record)STATUS_PATH.write_text(json.dumps({"state": "building"}), encoding="utf-8")
1234567891011121314{ "compilerOptions": { "allowJs": true, "checkJs": true, "noEmit": true, "strict": true, "target": "ES2022", "lib": ["ES2022", "WebWorker"], "module": "ESNext", "moduleResolution": "bundler", "moduleDetection": "force" }, "files": ["static/sw.js"]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421{ "name": "ccrd-static-checks", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ccrd-static-checks", "devDependencies": { "pyright": "1.1.414", "typescript": "7.0.2" } }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", "cpu": [ "ppc64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "aix" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-darwin-arm64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", "cpu": [ "arm64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-darwin-x64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", "cpu": [ "x64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-freebsd-arm64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", "cpu": [ "arm64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-freebsd-x64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", "cpu": [ "x64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-arm": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", "cpu": [ "arm" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-arm64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", "cpu": [ "arm64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-loong64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", "cpu": [ "loong64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-mips64el": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", "cpu": [ "mips64el" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", "cpu": [ "ppc64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-riscv64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", "cpu": [ "riscv64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-s390x": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", "cpu": [ "s390x" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-linux-x64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", "cpu": [ "x64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-netbsd-arm64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", "cpu": [ "arm64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-netbsd-x64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", "cpu": [ "x64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-openbsd-arm64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", "cpu": [ "arm64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-openbsd-x64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", "cpu": [ "x64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-sunos-x64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", "cpu": [ "x64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "sunos" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-win32-arm64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", "cpu": [ "arm64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "win32" ], "engines": { "node": ">=16.20.0" } }, "node_modules/@typescript/typescript-win32-x64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", "cpu": [ "x64" ], "dev": true, "license": "Apache-2.0", "optional": true, "os": [ "win32" ], "engines": { "node": ">=16.20.0" } }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/pyright": { "version": "1.1.414", "resolved": "https://registry.npmjs.org/pyright/-/pyright-1.1.414.tgz", "integrity": "sha512-FPZZb51jepDX4eP7TEYDeNFtmE3WgwkkEcJpvH3/QmUSsj0EAy3LXu+xB4T/FWDejtsXlCfFr/rbWFjwuwuXww==", "dev": true, "license": "MIT", "bin": { "pyright": "index.js", "pyright-langserver": "langserver.index.js" }, "engines": { "node": ">=14.0.0" }, "optionalDependencies": { "fsevents": "~2.3.3" } }, "node_modules/typescript": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", "dev": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc" }, "engines": { "node": ">=16.20.0" }, "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" } } }}12345678910111213{ "name": "ccrd-static-checks", "private": true, "scripts": { "types": "pyright --project pyrightconfig.json && tsc --project jsconfig.service-worker.json", "test:static": "python -B -m unittest tests.test_static_checks -v && node tests/test_service_worker.cjs", "coverage": "python -m coverage run -m unittest tests.test_search.TokenizationTests tests.test_prepare_fulltext_index tests.test_ocr_release tests.test_integration.FulltextIntegrationTests tests.test_typed_contracts tests.test_coverage_gate && python -m coverage report --show-missing --fail-under=65" }, "devDependencies": { "pyright": "1.1.414", "typescript": "7.0.2" }}9 unmodified lines10111213141516 unmodified lines32333435363738394016 unmodified lines5758596061626329 unmodified lines9394959697989914 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391 unmodified line1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691708 unmodified lines1791801811821831841855 unmodified lines19119219319419519619727 unmodified lines2252262272282292302319 unmodified linesimport reimport sqlite3from pathlib import PathBASE_DIR = Path(__file__).resolve().parent16 unmodified linestemporary.replace(STATUS_PATH)def validated_database(bucket: Path, source: str, details: object) -> Path:if not isinstance(details, dict):raise ValueError(f"{source}: missing manifest details")relative_path = details.get("path")expected_hash = details.get("sha256")expected_documents = details.get("documents")16 unmodified linesreturn path, expected_bytesdef verify_database(path: Path, details: dict, *, expected_hash: str | None = None,expected_ids: set[str] | None = None) -> None:if path.stat().st_size != details["bytes"]:raise ValueError("database size mismatch")29 unmodified linesraise ValueError("newspaper document/text/FTS IDs differ")def copy_database(source: str, source_path: Path, details: dict, expected_ids: set[str] | None = None) -> Path:target = FULLTEXT_DIR / f"{source}.sqlite3"temporary = target.with_suffix(".sqlite3.bucket.tmp")temporary.unlink(missing_ok=True)14 unmodified linesdef metadata_contract() -> tuple[dict[str, int], str, dict[str, set[str]]]:raw = DATA_PATH.read_bytes()payload = json.loads(gzip.decompress(raw).decode("utf-8"))counts = {}ids = {}for record in payload.get("records", []):source = record["source"]counts[source] = counts.get(source, 0) + 1doc_id = record["doc_id"]if (not isinstance(doc_id, str) or not re.fullmatch(re.escape(source) + r":[0-9]+", doc_id)or doc_id in ids.setdefault(source, set())):raise ValueError("invalid or duplicate base metadata document ID")ids[source].add(doc_id)if set(counts) not in [set(SOURCES), set(SOURCES + NEWSPAPER_SOURCES)]:raise ValueError("base metadata must contain CCRD/CW or the complete four-source collection")declared = {source["slug"]: source["count"] for source in payload.get("sources", [])}if declared != counts:raise ValueError("base metadata source counts differ from its records")return counts, hashlib.sha256(raw).hexdigest(), idsdef manifest_databases(manifest: dict, expected: tuple[dict[str, int], str, dict[str, set[str]]] | None = None) -> dict:version = manifest.get("format")if type(version) is not int or version not in {1, 2} or manifest.get("tokenizer_version") != TOKENIZER_VERSION:raise ValueError("invalid manifest version")1 unmodified lineif expected is None:expected = metadata_contract()counts, metadata_sha, _ids = expectedif not isinstance(databases, dict) or set(databases) != set(counts):raise ValueError("missing databases manifest")if set(counts) == set(SOURCES + NEWSPAPER_SOURCES):if (version != 2 or manifest.get("kind") != "ccrd-four-source-generation"or manifest.get("base_metadata_sha256") != metadata_sha):raise ValueError("four-source generation does not pin the current base metadata")for source, count in counts.items():details = databases[source]if not isinstance(details, dict) or details.get("documents") != count:raise ValueError("four-source index document count differs from metadata")for source in NEWSPAPER_SOURCES:details = databases[source]if (details.get("source") != source or details.get("index_profile") != NEWSPAPER_INDEX_PROFILEor details.get("text_rows") != counts[source]):raise ValueError("missing newspaper index capabilities")elif version != 1:raise ValueError("unexpected manifest profile for CCRD/CW")return databasesdef selected_manifest(bucket: Path) -> tuple[dict, str]:if not ACTIVATION_PATH.exists():return json.loads((bucket / "current.json").read_text(encoding="utf-8")), "bucket-pointer"activation = json.loads(ACTIVATION_PATH.read_text(encoding="utf-8"))relative = activation.get("path")expected_hash = activation.get("sha256")if (activation.get("version") != 1 or activation.get("kind") != "ccrd-index-activation"8 unmodified linesraw = path.read_bytes()if hashlib.sha256(raw).hexdigest() != expected_hash:raise ValueError("pinned index manifest SHA-256 mismatch")manifest = json.loads(raw)if (manifest.get("format") != 2 or manifest.get("kind") != "ccrd-four-source-generation"or relative != f'generations/{manifest.get("generation")}/manifest.json'):raise ValueError("pinned index manifest generation differs from its immutable path")5 unmodified lineswrite_status(state="disabled", reason="no_mount_path")return 1bucket = Path(BUCKET_DIR).resolve()staged = {}expected = Nonetry:write_status(state="checking")27 unmodified lineswrite_status(state="unavailable", **pointer_error)return 1try:previous = manifest_databases(json.loads(LAST_GOOD_PATH.read_text(encoding="utf-8")), expected)for source in previous:ids = expected[2][source] if set(previous) == set(SOURCES + NEWSPAPER_SOURCES) else Noneverify_database(FULLTEXT_DIR / f"{source}.sqlite3", previous[source], expected_ids=ids)9 unmodified lines1011121314151616 unmodified lines3334353637383940414216 unmodified lines5960616263646529 unmodified lines959697989910010114 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611 unmodified line1631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072088 unmodified lines2172182192202212222235 unmodified lines22923023123223323423527 unmodified lines2632642652662672682692702719 unmodified linesimport reimport sqlite3from pathlib import Pathfrom typing import castBASE_DIR = Path(__file__).resolve().parent16 unmodified linestemporary.replace(STATUS_PATH)def validated_database(bucket: Path, source: str, details: object) -> tuple[Path, int]:if not isinstance(details, dict):raise ValueError(f"{source}: missing manifest details")details = cast(dict[str, object], details)relative_path = details.get("path")expected_hash = details.get("sha256")expected_documents = details.get("documents")16 unmodified linesreturn path, expected_bytesdef verify_database(path: Path, details: dict[str, object], *, expected_hash: str | None = None,expected_ids: set[str] | None = None) -> None:if path.stat().st_size != details["bytes"]:raise ValueError("database size mismatch")29 unmodified linesraise ValueError("newspaper document/text/FTS IDs differ")def copy_database(source: str, source_path: Path, details: dict[str, object], expected_ids: set[str] | None = None) -> Path:target = FULLTEXT_DIR / f"{source}.sqlite3"temporary = target.with_suffix(".sqlite3.bucket.tmp")temporary.unlink(missing_ok=True)14 unmodified linesdef metadata_contract() -> tuple[dict[str, int], str, dict[str, set[str]]]:raw = DATA_PATH.read_bytes()payload: object = json.loads(gzip.decompress(raw).decode("utf-8"))if not isinstance(payload, dict):raise ValueError("base metadata must be an object")metadata = cast(dict[object, object], payload)records = metadata.get("records", [])sources = metadata.get("sources", [])if not isinstance(records, list) or not isinstance(sources, list):raise ValueError("invalid base metadata lists")counts: dict[str, int] = {}ids: dict[str, set[str]] = {}for item in cast(list[object], records):if not isinstance(item, dict):raise ValueError("invalid base metadata record")record = cast(dict[object, object], item)source = record.get("source")if not isinstance(source, str):raise ValueError("invalid base metadata source")counts[source] = counts.get(source, 0) + 1doc_id = record.get("doc_id")if (not isinstance(doc_id, str) or not re.fullmatch(re.escape(source) + r":[0-9]+", doc_id)or doc_id in ids.setdefault(source, set())):raise ValueError("invalid or duplicate base metadata document ID")ids[source].add(doc_id)if set(counts) not in [set(SOURCES), set(SOURCES + NEWSPAPER_SOURCES)]:raise ValueError("base metadata must contain CCRD/CW or the complete four-source collection")declared: dict[str, int] = {}for item in cast(list[object], sources):if not isinstance(item, dict):raise ValueError("invalid base metadata source declaration")entry = cast(dict[object, object], item)slug, count = entry.get("slug"), entry.get("count")if not isinstance(slug, str) or type(count) is not int:raise ValueError("invalid base metadata source declaration")declared[slug] = countif declared != counts:raise ValueError("base metadata source counts differ from its records")return counts, hashlib.sha256(raw).hexdigest(), idsdef manifest_databases(manifest: dict[str, object], expected: tuple[dict[str, int], str, dict[str, set[str]]] | None = None) -> dict[str, dict[str, object]]:version = manifest.get("format")if type(version) is not int or version not in {1, 2} or manifest.get("tokenizer_version") != TOKENIZER_VERSION:raise ValueError("invalid manifest version")1 unmodified lineif expected is None:expected = metadata_contract()counts, metadata_sha, _ids = expectedif not isinstance(databases, dict):raise ValueError("missing databases manifest")raw_databases = cast(dict[object, object], databases)if set(raw_databases) != set(counts):raise ValueError("missing databases manifest")typed_databases: dict[str, dict[str, object]] = {}for source in counts:details = raw_databases[source]if not isinstance(details, dict):raise ValueError("invalid database manifest details")typed_databases[source] = cast(dict[str, object], details)if set(counts) == set(SOURCES + NEWSPAPER_SOURCES):if (version != 2 or manifest.get("kind") != "ccrd-four-source-generation"or manifest.get("base_metadata_sha256") != metadata_sha):raise ValueError("four-source generation does not pin the current base metadata")for source, count in counts.items():details = typed_databases[source]if details.get("documents") != count:raise ValueError("four-source index document count differs from metadata")for source in NEWSPAPER_SOURCES:details = typed_databases[source]if (details.get("source") != source or details.get("index_profile") != NEWSPAPER_INDEX_PROFILEor details.get("text_rows") != counts[source]):raise ValueError("missing newspaper index capabilities")elif version != 1:raise ValueError("unexpected manifest profile for CCRD/CW")return typed_databasesdef json_object(raw: str | bytes) -> dict[str, object]:value: object = json.loads(raw)if not isinstance(value, dict) or any(not isinstance(key, str) for key in cast(dict[object, object], value)):raise ValueError("manifest must be an object with string keys")return cast(dict[str, object], value)def selected_manifest(bucket: Path) -> tuple[dict[str, object], str]:if not ACTIVATION_PATH.exists():return json_object((bucket / "current.json").read_text(encoding="utf-8")), "bucket-pointer"activation = json_object(ACTIVATION_PATH.read_text(encoding="utf-8"))relative = activation.get("path")expected_hash = activation.get("sha256")if (activation.get("version") != 1 or activation.get("kind") != "ccrd-index-activation"8 unmodified linesraw = path.read_bytes()if hashlib.sha256(raw).hexdigest() != expected_hash:raise ValueError("pinned index manifest SHA-256 mismatch")manifest = json_object(raw)if (manifest.get("format") != 2 or manifest.get("kind") != "ccrd-four-source-generation"or relative != f'generations/{manifest.get("generation")}/manifest.json'):raise ValueError("pinned index manifest generation differs from its immutable path")5 unmodified lineswrite_status(state="disabled", reason="no_mount_path")return 1bucket = Path(BUCKET_DIR).resolve()staged: dict[str, Path] = {}expected = Nonetry:write_status(state="checking")27 unmodified lineswrite_status(state="unavailable", **pointer_error)return 1try:if expected is None:raise ValueError("base metadata unavailable")previous = manifest_databases(json_object(LAST_GOOD_PATH.read_text(encoding="utf-8")), expected)for source in previous:ids = expected[2][source] if set(previous) == set(SOURCES + NEWSPAPER_SOURCES) else Noneverify_database(FULLTEXT_DIR / f"{source}.sqlite3", previous[source], expected_ids=ids)
12345{ "include": ["build_fulltext_db.py", "prepare_fulltext_index.py"], "pythonVersion": "3.11", "typeCheckingMode": "strict"}1coverage==7.16.212341 unmodified line6789101112131415161718192021222324252627282930313214 unmodified lines47484950515253const CACHE_NAME = "vomebook-search-v1.0.0";const PRECACHE_URLS = ["/static/style.css",1 unmodified line"/manifest.json"];self.addEventListener("install", (event) => {event.waitUntil(caches.open(CACHE_NAME).then((cache) => {return cache.addAll(PRECACHE_URLS).catch((err) => {console.warn("[SW] precache partial failure:", err);});}).then(() => self.skipWaiting()));});self.addEventListener("activate", (event) => {event.waitUntil(caches.keys().then((keys) => {return Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)));}).then(() => self.clients.claim()));});self.addEventListener("fetch", (event) => {const url = new URL(event.request.url);if (url.hostname !== self.location.hostname || event.request.method !== "GET") {return;}const cacheable = url.pathname.startsWith("/static/")14 unmodified lines});}return response;}).catch(() => cached);return cached || fetchPromise;}));123451 unmodified line78910111213141516171819202122232425262728293031323314 unmodified lines48495051525354555657const CACHE_NAME = "vomebook-search-v1.0.0";const sw = /** @type {ServiceWorkerGlobalScope} */ (/** @type {unknown} */ (self));const PRECACHE_URLS = ["/static/style.css",1 unmodified line"/manifest.json"];sw.addEventListener("install", (event) => {event.waitUntil(caches.open(CACHE_NAME).then((cache) => {return cache.addAll(PRECACHE_URLS).catch((err) => {console.warn("[SW] precache partial failure:", err);});}).then(() => sw.skipWaiting()));});sw.addEventListener("activate", (event) => {event.waitUntil(caches.keys().then((keys) => {return Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)));}).then(() => sw.clients.claim()));});sw.addEventListener("fetch", (event) => {const url = new URL(event.request.url);if (url.hostname !== sw.location.hostname || event.request.method !== "GET") {return;}const cacheable = url.pathname.startsWith("/static/")14 unmodified lines});}return response;}).catch((error) => {if (cached) return cached;throw error;});return cached || fetchPromise;}));
12345678910111213141516171819202122232425262728293031323334353637"""A selective test run must not appear to cover the complete backend."""import jsonimport osfrom pathlib import Pathimport shutilimport subprocessimport sysimport tempfileimport unittest
ROOT = Path(__file__).resolve().parents[1]
class CoverageGateTests(unittest.TestCase): def test_unimported_backend_modules_are_reported_as_uncovered(self): with tempfile.TemporaryDirectory(prefix="ccrd-coverage-") as directory: root = Path(directory) shutil.copyfile(ROOT / ".coveragerc", root / ".coveragerc") for name in ("app.py", "build_fulltext_db.py", "prepare_fulltext_index.py", "ocr_release.py"): (root / name).write_text("value = 1\n") environment = {**os.environ, "COVERAGE_FILE": str(root / ".coverage"), "COVERAGE_RCFILE": str(root / ".coveragerc")} for command in ((sys.executable, "-m", "coverage", "run", "-m", "app"), (sys.executable, "-m", "coverage", "json", "-o", "coverage.json")): result = subprocess.run(command, cwd=root, env=environment, text=True, capture_output=True, timeout=30) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) thresholds = subprocess.run((sys.executable, "-m", "coverage", "report", "--fail-under=100"), cwd=root, env=environment, text=True, capture_output=True, timeout=30) self.assertNotEqual(thresholds.returncode, 0, thresholds.stdout) report = json.loads((root / "coverage.json").read_text()) self.assertEqual(set(report["files"]), {"app.py", "build_fulltext_db.py", "prepare_fulltext_index.py", "ocr_release.py"}) self.assertEqual(report["files"]["build_fulltext_db.py"]["summary"]["covered_lines"], 0)
if __name__ == "__main__": unittest.main()12345678910111220 unmodified lines33343536373815 unmodified lines5455565758596061626364import hashlibimport jsonimport osimport sqlite3import subprocessimport sysimport tempfileimport unittestfrom pathlib import PathROOT = Path(__file__).resolve().parents[1]20 unmodified linesself.generation = self.bucket / "generations/test"self.generation.mkdir(parents=True)self.fulltext = self.root / "fulltext"def tearDown(self):self.temporary.cleanup()15 unmodified lines}), encoding="utf-8")def run_prepare(self):environment = os.environ | {"CCRD_INDEX_BUCKET_DIR": str(self.bucket),"CCRD_FULLTEXT_DIR": str(self.fulltext),}return subprocess.run([sys.executable, str(PREPARE)], env=environment, capture_output=True, text=True)def test_activates_verified_bucket_generation(self):hashes = {12345678910111213141520 unmodified lines363738394041424344454615 unmodified lines62636465666768697071727374import hashlibimport gzipimport jsonimport sqlite3import subprocessimport sysimport tempfileimport unittestfrom pathlib import Pathfrom unittest.mock import patchimport prepare_fulltext_index as prepareROOT = Path(__file__).resolve().parents[1]20 unmodified linesself.generation = self.bucket / "generations/test"self.generation.mkdir(parents=True)self.fulltext = self.root / "fulltext"self.metadata = self.root / "metadata.json.gz"self.metadata.write_bytes(gzip.compress(json.dumps({"records": [{"source": source, "doc_id": f"{source}:1"} for source in ("CCRD", "CW")],"sources": [{"slug": source, "count": 1} for source in ("CCRD", "CW")],}).encode()))def tearDown(self):self.temporary.cleanup()15 unmodified lines}), encoding="utf-8")def run_prepare(self):# Execute in-process so branch coverage records the verifier as well.# Each path is isolated; production files and buckets are never touched.with patch.multiple(prepare, BUCKET_DIR=str(self.bucket), FULLTEXT_DIR=self.fulltext,DATA_PATH=self.metadata, ACTIVATION_PATH=self.root / "no-activation.json",STATUS_PATH=self.fulltext / "bucket-index-status.json",LAST_GOOD_PATH=self.fulltext / "last-known-good-manifest.json"):return subprocess.CompletedProcess([sys.executable, str(PREPARE)], prepare.main(), "", "")def test_activates_verified_bucket_generation(self):hashes = {
1362 unmodified lines136313641365136613671368136913701362 unmodified linesself.assertIn("esbuild static/style.css --minify", dockerfile)self.assertIn("esbuild static/sw.js --minify --target=es2019 --charset=utf8 --legal-comments=none", dockerfile)self.assertIn("COPY --from=static-assets /out/ static/", dockerfile)self.assertEqual(dockerfile.count("FROM node:"), 1)self.assertEqual(dockerfile.count("FROM python:"), 1)self.assertIn("COPY CCRD/ CCRD/", dockerfile)self.assertIn("COPY CW/ CW/", dockerfile)self.assertIn("COPY app.py build_fulltext_db.py prepare_fulltext_index.py start.sh ./", dockerfile)1362 unmodified lines1363136413651366136713681369137013711362 unmodified linesself.assertIn("esbuild static/style.css --minify", dockerfile)self.assertIn("esbuild static/sw.js --minify --target=es2019 --charset=utf8 --legal-comments=none", dockerfile)self.assertIn("COPY --from=static-assets /out/ static/", dockerfile)self.assertIn("AS static-check-node", dockerfile)self.assertIn("AS static-check-python", dockerfile)self.assertIn("COPY --from=static-check-python", dockerfile)self.assertIn("COPY CCRD/ CCRD/", dockerfile)self.assertIn("COPY CW/ CW/", dockerfile)self.assertIn("COPY app.py build_fulltext_db.py prepare_fulltext_index.py start.sh ./", dockerfile)
1234567891011121314151617181920212223242526272829303132333435363738const assert = require("node:assert/strict");const fs = require("node:fs");const vm = require("node:vm");const path = require("node:path");
const handlers = {};const response = { ok: true, status: 200, clone() { return this; } };let cached;let failNetwork = false;let calls = 0;const entries = new Map();const cache = { addAll: async () => {}, put: async (request, value) => entries.set(request.url, value) };const caches = { open: async () => cache, match: async () => cached, keys: async () => [], delete: async () => true };const self = { location: { hostname: "example.test" }, addEventListener: (type, fn) => { handlers[type] = fn; }, skipWaiting: async () => {}, clients: { claim: async () => {} } };const fetch = async () => { calls++; if (failNetwork) throw new Error("offline"); return response; };vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/sw.js"), "utf8"), { self, caches, fetch, URL, console });
async function dispatch(url, method = "GET") { let result; handlers.fetch({ request: { url, method }, respondWith(value) { result = value; } }); return result;}
(async () => { assert.equal(await dispatch("https://example.test/api/search"), undefined); assert.equal(await dispatch("https://other.test/static/app.js"), undefined); assert.equal(await dispatch("https://example.test/static/app.js", "POST"), undefined); assert.equal(calls, 0); cached = undefined; assert.equal(await dispatch("https://example.test/static/app.js"), response); cached = response; failNetwork = true; assert.equal(await dispatch("https://example.test/static/app.js"), response); cached = undefined; await assert.rejects(dispatch("https://example.test/static/app.js"), /offline/); console.log("CCRD service worker cache/network behavior passed");})().catch((error) => { console.error(error); process.exitCode = 1; });12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""The strict gates must reject type errors, not merely execute successfully."""import jsonfrom pathlib import Pathimport shutilimport subprocessimport tempfileimport unittest
ROOT = Path(__file__).resolve().parents[1]
class StaticChecksTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory(prefix="ccrd-static-") self.addCleanup(self.temporary.cleanup) self.root = Path(self.temporary.name) for name in ("pyrightconfig.json", "jsconfig.service-worker.json", "build_fulltext_db.py", "prepare_fulltext_index.py", "static/sw.js"): target = self.root / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / name, target) self.root.joinpath("node_modules").symlink_to(ROOT / "node_modules", target_is_directory=True)
def check(self, *command): return subprocess.run(command, cwd=self.root, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)
def test_strict_options_and_real_entry_injections(self): pyconfig = json.loads((self.root / "pyrightconfig.json").read_text()) jsconfig = json.loads((self.root / "jsconfig.service-worker.json").read_text()) self.assertEqual(pyconfig["typeCheckingMode"], "strict") self.assertTrue(jsconfig["compilerOptions"]["strict"]) self.assertTrue(jsconfig["compilerOptions"]["checkJs"]) checks = [ ("build_fulltext_db.py", '\n_bad_static_check: int = "wrong"\n', ("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")), ("prepare_fulltext_index.py", '\n_bad_static_check: int = "wrong"\n', ("node", str(ROOT / "node_modules/pyright/index.js"), "-p", "pyrightconfig.json")), ("static/sw.js", '\n/** @type {number} */ const badStaticCheck = "wrong";\n', ("node", str(ROOT / "node_modules/typescript/bin/tsc"), "-p", "jsconfig.service-worker.json")), ] for filename, fault, command in checks: with self.subTest(filename=filename): path = self.root / filename original = path.read_text() baseline = self.check(*command) self.assertEqual(baseline.returncode, 0, baseline.stdout) path.write_text(original + fault) injected = self.check(*command) self.assertNotEqual(injected.returncode, 0, injected.stdout) self.assertIn("error", injected.stdout.lower()) path.write_text(original)
def test_release_image_depends_on_both_strict_checks(self): dockerfile = (ROOT / "Dockerfile").read_text() self.assertIn("tsc --project jsconfig.service-worker.json", dockerfile) self.assertIn("pyright/index.js --project pyrightconfig.json", dockerfile) self.assertIn("COPY --from=static-check-python", dockerfile) self.assertIn("unittest tests.test_static_checks", dockerfile) self.assertIn("node tests/test_service_worker.cjs", dockerfile) self.assertIn("tests.test_coverage_gate", dockerfile) self.assertIn("tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py", dockerfile) self.assertIn("python -m coverage report --fail-under=65", dockerfile)
if __name__ == "__main__": unittest.main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import gzipimport jsonfrom pathlib import Pathimport tempfileimport unittestfrom unittest.mock import patch
import build_fulltext_db as builderimport prepare_fulltext_index as prepare
class TypedBoundaryTests(unittest.TestCase): def test_database_reference_requires_size_and_stays_in_bucket(self): with tempfile.TemporaryDirectory() as directory: bucket = Path(directory).resolve() target = bucket / "generations/test/CCRD.sqlite3" target.parent.mkdir(parents=True) target.write_bytes(b"index") details = {"path": "generations/test/CCRD.sqlite3", "sha256": "a" * 64, "documents": 1, "fts_rows": 1, "bytes": 5} self.assertEqual(prepare.validated_database(bucket, "CCRD", details), (target, 5)) for updates in ({"path": "generations/../../outside"}, {"bytes": True}, {"bytes": 0}, {"fts_rows": 2}, {"sha256": "bad"}): with self.subTest(updates=updates), self.assertRaises(ValueError): prepare.validated_database(bucket, "CCRD", {**details, **updates})
def test_manifest_object_and_immutable_selection(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) activation_path = root / "activation.json" self.assertEqual(prepare.json_object('{"format": 1}'), {"format": 1}) manifest = {"format": 2, "kind": "ccrd-four-source-generation", "generation": "ccrd-four-" + "a" * 64} relative = f'generations/{manifest["generation"]}/manifest.json' target = root / relative target.parent.mkdir(parents=True) raw = json.dumps(manifest).encode() target.write_bytes(raw) activation = {"version": 1, "kind": "ccrd-index-activation", "bucket": "vomebook/ccrd-index", "path": relative, "sha256": prepare.hashlib.sha256(raw).hexdigest()} activation_path.write_text(json.dumps(activation)) with patch.object(prepare, "ACTIVATION_PATH", activation_path): self.assertEqual(prepare.selected_manifest(root), (manifest, "space-activation")) activation["sha256"] = "f" * 64 activation_path.write_text(json.dumps(activation)) with self.assertRaisesRegex(ValueError, "SHA-256"): prepare.selected_manifest(root)
def test_builder_metadata_boundary_rejects_malformed_records(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "records.json.gz" record = {"source": "CCRD", "doc_id": "CCRD:1", "storage_root": "CCRD", "storage_rel_path": "one.txt", "extra": "preserved"} for value in ([], {"records": {}}, {"records": [None]}, {"records": [{**record, "storage_rel_path": 42}]}): with self.subTest(value=value): path.write_bytes(gzip.compress(json.dumps(value).encode())) with self.assertRaises(ValueError): builder.load_json_gz(path) path.write_bytes(gzip.compress(json.dumps({"records": [record], "extra": 5}).encode())) payload = builder.load_json_gz(path) self.assertEqual(payload["records"][0]["extra"], "preserved") self.assertEqual(payload["extra"], 5)
def test_index_metadata_contract_rejects_bad_sources_and_duplicate_ids(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "records.json.gz" records = [{"source": "CCRD", "doc_id": "CCRD:1"}, {"source": "CW", "doc_id": "CW:1"}] sources = [{"slug": "CCRD", "count": 1}, {"slug": "CW", "count": 1}] with patch.object(prepare, "DATA_PATH", path): for payload in ({"records": records + [records[0]], "sources": sources}, {"records": records, "sources": [{"slug": "CCRD", "count": "1"}]}, {"records": [{"source": 5}], "sources": sources}): path.write_bytes(gzip.compress(json.dumps(payload).encode())) with self.subTest(payload=payload), self.assertRaises(ValueError): prepare.metadata_contract() path.write_bytes(gzip.compress(json.dumps({"records": records, "sources": sources}).encode())) counts, _sha, ids = prepare.metadata_contract() self.assertEqual(counts, {"CCRD": 1, "CW": 1}) self.assertEqual(ids, {"CCRD": {"CCRD:1"}, "CW": {"CW:1"}})
def test_manifest_json_rejects_non_object(self): for raw in ('[]', 'null', '123'): with self.subTest(raw=raw), self.assertRaises(ValueError): prepare.json_object(raw)
if __name__ == "__main__": unittest.main().coveragercAdded+9
.dockerignore+11-1
.gitignore+1
Dockerfile+34
build_fulltext_db.py+42-6
jsconfig.service-worker.jsonAdded+14
package-lock.jsonAdded+421
package.jsonAdded+13
prepare_fulltext_index.py+62-22
pyrightconfig.jsonAdded+5
requirements-coverage.txtAdded+1
static/sw.js+11-7
tests/test_coverage_gate.pyAdded+37
tests/test_prepare_fulltext_index.py+16-6
tests/test_search.py+3-2
tests/test_service_worker.cjsAdded+38
tests/test_static_checks.pyAdded+67
tests/test_typed_contracts.pyAdded+88