Compare commits

..

No commits in common. "648bde44b1756485d95ca3c3a8714cd2015d5be4" and "b3c9611af212880301ca79ed21f909bc4640f81f" have entirely different histories.

37 changed files with 9 additions and 2092 deletions

View File

@ -1,36 +0,0 @@
name: data_transfer_flutter tests
on:
push:
branches: [main]
paths: ['data_transfer_flutter/**']
pull_request:
branches: [main]
paths: ['data_transfer_flutter/**']
jobs:
test:
runs-on: ubuntu-latest
defaults:
run:
working-directory: data_transfer_flutter
steps:
- uses: actions/checkout@v4
- name: Set up Flutter
uses: subosito/flutter-action@v2
with:
channel: stable
- name: Install dependencies
run: flutter pub get
- name: Analyze
run: flutter analyze
- name: Run tests with coverage
run: flutter test --coverage
- name: Enforce 100% line coverage
run: scripts/check_coverage.sh coverage/lcov.info 100

View File

@ -11,8 +11,8 @@ overwrite it with `repo_contract/templates/check_repo_contract.shim.sh`.
## Commands
- run: n/a: collection of gates and libraries, no single entry point
- test: `PYTHONPATH=. python -m pytest -q agent_ready/tests coverage_gaps/tests dep_freshness/tests file_length/tests flutter_web_drive/tests home_paths/tests md_naming/tests repo_contract/tests scripts/tests unified-design-system/tests`
- test: `PYTHONPATH=. python -m pytest -q agent_ready/tests coverage_gaps/tests dep_freshness/tests file_length/tests flutter_web_drive/tests home_paths/tests md_naming/tests repo_contract/tests scripts/tests`
- test-changed: `scripts/test_changed.sh`
- lint: `ruff check agent_ready coverage_gaps flutter_web_drive repo_contract`
- coverage: `PYTHONPATH=. python -m pytest -q agent_ready/tests flutter_web_drive/tests repo_contract/tests unified-design-system/tests --cov=agent_ready --cov=flutter_web_drive --cov=repo_contract --cov=conformance --cov=conformance_diff --cov-branch --cov-report=xml --cov-fail-under=100`
- coverage: `PYTHONPATH=. python -m pytest -q agent_ready/tests flutter_web_drive/tests repo_contract/tests --cov=agent_ready --cov=flutter_web_drive --cov=repo_contract --cov-branch --cov-report=xml --cov-fail-under=100`
- coverage-gaps: `coverage-gaps coverage.xml`

View File

@ -1,41 +0,0 @@
# Encrypt crdt_sync payloads end to end
## what
Firebase RTDB stores every crdt_sync record in plaintext, so Google can read
all app data. Encrypt record payloads on the device before push and decrypt
after pull, so RTDB stays a blind relay (the "ownership" meaning of
local-first: hologram.page/blog/local-first-means-three-different-things).
## open decisions (ask kuhy before coding)
- Key source: derived from the shared crdt-sync password (Argon2id) or a
random key stored in the OS keystore and copied to new devices.
- Migration: re-encrypt existing logs in place, or new prefix + one-time copy.
- Scope: payload only (keep HLC/ids clear for merge) or whole record.
- diet_guard's `export_keys` document (random data-export keys, synced as a
keyring) sits in plaintext in RTDB, so Firebase can read them: it must move
under E2E too, with its key source decided here first.
- tutor uses its own RTDB client (`~/src/tutor/app/lib/sync/rtdb_client.dart`):
in or out of scope.
## steps
1. Add an encrypt/decrypt seam in `crdt_sync_dart/lib/src/remote_store.dart`
(push/pull), AEAD (XChaCha20-Poly1305), version byte per record.
2. Property test: decrypt(encrypt(r)) == r; merge result identical with and
without encryption (see property-and-differential-tests skill).
3. Read path accepts plaintext and v1 records during migration.
4. Roll out app by app (todo first), bump pins, verify on the phone.
## done
`dart test` in `crdt_sync_dart` passes, and
`firebase database:get /<prefix> | grep -c '"title"'` returns 0 for every
migrated app.
## verify
Pixel 6a + desktop todo: edit on one, see it on the other; raw RTDB JSON shows
only ciphertext.
## read first
- `crdt_sync_dart/lib/src/sync.dart`, `log.dart`, `remote_store.dart`
- `crdt_sync_flutter/lib/src/bootstrap.dart`
REMOVE ME AFTER FINISH

View File

@ -1,6 +0,0 @@
.dart_tool/
.packages
build/
pubspec.lock
coverage/
*.iml

View File

@ -1,66 +0,0 @@
# Pre-commit Configuration for data_transfer_flutter
# Install: pre-commit install && pre-commit install --hook-type pre-push
# Run: pre-commit run --all-files
# NOTE: this subproject lives inside the ~/src/utils monorepo, whose git root is
# one level up. pre-commit always runs hooks from the git root, so every path
# below is written relative to THAT, not to this directory, and the top-level
# `files` key keeps these hooks off the sibling subprojects. CI invokes this
# config exactly the same way:
# pre-commit run --config data_transfer_flutter/.pre-commit-config.yaml --all-files
files: ^data_transfer_flutter/
default_stages: [pre-commit]
fail_fast: false
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
- id: end-of-file-fixer
- id: check-yaml
- id: check-merge-conflict
- id: mixed-line-ending
args: [--fix=lf]
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash scripts/check_file_length.sh
language: system
pass_filenames: true
- id: subproject-scope
name: subproject scope regex still matches
entry: scripts/check_subproject_scope.sh data_transfer_flutter
language: script
# always_run so the top-level `files` filter cannot skip the one hook
# whose job is to notice that filter has stopped matching anything.
always_run: true
pass_filenames: false
- id: no-crdt-sync-override
name: no local dependency_overrides on a utils git dependency
entry: scripts/check_no_crdt_sync_override.sh data_transfer_flutter/pubspec.yaml
language: script
pass_filenames: false
- id: dart-format
name: dart format --set-exit-if-changed
entry: bash -c 'cd data_transfer_flutter && dart format --set-exit-if-changed lib test'
language: system
pass_filenames: false
- id: flutter-analyze
name: flutter analyze
entry: bash -c 'cd data_transfer_flutter && flutter analyze'
language: system
pass_filenames: false
- id: flutter-test-coverage
name: flutter test --coverage with 100% line-coverage gate
entry: >-
bash -c 'cd data_transfer_flutter && flutter test --coverage &&
scripts/check_coverage.sh coverage/lcov.info 100'
language: system
pass_filenames: false
require_serial: true
stages: [pre-push]

View File

@ -1,38 +0,0 @@
# data_transfer_flutter
Shared "export to a JSON file / import from a JSON file" plumbing for kuhy's
Flutter apps. Apps keep their own export CONTENT; this owns the file plumbing
and the envelope.
## Install
```yaml
dependencies:
data_transfer_flutter:
git:
url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.0
path: data_transfer_flutter
```
## Use
```dart
final saved = await exportJson(fileName: 'x.json', json: envelope);
final map = await pickJson(); // null when cancelled
```
- `exportJson` / `exportJsonText` save to **device storage**: Android and iOS
use the system "Save as" document picker (`file_picker` `saveFile`, i.e.
ACTION_CREATE_DOCUMENT), desktop a save dialog (`file_selector`), web a
browser download. Returns false when cancelled.
- `exportTextFile` does the same for any text (`text/csv`, `text/calendar`).
- `shareJson` is an optional second action (share sheet). It is never the
only way out: a stock phone's share sheet has no local save target.
- `pickJson` / `pickJsonText` use the system open-document picker.
- `buildEnvelope` / `validateEnvelope` / `parseEnvelope` write and check
`{format, version, exported_at, ...}`; mismatches throw a typed
`EnvelopeException` (always a `FormatException`).
Tests fake `DataTransfer.platform` (a `DataTransferPlatform`); restore it in
`tearDown`.

View File

@ -1,38 +0,0 @@
include: package:very_good_analysis/analysis_options.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
errors:
# Promote key lints to errors so they fail CI, not just warn.
missing_required_param: error
unnecessary_null_comparison: error
dead_code: error
invalid_annotation_target: error
exclude:
- build/**
- "**/*.g.dart"
- "**/*.freezed.dart"
- "test/**"
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:
# very_good_analysis enables most rules; add extras it doesn't include.
always_use_package_imports: true
avoid_print: true
avoid_relative_lib_imports: true
cancel_subscriptions: true
close_sinks: true
comment_references: false # conflicts with typical Flutter API docs style
directives_ordering: true
lines_longer_than_80_chars: true
public_member_api_docs: true
unawaited_futures: true

View File

@ -1,7 +0,0 @@
/// Shared JSON export/import plumbing: save, share, pick and a versioned
/// envelope.
library;
export 'src/envelope.dart';
export 'src/platform.dart';
export 'src/transfer.dart';

View File

@ -1,118 +0,0 @@
import 'dart:convert';
/// Why a file is not an acceptable export envelope.
///
/// Always a [FormatException], so callers that only care about "bad file"
/// can keep catching that.
sealed class EnvelopeException implements FormatException {
const EnvelopeException(this.message);
@override
final String message;
@override
dynamic get source => null;
@override
int? get offset => null;
@override
String toString() => 'EnvelopeException: $message';
}
/// The text is not JSON at all.
final class EnvelopeInvalidJson extends EnvelopeException {
/// Creates the error.
const EnvelopeInvalidJson() : super('not valid JSON');
}
/// The JSON is valid but its top level is not an object.
final class EnvelopeNotObject extends EnvelopeException {
/// Creates the error.
const EnvelopeNotObject() : super('export is not a JSON object');
}
/// The `format` marker is missing or names another kind of file.
final class EnvelopeFormatMismatch extends EnvelopeException {
/// Creates the error for a file marked [actual] when [expected] was needed.
EnvelopeFormatMismatch({required this.expected, required this.actual})
: super('not a $expected file (found "$actual")');
/// The format the caller accepts.
final String expected;
/// The format the file declared, `null` when it declared none.
final Object? actual;
}
/// The `version` is missing or differs from the one the caller reads.
final class EnvelopeVersionMismatch extends EnvelopeException {
/// Creates the error for a file at version [actual] when [expected] was
/// needed.
EnvelopeVersionMismatch({required this.expected, required this.actual})
: super('unsupported version $actual (expected $expected)');
/// The version the caller reads.
final int expected;
/// The version the file declared, `null` when it declared none.
final Object? actual;
}
/// Builds `{format, version, exported_at, ...body}`, in that key order.
///
/// [now] is converted to UTC. Throws [ArgumentError] when [body] reuses an
/// envelope key, which would silently corrupt the marker.
Map<String, Object?> buildEnvelope({
required String format,
required int version,
required DateTime now,
Map<String, Object?> body = const {},
}) {
const reserved = {'format', 'version', 'exported_at'};
final clash = body.keys.where(reserved.contains).toList();
if (clash.isNotEmpty) {
throw ArgumentError.value(body, 'body', 'reuses envelope keys: $clash');
}
return <String, Object?>{
'format': format,
'version': version,
'exported_at': now.toUtc().toIso8601String(),
...body,
};
}
/// Returns [decoded] when it is an object marked [format] at [version].
///
/// Throws an [EnvelopeException] subtype otherwise.
Map<String, Object?> validateEnvelope(
Object? decoded, {
required String format,
required int version,
}) {
if (decoded is! Map<String, Object?>) throw const EnvelopeNotObject();
final actualFormat = decoded['format'];
if (actualFormat != format) {
throw EnvelopeFormatMismatch(expected: format, actual: actualFormat);
}
final actualVersion = decoded['version'];
if (actualVersion != version) {
throw EnvelopeVersionMismatch(expected: version, actual: actualVersion);
}
return decoded;
}
/// Decodes [text] and runs [validateEnvelope] on it.
Map<String, Object?> parseEnvelope(
String text, {
required String format,
required int version,
}) {
final Object? decoded;
try {
decoded = jsonDecode(text);
} on FormatException {
throw const EnvelopeInvalidJson();
}
return validateEnvelope(decoded, format: format, version: version);
}

View File

@ -1,27 +0,0 @@
import 'package:file_selector/file_selector.dart';
/// The type group the open and save dialogs restrict to.
const jsonTypeGroup = XTypeGroup(
label: 'JSON',
extensions: ['json'],
// Needed by the macOS/iOS pickers and harmless elsewhere; a group with no
// recognised identifier silently matches nothing on those hosts.
uniformTypeIdentifiers: ['public.json'],
mimeTypes: ['application/json'],
);
/// The save-dialog filter for [fileName] holding [mimeType] data.
///
/// Keyed on the file's own extension so a CSV export is not offered under a
/// JSON filter; a name with no extension accepts any type.
XTypeGroup saveTypeGroup(String fileName, String mimeType) {
final dot = fileName.lastIndexOf('.');
final extension = dot > 0 && dot < fileName.length - 1
? fileName.substring(dot + 1).toLowerCase()
: null;
return XTypeGroup(
label: extension?.toUpperCase(),
extensions: extension == null ? null : [extension],
mimeTypes: [mimeType],
);
}

View File

@ -1,32 +0,0 @@
/// What differs per host: where the bytes of an export go and come from.
///
/// The seam tests fake. Real implementations live in `platform_io.dart`
/// (Android, iOS, desktop) and `platform_web.dart`, chosen by
/// `platform_default.dart` so no `dart:io` import reaches a web build.
abstract interface class DataTransferPlatform {
/// Saves [text] as [fileName] where the user can find it again.
///
/// Android/iOS: the system "Save as" document picker (device storage).
/// Desktop: a save dialog. Web: a browser download. Returns false when the
/// user cancelled.
Future<bool> saveText({
required String fileName,
required String text,
String mimeType = 'application/json',
});
/// Offers [text] as [fileName] to the share sheet, where the host has one.
///
/// A second action only: a share sheet can route the data to cloud apps, so
/// it never replaces [saveText]. Hosts without a sheet fall back to
/// [saveText].
Future<bool> shareText({
required String fileName,
required String text,
String mimeType = 'application/json',
});
/// Opens the system open-document picker and returns the file's text, or
/// null when the user cancelled.
Future<String?> pickText();
}

View File

@ -1,3 +0,0 @@
export 'platform_io.dart'
if (dart.library.js_interop) 'platform_web.dart'
show createDefaultPlatform;

View File

@ -1,120 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:data_transfer_flutter/src/json_type_group.dart';
import 'package:data_transfer_flutter/src/platform.dart';
import 'package:file_picker/file_picker.dart';
import 'package:file_selector/file_selector.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
/// Writes [bytes] through the system "Save as" picker; false on cancel.
typedef DocumentSaver =
Future<bool> Function({
required String fileName,
required Uint8List bytes,
required String mimeType,
});
/// Offers [text] as a file named [fileName] to the share sheet.
typedef SheetSharer =
Future<bool> Function({
required String fileName,
required String text,
required String mimeType,
});
/// The platform for hosts that have `dart:io`.
DataTransferPlatform createDefaultPlatform() => IoDataTransferPlatform();
/// Android, iOS and desktop.
///
/// Mobile saves through the Storage Access Framework / document picker
/// (`file_picker`'s `saveFile`), because the share sheet on a stock phone has
/// no local save target and an export that can only be shared is an upload.
/// Desktop uses `file_selector`'s save dialog. Opening is `file_selector`'s
/// `openFile` everywhere: ACTION_OPEN_DOCUMENT on Android.
class IoDataTransferPlatform implements DataTransferPlatform {
/// Creates the platform; every argument is a test seam.
IoDataTransferPlatform({
bool? isMobile,
DocumentSaver? documentSaver,
SheetSharer? sheetSharer,
}) : _isMobile = isMobile ?? (Platform.isAndroid || Platform.isIOS),
_documentSaver = documentSaver ?? _saveViaDocumentPicker,
_sheetSharer = sheetSharer ?? _shareViaSheet;
final bool _isMobile;
final DocumentSaver _documentSaver;
final SheetSharer _sheetSharer;
@override
Future<bool> saveText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) async {
if (_isMobile) {
return await _documentSaver(
fileName: fileName,
bytes: Uint8List.fromList(utf8.encode(text)),
mimeType: mimeType,
);
}
final location = await getSaveLocation(
suggestedName: fileName,
acceptedTypeGroups: [saveTypeGroup(fileName, mimeType)],
);
if (location == null) return false;
await File(location.path).writeAsString(text);
return true;
}
@override
Future<bool> shareText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) => _isMobile
? _sheetSharer(fileName: fileName, text: text, mimeType: mimeType)
: saveText(fileName: fileName, text: text, mimeType: mimeType);
@override
Future<String?> pickText() async {
final file = await openFile(acceptedTypeGroups: const [jsonTypeGroup]);
return await file?.readAsString();
}
}
// coverage:ignore-start
// Real plugin calls: unreachable on the Linux test host (a platform channel
// answers nothing there) and faked at the typedef seams above instead.
Future<bool> _saveViaDocumentPicker({
required String fileName,
required Uint8List bytes,
required String mimeType,
}) async {
final saved = await FilePicker.saveFile(
fileName: fileName,
bytes: bytes,
mimeType: mimeType,
);
return saved != null;
}
Future<bool> _shareViaSheet({
required String fileName,
required String text,
required String mimeType,
}) async {
final dir = await getTemporaryDirectory();
final file = File(p.join(dir.path, fileName));
await file.writeAsString(text);
await SharePlus.instance.share(
ShareParams(files: [XFile(file.path, mimeType: mimeType)]),
);
return true;
}
// coverage:ignore-end

View File

@ -1,43 +0,0 @@
import 'dart:convert';
import 'package:data_transfer_flutter/src/json_type_group.dart';
import 'package:data_transfer_flutter/src/platform.dart';
import 'package:file_selector/file_selector.dart';
/// The browser's platform: downloads and the open-file dialog.
DataTransferPlatform createDefaultPlatform() => const WebDataTransferPlatform();
/// Browser implementation. No share sheet; download covers both actions.
class WebDataTransferPlatform implements DataTransferPlatform {
/// Creates the platform.
const WebDataTransferPlatform();
@override
Future<bool> saveText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) async {
// `saveTo` on web clicks a synthetic anchor: the path is ignored and the
// browser's download UI decides where the file lands.
await XFile.fromData(
utf8.encode(text),
mimeType: mimeType,
name: fileName,
).saveTo('');
return true;
}
@override
Future<bool> shareText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) => saveText(fileName: fileName, text: text, mimeType: mimeType);
@override
Future<String?> pickText() async {
final file = await openFile(acceptedTypeGroups: const [jsonTypeGroup]);
return await file?.readAsString();
}
}

View File

@ -1,65 +0,0 @@
import 'dart:convert';
import 'package:data_transfer_flutter/src/envelope.dart';
import 'package:data_transfer_flutter/src/platform.dart';
import 'package:data_transfer_flutter/src/platform_default.dart';
/// Holds the platform the top-level functions use; tests replace it.
abstract final class DataTransfer {
/// The active platform. Defaults to the host's real implementation.
static DataTransferPlatform platform = createDefaultPlatform();
}
const _pretty = JsonEncoder.withIndent(' ');
/// Saves [json] as [fileName] to device storage (see
/// [DataTransferPlatform.saveText]). False when the user cancelled.
Future<bool> exportJson({
required String fileName,
required Map<String, Object?> json,
}) => exportJsonText(fileName: fileName, text: _pretty.convert(json));
/// [exportJson] for an already-encoded JSON string.
Future<bool> exportJsonText({required String fileName, required String text}) =>
exportTextFile(fileName: fileName, text: text);
/// Saves any text file ([mimeType], e.g. `text/csv`) to device storage, with
/// the same host behaviour as [exportJson]. False when cancelled.
Future<bool> exportTextFile({
required String fileName,
required String text,
String mimeType = 'application/json',
}) => DataTransfer.platform.saveText(
fileName: fileName,
text: text,
mimeType: mimeType,
);
/// Optional second action: offers [json] to the share sheet.
Future<bool> shareJson({
required String fileName,
required Map<String, Object?> json,
}) => DataTransfer.platform.shareText(
fileName: fileName,
text: _pretty.convert(json),
);
/// Lets the user pick a JSON file and decodes it; null when cancelled.
///
/// Throws [EnvelopeInvalidJson] / [EnvelopeNotObject] for a file that is not
/// a JSON object.
Future<Map<String, Object?>?> pickJson() async {
final text = await pickJsonText();
if (text == null) return null;
final Object? decoded;
try {
decoded = jsonDecode(text);
} on FormatException {
throw const EnvelopeInvalidJson();
}
if (decoded is! Map<String, Object?>) throw const EnvelopeNotObject();
return decoded;
}
/// Lets the user pick a file and returns its raw text; null when cancelled.
Future<String?> pickJsonText() => DataTransfer.platform.pickText();

View File

@ -1,28 +0,0 @@
name: data_transfer_flutter
description: >-
Shared "export to a JSON file / import from a JSON file" plumbing for kuhy's
Flutter apps: system Save-as on Android/iOS (never cloud-only), a save
dialog on desktop, a download on web, plus a versioned export envelope.
publish_to: 'none'
version: 0.2.0
environment:
sdk: ^3.12.2
dependencies:
file_picker: 13.3.1
file_selector: 1.1.0
flutter:
sdk: flutter
path: 1.9.1
path_provider: 2.1.6
share_plus: 13.3.1
dev_dependencies:
file_selector_platform_interface: 2.7.0
flutter_test:
sdk: flutter
plugin_platform_interface: 2.1.8
very_good_analysis: ^11.0.0
flutter:

View File

@ -1,32 +0,0 @@
#!/bin/bash
# ============================================================================
# Fail if lcov line coverage drops below a threshold.
#
# Thin delegate to the shared gate in ~/src/utils/scripts, which owns the parsing
# and the threshold comparison. This file used to be a byte-identical copy of
# that logic; three such copies existed, which is how one package's idea of
# "covered" drifts from every other package's.
#
# Usage: check_coverage.sh <lcov.info> <min_percent>
# ============================================================================
set -euo pipefail
# Repo-relative, resolved from this script's own location: an absolute
# /home/... path exits 127 on an Actions runner.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly SHARED_GATE="${SCRIPT_DIR}/../../scripts/check_coverage.sh"
main() {
if [[ ! -f "$SHARED_GATE" ]]; then
echo "Error: shared coverage gate not found at $SHARED_GATE" >&2
echo " It lives in the utils repo at scripts/check_coverage.sh." >&2
exit 1
fi
exec bash "$SHARED_GATE" "$@"
}
main "$@"

View File

@ -1,182 +0,0 @@
import 'dart:convert';
import 'package:data_transfer_flutter/data_transfer_flutter.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final now = DateTime.utc(2026, 11, 1, 12, 30);
group('buildEnvelope', () {
test('puts format, version and a UTC timestamp first', () {
final envelope = buildEnvelope(
format: 'demo_export',
version: 2,
now: now,
body: {
'items': <Object?>[1, 2],
},
);
expect(envelope.keys, ['format', 'version', 'exported_at', 'items']);
expect(envelope['format'], 'demo_export');
expect(envelope['version'], 2);
expect(envelope['exported_at'], '2026-11-01T12:30:00.000Z');
expect(envelope['items'], [1, 2]);
});
test('converts a local clock to UTC', () {
final local = DateTime.parse('2026-11-01T12:30:00+02:00');
final envelope = buildEnvelope(format: 'f', version: 1, now: local);
expect(envelope['exported_at'], '2026-11-01T10:30:00.000Z');
});
test('refuses a body that shadows an envelope key', () {
expect(
() => buildEnvelope(
format: 'f',
version: 1,
now: now,
body: {'version': 9},
),
throwsArgumentError,
);
});
});
group('validateEnvelope', () {
final good = <String, Object?>{
'format': 'demo_export',
'version': 1,
'exported_at': 'x',
'rest': true,
};
test('returns the same map when format and version match', () {
final out = validateEnvelope(good, format: 'demo_export', version: 1);
expect(out, same(good));
});
test('rejects a non-object as not an object', () {
for (final value in <Object?>[null, 3, 'text', <Object?>[]]) {
expect(
() => validateEnvelope(value, format: 'demo_export', version: 1),
throwsA(isA<EnvelopeNotObject>()),
);
}
});
test('rejects a foreign format and reports both names', () {
expect(
() => validateEnvelope(
{...good, 'format': 'other'},
format: 'demo_export',
version: 1,
),
throwsA(
isA<EnvelopeFormatMismatch>()
.having((e) => e.expected, 'expected', 'demo_export')
.having((e) => e.actual, 'actual', 'other')
.having((e) => e.message, 'message', contains('demo_export')),
),
);
});
test('rejects a missing format', () {
expect(
() =>
validateEnvelope({'version': 1}, format: 'demo_export', version: 1),
throwsA(isA<EnvelopeFormatMismatch>()),
);
});
test('rejects another version and reports both numbers', () {
expect(
() => validateEnvelope(
{...good, 'version': 7},
format: 'demo_export',
version: 1,
),
throwsA(
isA<EnvelopeVersionMismatch>()
.having((e) => e.expected, 'expected', 1)
.having((e) => e.actual, 'actual', 7)
.having((e) => e.message, 'message', contains('7')),
),
);
});
test('rejects a missing version', () {
expect(
() => validateEnvelope(
{'format': 'demo_export'},
format: 'demo_export',
version: 1,
),
throwsA(isA<EnvelopeVersionMismatch>()),
);
});
test('every error is a FormatException', () {
expect(
() => validateEnvelope(null, format: 'f', version: 1),
throwsFormatException,
);
expect(
() => validateEnvelope({'format': 'g'}, format: 'f', version: 1),
throwsFormatException,
);
expect(
() => validateEnvelope(
{'format': 'f', 'version': 2},
format: 'f',
version: 1,
),
throwsFormatException,
);
});
});
group('EnvelopeException', () {
test('behaves as a FormatException with no source position', () {
const FormatException error = EnvelopeInvalidJson();
expect(error.message, 'not valid JSON');
expect(error.source, isNull);
expect(error.offset, isNull);
expect(error.toString(), contains('not valid JSON'));
});
});
group('parseEnvelope', () {
test('round-trips what buildEnvelope produced', () {
final text = jsonEncode(
buildEnvelope(format: 'f', version: 1, now: now, body: {'n': 1}),
);
final parsed = parseEnvelope(text, format: 'f', version: 1);
expect(parsed['n'], 1);
});
test('reports malformed JSON as an invalid-JSON error', () {
expect(
() => parseEnvelope('{oops', format: 'f', version: 1),
throwsA(isA<EnvelopeInvalidJson>()),
);
});
test('runs the format and version checks on valid JSON', () {
expect(
() => parseEnvelope(
'{"format":"g","version":1}',
format: 'f',
version: 1,
),
throwsA(isA<EnvelopeFormatMismatch>()),
);
});
});
}

View File

@ -1,162 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:data_transfer_flutter/src/json_type_group.dart';
import 'package:data_transfer_flutter/src/platform_io.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
class _FakeSelector extends FileSelectorPlatform
with MockPlatformInterfaceMixin {
FileSaveLocation? saveLocation;
XFile? fileToOpen;
final saveRequests = <String?>[];
@override
Future<FileSaveLocation?> getSaveLocation({
List<XTypeGroup>? acceptedTypeGroups,
SaveDialogOptions options = const SaveDialogOptions(),
}) async {
saveRequests.add(options.suggestedName);
return saveLocation;
}
@override
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async => fileToOpen;
}
void main() {
late _FakeSelector selector;
late Directory temp;
setUp(() async {
TestWidgetsFlutterBinding.ensureInitialized();
selector = _FakeSelector();
FileSelectorPlatform.instance = selector;
temp = await Directory.systemTemp.createTemp('data_transfer_io');
});
tearDown(() => temp.delete(recursive: true));
group('desktop', () {
final desktop = IoDataTransferPlatform(isMobile: false);
test('the save dialog is typed by the file name and mime type', () {
final group = saveTypeGroup('punchme.csv', 'text/csv');
expect(group.extensions, ['csv']);
expect(group.mimeTypes, ['text/csv']);
});
test('a name without an extension accepts any type', () {
expect(saveTypeGroup('README', 'text/plain').extensions, isNull);
});
test('save writes to the chosen path and suggests the name', () async {
final path = '${temp.path}/out.json';
selector.saveLocation = FileSaveLocation(path);
final saved = await desktop.saveText(fileName: 'x.json', text: '{}');
expect(saved, isTrue);
expect(File(path).readAsStringSync(), '{}');
expect(selector.saveRequests, ['x.json']);
});
test('a cancelled save writes nothing and returns false', () async {
final saved = await desktop.saveText(fileName: 'x.json', text: '{}');
expect(saved, isFalse);
expect(temp.listSync(), isEmpty);
});
test('share falls back to the save dialog', () async {
final path = '${temp.path}/shared.json';
selector.saveLocation = FileSaveLocation(path);
final shared = await desktop.shareText(fileName: 'x.json', text: '[]');
expect(shared, isTrue);
expect(File(path).readAsStringSync(), '[]');
});
test('pick reads the chosen file, null when cancelled', () async {
expect(await desktop.pickText(), isNull);
selector.fileToOpen = XFile.fromData(
Uint8List.fromList('{"a":1}'.codeUnits),
name: 'in.json',
);
expect(await desktop.pickText(), '{"a":1}');
});
});
group('mobile', () {
test(
'save hands UTF-8 bytes to the document saver, not file_selector',
() async {
String? name;
String? mime;
List<int>? captured;
final mobile = IoDataTransferPlatform(
isMobile: true,
documentSaver:
({required fileName, required bytes, required mimeType}) async {
name = fileName;
mime = mimeType;
captured = bytes;
return true;
},
);
final saved = await mobile.saveText(
fileName: 'm.json',
text: 'zażółć',
mimeType: 'text/csv',
);
expect(saved, isTrue);
expect(name, 'm.json');
expect(mime, 'text/csv');
expect(utf8.decode(captured!), 'zażółć');
expect(selector.saveRequests, isEmpty);
},
);
test('a cancelled document picker reports false', () async {
final mobile = IoDataTransferPlatform(
isMobile: true,
documentSaver:
({required fileName, required bytes, required mimeType}) async =>
false,
);
expect(await mobile.saveText(fileName: 'm.json', text: '{}'), isFalse);
});
test('share goes through the share sheet seam', () async {
(String, String)? seen;
String? sharedMime;
final mobile = IoDataTransferPlatform(
isMobile: true,
sheetSharer:
({required fileName, required text, required mimeType}) async {
seen = (fileName, text);
sharedMime = mimeType;
return true;
},
);
expect(await mobile.shareText(fileName: 's.json', text: '1'), isTrue);
expect(seen, ('s.json', '1'));
expect(sharedMime, 'application/json');
});
});
}

View File

@ -1,43 +0,0 @@
import 'package:data_transfer_flutter/data_transfer_flutter.dart';
/// Records what the facade asked the platform to do.
class FakePlatform implements DataTransferPlatform {
/// What every save/share returns; false stands for a cancelled dialog.
bool accept = true;
/// What [pickText] returns; null stands for a cancelled picker.
String? picked;
/// `(fileName, text)` of every [saveText] call.
final saves = <(String, String)>[];
/// The mime type of every [saveText] call, in order.
final saveMimes = <String>[];
/// `(fileName, text)` of every [shareText] call.
final shares = <(String, String)>[];
@override
Future<bool> saveText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) async {
saves.add((fileName, text));
saveMimes.add(mimeType);
return accept;
}
@override
Future<bool> shareText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) async {
shares.add((fileName, text));
return accept;
}
@override
Future<String?> pickText() async => picked;
}

View File

@ -1,113 +0,0 @@
import 'dart:convert';
import 'package:data_transfer_flutter/data_transfer_flutter.dart';
import 'package:flutter_test/flutter_test.dart';
import 'support/fake_platform.dart';
void main() {
late FakePlatform fake;
late DataTransferPlatform original;
setUp(() {
original = DataTransfer.platform;
fake = FakePlatform();
DataTransfer.platform = fake;
});
tearDown(() => DataTransfer.platform = original);
group('exportJson', () {
test('saves the map as indented JSON under the given name', () async {
final saved = await exportJson(fileName: 'a.json', json: {'k': 1});
expect(saved, isTrue);
expect(fake.saves.single.$1, 'a.json');
expect(
fake.saves.single.$2,
const JsonEncoder.withIndent(' ').convert({'k': 1}),
);
expect(fake.shares, isEmpty);
});
test('returns false when the dialog was cancelled', () async {
fake.accept = false;
expect(await exportJson(fileName: 'a.json', json: {}), isFalse);
});
});
group('exportJsonText', () {
test('passes an already-encoded string through untouched', () async {
await exportJsonText(fileName: 'b.json', text: '{"x":1}');
expect(fake.saves.single, ('b.json', '{"x":1}'));
});
});
group('exportTextFile', () {
test('saves non-JSON text with its own mime type', () async {
final saved = await exportTextFile(
fileName: 'a.csv',
text: 'a,b\n',
mimeType: 'text/csv',
);
expect(saved, isTrue);
expect(fake.saves.single, ('a.csv', 'a,b\n'));
expect(fake.saveMimes.single, 'text/csv');
});
test('exportJsonText keeps the JSON mime type', () async {
await exportJsonText(fileName: 'a.json', text: '{}');
expect(fake.saveMimes.single, 'application/json');
});
});
group('shareJson', () {
test('uses the share action, not save', () async {
final shared = await shareJson(fileName: 'c.json', json: {'k': 2});
expect(shared, isTrue);
expect(fake.shares.single.$1, 'c.json');
expect(jsonDecode(fake.shares.single.$2), {'k': 2});
expect(fake.saves, isEmpty);
});
});
group('pickJson', () {
test('decodes the picked file', () async {
fake.picked = '{"a":[1,2]}';
expect(await pickJson(), {
'a': [1, 2],
});
});
test('returns null when the picker was cancelled', () async {
expect(await pickJson(), isNull);
expect(await pickJsonText(), isNull);
});
test('rejects a file that is not JSON', () async {
fake.picked = '{oops';
await expectLater(pickJson, throwsA(isA<EnvelopeInvalidJson>()));
});
test('rejects JSON that is not an object', () async {
fake.picked = '[1]';
await expectLater(pickJson, throwsA(isA<EnvelopeNotObject>()));
});
});
group('pickJsonText', () {
test('returns the raw text without decoding it', () async {
fake.picked = 'not even json';
expect(await pickJsonText(), 'not even json');
});
});
}

View File

@ -1,31 +0,0 @@
# Add a plain-text multi-voice score format
## what
Add a plain-text score format that `compose.py` and `sequencer.py` can
render: named voices, a noise-drum voice, a `meter` field (3/4, 6/8) and
A/B sections. Today `sequencer.BEATS_PER_BAR` is fixed at 4 and a `Recipe`
has one bass, one arpeggio and one melody.
Source: simonwillison.net/2026/Oct/6/scrimshaw-jukebox.
## done
```
cd ~/src/utils/music_theory && PYTHONPATH=. python -m pytest music_theory/tests/test_score.py music_theory/tests/test_sequencer.py music_theory/tests/test_compose.py --cov=music_theory.score --cov=music_theory.sequencer --cov=music_theory.compose --cov-branch --cov-fail-under=100
```
exits 0. It covers: a 3/4 and a 6/8 score render bar-exact loops, two named
voices stack, the noise-drum voice is deterministic for a fixed seed, and an
A/B-section score renders A then B in order.
## verify
Desktop. Render one 3/4 and one 6/8 example score with
`PYTHONPATH=. python -m music_theory render --score examples/waltz.txt --out /tmp/waltz.wav`,
check `analysis.dominant_frequency` and the frame count equal
`sequencer.loop_frames` for the bar count, and re-render for byte-identical
output. The final listen is kuhy's.
## read first
- `music_theory/compose.py` (`Recipe`), `music_theory/sequencer.py`
(`NoteEvent`, `BEATS_PER_BAR`), `music_theory/noise.py` (drum source).
- `DOCS-article-walkthrough.md` (article section 10, notation as format).
- `~/.claude/skills/procedural-music/SKILL.md`.
REMOVE ME AFTER FINISH

View File

@ -4,4 +4,3 @@ build/
pubspec.lock
coverage/
*.iml
pubspec_overrides.yaml

View File

@ -1,24 +1,12 @@
import 'package:data_transfer_flutter/data_transfer_flutter.dart';
/// Thrown by a [BackupSlot] callback when the user dismissed the file dialog.
///
/// Not a failure: [SyncSettingsScreen] clears its status line instead of
/// claiming success or showing an error.
class BackupCancelled implements Exception {
/// Creates the signal.
const BackupCancelled();
}
/// An injectable local export/import delegate for [SyncSettingsScreen]'s
/// optional "Backup" section.
///
/// The export/import CONTENT differs per app (todo: Markdown notes;
/// home_inventory: inventory export; workout_app: a permission-gated
/// `BackupService`), so the default constructor only carries the label and
/// the two callbacks. Apps whose backup is a JSON file use [BackupSlot.json],
/// which adds the shared file plumbing (`data_transfer_flutter`). Passing
/// `null` for `SyncSettingsScreen.backup` omits the section entirely
/// (diet_guard, wake_alarm have no local backup at all).
/// Deliberately not a shared implementation: the actual export/import format
/// differs per app (todo: Markdown notes; home_inventory: inventory export;
/// workout_app: a permission-gated `BackupService`), so this package only
/// carries the label and the two callbacks. Passing `null` for
/// `SyncSettingsScreen.backup` omits the section entirely (diet_guard,
/// wake_alarm have no local backup at all).
class BackupSlot {
/// Creates a [BackupSlot] labelled [label] (e.g. `'notes'`,
/// `'inventory'`), backed by [export] and [import].
@ -28,31 +16,6 @@ class BackupSlot {
required this.import,
});
/// A slot whose backup is a JSON file, using `data_transfer_flutter`.
///
/// Export saves `build()` as [fileName] to device storage (system Save-as
/// on Android/iOS, a save dialog on desktop, a download on web). Import
/// lets the user pick a JSON file and hands the decoded object to
/// [restore]. A dismissed dialog throws [BackupCancelled] (and a cancelled
/// picker restores nothing).
factory BackupSlot.json({
required String label,
required String fileName,
required Future<Map<String, Object?>> Function() build,
required Future<void> Function(Map<String, Object?> json) restore,
}) => BackupSlot(
label: label,
export: () async {
final saved = await exportJson(fileName: fileName, json: await build());
if (!saved) throw const BackupCancelled();
},
import: () async {
final json = await pickJson();
if (json == null) throw const BackupCancelled();
await restore(json);
},
);
/// Noun describing what this exports/imports, used in the section's
/// button text ("Export $label" / "Import $label").
final String label;

View File

@ -123,8 +123,6 @@ class _SyncSettingsScreenState extends State<SyncSettingsScreen> {
try {
await backup.export();
if (mounted) setState(() => _status = 'Exported ${backup.label}.');
} on BackupCancelled {
if (mounted) setState(() => _status = null);
} on Exception catch (error) {
if (mounted) setState(() => _status = 'Export failed: $error');
}
@ -134,8 +132,6 @@ class _SyncSettingsScreenState extends State<SyncSettingsScreen> {
try {
await backup.import();
if (mounted) setState(() => _status = 'Imported ${backup.label}.');
} on BackupCancelled {
if (mounted) setState(() => _status = null);
} on Exception catch (error) {
if (mounted) setState(() => _status = 'Import failed: $error');
}

View File

@ -5,7 +5,7 @@ description: >-
injected closures -- no keystore or platform plugin access lives in this
package itself.
publish_to: 'none'
version: 0.5.2
version: 0.4.3
environment:
sdk: ^3.12.2
@ -16,11 +16,6 @@ dependencies:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.11.3
path: crdt_sync_dart
data_transfer_flutter:
git:
url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.0
path: data_transfer_flutter
flutter:
sdk: flutter

View File

@ -1,6 +1,3 @@
import 'dart:convert';
import 'package:data_transfer_flutter/data_transfer_flutter.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sync_settings_ui/sync_settings_ui.dart';
@ -19,98 +16,4 @@ void main() {
expect(exported, isTrue);
expect(imported, isTrue);
});
group('BackupSlot.json', () {
late _FakePlatform fake;
late DataTransferPlatform original;
setUp(() {
original = DataTransfer.platform;
fake = _FakePlatform();
DataTransfer.platform = fake;
});
tearDown(() => DataTransfer.platform = original);
test('export saves the built map under fileName', () async {
final slot = BackupSlot.json(
label: 'inventory',
fileName: 'inv.json',
build: () async => {'items': 3},
restore: (_) async {},
);
await slot.export();
expect(fake.saved.single.$1, 'inv.json');
expect(jsonDecode(fake.saved.single.$2), {'items': 3});
});
test('import hands the picked map to restore', () async {
fake.picked = '{"items":3}';
Map<String, Object?>? restored;
final slot = BackupSlot.json(
label: 'inventory',
fileName: 'inv.json',
build: () async => {},
restore: (json) async => restored = json,
);
await slot.import();
expect(restored, {'items': 3});
});
test('a cancelled picker restores nothing', () async {
var called = false;
final slot = BackupSlot.json(
label: 'inventory',
fileName: 'inv.json',
build: () async => {},
restore: (_) async => called = true,
);
await expectLater(slot.import(), throwsA(isA<BackupCancelled>()));
expect(called, isFalse);
});
test('a cancelled save dialog reports the cancellation', () async {
fake.acceptSave = false;
final slot = BackupSlot.json(
label: 'inventory',
fileName: 'inv.json',
build: () async => {'items': 3},
restore: (_) async {},
);
await expectLater(slot.export(), throwsA(isA<BackupCancelled>()));
});
});
}
class _FakePlatform implements DataTransferPlatform {
String? picked;
bool acceptSave = true;
final saved = <(String, String)>[];
@override
Future<bool> saveText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) async {
saved.add((fileName, text));
return acceptSave;
}
@override
Future<bool> shareText({
required String fileName,
required String text,
String mimeType = 'application/json',
}) async => true;
@override
Future<String?> pickText() async => picked;
}

View File

@ -17,38 +17,6 @@ Widget _wrap(Widget child) => MaterialApp(home: child);
void main() {
group('Backup section', () {
testWidgets('a cancelled export or import claims no success', (
tester,
) async {
await tester.pumpWidget(
_wrap(
SyncSettingsScreen(
accountLoader: () async => null,
accountSaver: (_) async {},
accountClearer: () async {},
sessionProbe: () async => false,
firebaseFactory: () async => null,
backup: BackupSlot(
label: 'notes',
export: () async => throw const BackupCancelled(),
import: () async => throw const BackupCancelled(),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Export notes'));
await tester.pumpAndSettle();
expect(find.text('Exported notes.'), findsNothing);
expect(find.textContaining('failed'), findsNothing);
await tester.tap(find.text('Import notes'));
await tester.pumpAndSettle();
expect(find.text('Imported notes.'), findsNothing);
expect(find.textContaining('failed'), findsNothing);
});
testWidgets('omitted entirely when backup is null', (tester) async {
await tester.pumpWidget(
_wrap(

View File

@ -1,206 +0,0 @@
"""Design-token conformance per UI surface: tokens used vs raw literals.
Install counts and component counts are vanity metrics. What shows whether a
design system is working is how often a surface reaches for a token versus a
hard-coded value (learn.thedesignsystem.guide, "Half my design system metrics
don't work anymore"). This script counts, per UI surface of one repo:
* token usages: ``var(--x)`` in CSS/TS/TSX/Astro, ``AppPalette.x`` style
constants and ``Theme.of`` / ``colorScheme`` / ``textTheme`` in Dart
* raw literals: hex colours (``#rrggbb``, ``0xAARRGGBB``) and non-zero
``px`` / ``pt`` numbers, outside the token files
A surface is the nearest ancestor directory holding a manifest
(``pubspec.yaml``, ``package.json``, ``astro.config.*``), else the repo root.
Token files (tokens/theme/palette/colors), custom-property definitions,
comments, tests, ``@media`` lines and generated/build dirs are skipped.
The counts are a heuristic trend signal, not an audit.
Run: python3 conformance.py <repo> [--json] [--previous <earlier.json>]
Exit 0 = report printed; 2 = bad arguments or unreadable previous file.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from conformance_diff import delta, load_previous, table
Json = dict[str, Any]
EXTENSIONS = frozenset({".dart", ".css", ".ts", ".tsx", ".astro"})
SKIP_DIRS = frozenset({
".git", "node_modules", "build", "dist", ".dart_tool", ".astro", ".next",
"coverage", "generated", "__pycache__", ".venv", "test", "tests",
"__tests__", ".fvm", ".pub-cache",
})
SKIP_NAME = re.compile(
r"(\.g\.dart|\.freezed\.dart|\.d\.ts|\.test\.[jt]sx?|_test\.dart)$"
)
TOKEN_FILE = re.compile(r"^_?(tokens?|theme|palette|colou?rs?)\b", re.IGNORECASE)
MANIFESTS = ("pubspec.yaml", "package.json")
MAX_BYTES = 1_000_000
BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
LINE_COMMENT = re.compile(r"(?<![:\w])//.*")
TOKEN_DEFINITION = re.compile(r"--[\w-]+\s*:[^;}]*;?")
MEDIA_LINE = re.compile(r"@(media|container)\b")
HEX = re.compile(
r"#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b|\b0x[0-9A-Fa-f]{8}\b"
)
UNIT = re.compile(r"(?<![\w.#-])(?!0+(?:\.0+)?(?:px|pt)\b)\d+(?:\.\d+)?(?:px|pt)\b")
TOKEN_USE = re.compile(
r"var\(--|\bApp(?:Palette|Spacing|Radius|TextSize|Duration|Curve)\.\w+"
r"|\bTheme\.of\(|\bcolorScheme\.|\btextTheme\."
)
@dataclass
class Surface:
"""Counts for one UI surface."""
name: str
files: int = 0
token_usages: int = 0
raw_literals: int = 0
@property
def conformance(self) -> float | None:
"""Percent of style values that are tokens, or None with no values."""
total = self.token_usages + self.raw_literals
if total == 0:
return None
return round(100.0 * self.token_usages / total, 1)
def as_dict(self) -> Json:
"""JSON-ready form."""
return {
"name": self.name,
"files": self.files,
"token_usages": self.token_usages,
"raw_literals": self.raw_literals,
"conformance": self.conformance,
}
def strip_comments(text: str, suffix: str) -> str:
"""Remove comments so a hex in prose is not counted as a literal."""
text = BLOCK_COMMENT.sub("", text)
if suffix == ".css":
return text
return LINE_COMMENT.sub("", text)
def count_text(text: str, suffix: str) -> tuple[int, int]:
"""Return (token usages, raw literals) for one file's text."""
tokens = 0
literals = 0
for line in strip_comments(text, suffix).splitlines():
tokens += len(TOKEN_USE.findall(line))
if MEDIA_LINE.search(line):
continue
line = TOKEN_DEFINITION.sub("", line)
literals += len(HEX.findall(line)) + len(UNIT.findall(line))
return tokens, literals
def _has_manifest(directory: Path) -> bool:
"""True when ``directory`` holds a package/app manifest."""
return any((directory / m).exists() for m in MANIFESTS) or any(
directory.glob("astro.config.*")
)
def surface_root(path: Path, repo: Path) -> Path:
"""Nearest ancestor of ``path`` (within ``repo``) holding a manifest."""
parent = path.parent
while parent != repo and not _has_manifest(parent):
parent = parent.parent
return parent
def ui_files(repo: Path) -> list[Path]:
"""UI source files, skipping build/generated dirs and token files."""
found: list[Path] = []
for root, dirs, names in os.walk(repo):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
for name in sorted(names):
path = Path(root) / name
if path.suffix not in EXTENSIONS or SKIP_NAME.search(name):
continue
if TOKEN_FILE.match(path.stem):
continue
if path.is_file() and path.stat().st_size <= MAX_BYTES:
found.append(path)
return found
def scan(repo: Path) -> list[Surface]:
"""Count every UI surface under ``repo``, sorted by name."""
surfaces: dict[Path, Surface] = {}
for path in ui_files(repo):
root = surface_root(path, repo)
name = str(root.relative_to(repo))
surface = surfaces.setdefault(root, Surface(name))
text = path.read_text(encoding="utf-8", errors="replace")
tokens, literals = count_text(text, path.suffix)
surface.files += 1
surface.token_usages += tokens
surface.raw_literals += literals
return sorted(surfaces.values(), key=lambda s: s.name)
def totals(surfaces: list[Surface]) -> Surface:
"""Sum of all surfaces."""
return Surface(
"TOTAL",
sum(s.files for s in surfaces),
sum(s.token_usages for s in surfaces),
sum(s.raw_literals for s in surfaces),
)
def report(repo: Path) -> Json:
"""Whole-repo report as a JSON-ready dict."""
surfaces = scan(repo)
return {
"repo": str(repo),
"surfaces": [s.as_dict() for s in surfaces],
"totals": totals(surfaces).as_dict(),
}
def main(argv: list[str] | None = None) -> int:
"""CLI entry point."""
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("repo", type=Path)
parser.add_argument("--json", action="store_true", help="print JSON")
parser.add_argument("--previous", type=Path, help="earlier --json output")
args = parser.parse_args(argv)
if not args.repo.is_dir():
print(f"not a directory: {args.repo}", file=sys.stderr)
return 2
rep = report(args.repo.resolve())
diff = None
if args.previous:
try:
diff = delta(rep, load_previous(args.previous))
except (OSError, ValueError) as exc:
print(f"cannot read previous report: {exc}", file=sys.stderr)
return 2
if args.json:
print(json.dumps({**rep, **({"delta": diff} if diff else {})}, indent=2))
else:
print(table(rep, diff))
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -1,74 +0,0 @@
"""Delta and table rendering for conformance reports (see conformance.py)."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
Json = dict[str, Any]
def _num(value: object) -> float:
"""Numeric value from loosely typed JSON, 0 when absent."""
return float(value) if isinstance(value, (int, float)) else 0.0
def load_previous(path: Path) -> Json:
"""Read an earlier ``--json`` report; ValueError if its shape is wrong."""
data = json.loads(path.read_text(encoding="utf-8"))
surfaces = data.get("surfaces") if isinstance(data, dict) else None
ok = isinstance(surfaces, list) and isinstance(data.get("totals"), dict)
if not ok or not all(isinstance(s, dict) and "name" in s for s in surfaces):
msg = "not a conformance report"
raise ValueError(msg)
return data
def delta(current: Json, previous: Json) -> Json:
"""Per-surface and total change versus a previous report."""
before = {str(s["name"]): s for s in previous["surfaces"]}
rows: list[Json] = []
entries = [*current["surfaces"], current["totals"]]
prev_total = previous["totals"]
for row in entries:
old = prev_total if row["name"] == "TOTAL" else before.get(str(row["name"]), {})
rows.append({
"name": row["name"],
"token_usages": _num(row["token_usages"]) - _num(old.get("token_usages")),
"raw_literals": _num(row["raw_literals"]) - _num(old.get("raw_literals")),
"conformance": None
if row["conformance"] is None or old.get("conformance") is None
else round(_num(row["conformance"]) - _num(old["conformance"]), 1),
})
return {"rows": rows}
def _fmt(value: object, signed: bool = False) -> str:
"""Table cell text for a count, percent or missing value."""
if value is None:
return "-"
return f"{_num(value):+g}" if signed else f"{_num(value):g}"
def table(rep: Json, diff: Json | None) -> str:
"""Plain-text table, with delta columns when ``diff`` is given."""
head = ["surface", "files", "tokens", "raw", "conf%"]
if diff:
head += ["d.tokens", "d.raw", "d.conf"]
rows = [head]
deltas = {str(r["name"]): r for r in diff["rows"]} if diff else {}
for row in [*rep["surfaces"], rep["totals"]]:
cells = [str(row["name"]), _fmt(row["files"]), _fmt(row["token_usages"]),
_fmt(row["raw_literals"]), _fmt(row["conformance"])]
if diff:
d = deltas.get(str(row["name"]), {})
cells += [_fmt(d.get("token_usages", 0), True),
_fmt(d.get("raw_literals", 0), True),
_fmt(d.get("conformance"), True)]
rows.append(cells)
widths = [max(len(r[i]) for r in rows) for i in range(len(head))]
return "\n".join(
" ".join(c.ljust(w) for c, w in zip(r, widths, strict=True)).rstrip()
for r in rows
)

View File

@ -1,6 +0,0 @@
"""Make ``scripts/`` importable: the folder name has a hyphen, so no package."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))

View File

@ -1,118 +0,0 @@
"""Tests for scripts/conformance.py (100 % branch coverage)."""
from __future__ import annotations
import json
import runpy
import sys
from typing import TYPE_CHECKING
import conformance
import pytest
if TYPE_CHECKING:
from pathlib import Path
def write(root: Path, rel: str, text: str) -> None:
path = root / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def test_count_text_css_tokens_literals_and_skips() -> None:
css = (
"/* #123456 in a comment */\n"
":root { --brand: #b8862e; }\n"
"@media (min-width: 600px) { a { color: red; } }\n"
".a { color: var(--brand); margin: 12px 0px; border: 1.5pt solid #fff; }\n"
)
assert conformance.count_text(css, ".css") == (1, 3)
def test_count_text_line_comments_and_urls_in_ts() -> None:
ts = 'const u = "http://x.test"; // #abcdef\nconst c = "#a1b2c3";\n'
assert conformance.count_text(ts, ".ts") == (0, 1)
def test_count_text_dart_tokens_and_literals() -> None:
dart = (
"final c = Color(0xFF112233);\n"
"final d = AppPalette.accent;\n"
"final e = Theme.of(context).colorScheme.primary;\n"
)
assert conformance.count_text(dart, ".dart") == (3, 1)
def test_conformance_percent_and_none() -> None:
assert conformance.Surface("x").conformance is None
assert conformance.Surface("x", 1, 3, 1).conformance == 75.0
def test_scan_groups_by_manifest_and_skips_generated(tmp_path: Path) -> None:
write(tmp_path, "pubspec.yaml", "name: a")
write(tmp_path, "lib/ui.dart", "final c = AppPalette.bg; final d = '#fff';")
write(tmp_path, "lib/tokens.dart", "const c = Color(0xFF000000);")
write(tmp_path, "lib/a.g.dart", "const c = '#ffffff';")
write(tmp_path, "build/out.css", "a { color: #fff }")
write(tmp_path, "test/x_test.dart", "const c = '#fff';")
write(tmp_path, "web/package.json", "{}")
write(tmp_path, "web/s.css", "a { margin: 8px; color: var(--x); }")
write(tmp_path, "site/astro.config.mjs", "export default {}")
write(tmp_path, "site/p.astro", "<p style='top: 4pt'>hi</p>")
write(tmp_path, "loose/readme.txt", "#fff 3px")
write(tmp_path, "root.tsx", "const a = 'var(--r)';")
write(tmp_path, "big.css", "a{}" + " " * conformance.MAX_BYTES)
surfaces = {s.name: s for s in conformance.scan(tmp_path)}
assert sorted(surfaces) == [".", "site", "web"]
assert (surfaces["."].token_usages, surfaces["."].raw_literals) == (2, 1)
assert surfaces["."].files == 2
assert (surfaces["web"].token_usages, surfaces["web"].raw_literals) == (1, 1)
assert (surfaces["site"].token_usages, surfaces["site"].raw_literals) == (0, 1)
def test_scan_ignores_non_regular_file(tmp_path: Path) -> None:
(tmp_path / "dangling.css").symlink_to(tmp_path / "missing.css")
assert conformance.scan(tmp_path) == []
def test_totals_and_report(tmp_path: Path) -> None:
write(tmp_path, "a.css", "a { margin: 8px; }")
write(tmp_path, "web/package.json", "{}")
write(tmp_path, "web/b.css", "b { color: var(--x); }")
rep = conformance.report(tmp_path)
assert rep["totals"]["token_usages"] == 1
assert rep["totals"]["raw_literals"] == 1
assert rep["totals"]["conformance"] == 50.0
assert [s["name"] for s in rep["surfaces"]] == [".", "web"]
def test_main_table_json_and_delta(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
repo = tmp_path / "repo"
write(repo, "a.css", "a { margin: 8px; color: var(--x); }")
assert conformance.main([str(repo)]) == 0
assert "TOTAL" in capsys.readouterr().out
assert conformance.main([str(repo), "--json"]) == 0
first = capsys.readouterr().out
assert "delta" not in json.loads(first)
prev = tmp_path / "prev.json"
prev.write_text(first, encoding="utf-8")
write(repo, "b.css", "b { color: var(--y); }")
assert conformance.main([str(repo), "--json", "--previous", str(prev)]) == 0
assert json.loads(capsys.readouterr().out)["delta"]["rows"][-1]["token_usages"] == 1.0
assert conformance.main([str(repo), "--previous", str(prev)]) == 0
assert "d.tokens" in capsys.readouterr().out
def test_main_errors(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
assert conformance.main([str(tmp_path / "nope")]) == 2
assert "not a directory" in capsys.readouterr().err
assert conformance.main([str(tmp_path), "--previous", str(tmp_path / "none.json")]) == 2
assert "cannot read previous" in capsys.readouterr().err
def test_script_entry_point(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(sys, "argv", ["conformance.py", str(tmp_path)])
with pytest.raises(SystemExit) as exit_info:
runpy.run_path(conformance.__file__, run_name="__main__")
assert exit_info.value.code == 0

View File

@ -1,71 +0,0 @@
"""Tests for scripts/conformance_diff.py (100 % branch coverage)."""
from __future__ import annotations
from typing import TYPE_CHECKING
import conformance_diff
import pytest
if TYPE_CHECKING:
from pathlib import Path
def previous_report(conf: float | None = 50.0) -> dict:
return {
"surfaces": [{"name": ".", "token_usages": 1, "raw_literals": 1, "conformance": conf}],
"totals": {"name": "TOTAL", "token_usages": 1, "raw_literals": 1, "conformance": conf},
}
def current_report() -> dict:
return {
"surfaces": [
{"name": ".", "files": 1, "token_usages": 3, "raw_literals": 1, "conformance": 75.0},
{"name": "new", "files": 1, "token_usages": 2, "raw_literals": 0, "conformance": None},
],
"totals": {"name": "TOTAL", "files": 2, "token_usages": 5, "raw_literals": 1, "conformance": 83.3},
}
def test_delta_rows() -> None:
rows = {r["name"]: r for r in conformance_diff.delta(current_report(), previous_report())["rows"]}
assert rows["."] == {"name": ".", "token_usages": 2.0, "raw_literals": 0.0, "conformance": 25.0}
assert rows["new"]["token_usages"] == 2.0
assert rows["new"]["conformance"] is None
assert rows["TOTAL"]["conformance"] == 33.3
def test_delta_missing_previous_conformance() -> None:
rows = conformance_diff.delta(current_report(), previous_report(None))["rows"]
assert rows[0]["conformance"] is None
def test_num_and_fmt() -> None:
assert conformance_diff._num("x") == 0.0
assert conformance_diff._num(2) == 2.0
assert conformance_diff._fmt(None) == "-"
assert conformance_diff._fmt(2.5) == "2.5"
assert conformance_diff._fmt(2, signed=True) == "+2"
def test_table_without_and_with_delta() -> None:
plain = conformance_diff.table(current_report(), None)
assert plain.splitlines()[0].split() == ["surface", "files", "tokens", "raw", "conf%"]
assert "TOTAL" in plain
diff = conformance_diff.delta(current_report(), previous_report())
text = conformance_diff.table(current_report(), diff)
assert "d.conf" in text
assert "+25" in text
@pytest.mark.parametrize(
"payload",
["[]", "{}", '{"surfaces": 1, "totals": {}}', '{"surfaces": [1], "totals": {}}',
'{"surfaces": [], "totals": 1}'],
)
def test_load_previous_rejects_bad_shape(tmp_path: Path, payload: str) -> None:
path = tmp_path / "p.json"
path.write_text(payload, encoding="utf-8")
with pytest.raises(ValueError, match="not a conformance report"):
conformance_diff.load_previous(path)

View File

@ -1,80 +0,0 @@
# Port @kuhyx/web-ui from React to Astro + vanilla TS
## what
kuhy chose one framework for every web UI: Astro, with no React islands. This
package is the first blocker. `RangeSlider` is its only React export. It
becomes `RangeSlider.astro` plus a `<range-slider>` custom element. The
pure-TS helpers and the CSS stay as they are. Every repo's
`TODO-astro-migration.md` waits for the tag this produces.
## steps
1. Keep these as they are: `quantile.ts` (`nth`, `clamp01`, `quantileValue`,
`valueQuantile`, `fractionFromPointer`), `stepped-value.ts` (`keyTarget`,
`steppedValue`), `text.ts` (`fuzzyMatch`), `tokens.css`, `range-slider.css`.
2. Write `src/range-slider-element.ts`, a `RangeSliderElement extends HTMLElement`
registered as `range-slider`. Inputs: a `values` property (number[]), `lo` and
`hi` attributes, a `label` attribute, and a `format` property (a function).
Output: a bubbling `change` CustomEvent with `{ lo, hi }`. Keep the current
DOM: two `<button role="slider">` thumbs with `aria-valuemin`, `aria-valuemax`
and `aria-valuenow`, grab-the-nearer-thumb on pointer, and the keyboard map in
README.md. All of the logic stays in the existing pure helpers.
3. Write `src/RangeSlider.astro`. It server-renders the same markup (track,
thumbs, optional head) inside `<range-slider>`. Its `<script>` imports the
element module, so including the component registers the element.
4. Order: element and its tests first, then the `.astro` wrapper, then exports
and packaging, then README, then the tag.
5. Packaging. tsc cannot emit `.astro`, so ship the `.astro` source as it is.
Astro compiles `.astro` files from dependencies. Add to `exports`:
`"./RangeSlider.astro": "./src/RangeSlider.astro"` and
`"./range-slider": "./dist/range-slider-element.js"`. Add `src/*.astro`
to `files`. Keep `dist/` committed for the `.ts` output. The `.astro`
script imports `../dist/range-slider-element.js`, never the `.ts` source.
6. Consumers import it like this:
`import RangeSlider from "@kuhyx/web-ui/RangeSlider.astro";` in frontmatter.
Scripts use `import "@kuhyx/web-ui/range-slider";` and listen for `change`.
Tokens stay `import "@kuhyx/web-ui/tokens.css";` in the shared layout.
7. Dependencies, all exact pins via pnpm: drop `peerDependencies.react`,
`react`, `react-dom`, `@types/react`, `@types/react-dom` and
`@testing-library/react`. Add `astro@7.4.4` as a devDependency (for the
Container API and `astro check`), `@astrojs/check@0.9.12` and
`@testing-library/dom` at its newest stable. Add
`peerDependencies.astro: ">=7.4.0"`.
8. Tests. `range-slider.test.tsx` becomes `range-slider-element.test.ts`, which
covers the custom element in jsdom: pointer, keyboard, the `change` event and
the ARIA attributes. Add `RangeSlider.astro.test.ts`, which uses
`experimental_AstroContainer` to check the server markup. Keep coverage at
100% for `src/**/*.ts`. Exclude `.astro` from coverage, since its script
holds only the import.
9. Rewrite README.md's Install and "What's here" sections for the Astro API.
Then tag `web_ui-v0.5.0`. Before tagging, run `pnpm build`.
## done
Run from `~/src/utils/web_ui`:
`pnpm install --frozen-lockfile && pnpm lint && pnpm coverage && pnpm build && ! grep -q '"react"' package.json && ! find src -name '*.tsx' | grep -q . && git tag -l web_ui-v0.5.0 | grep -q .`
This exits 0.
## verify
Do it in the first consumer migrated, awesome-mcp-explorer, because it uses
`RangeSlider`. Check that the slider drags and that arrow keys and Home/End
step. Use a headless chromium at 4K and at a mobile viewport. The filter must
update and there must be no console errors.
## read first
- `~/src/utils/web_ui/README.md`: keyboard map, why `&path:/web_ui`, release steps.
- `~/src/utils/web_ui/src/range-slider.tsx` and `range-slider.test.tsx`.
- The consumers and their tags:
- control-panel/web: v0.3.2
- signal-bot/web: v0.3.1
- dufs-cloud/web: v0.3.1
- awesome-mcp-explorer: v0.3.1
- foss-audit: v0.4.0
- Astro docs: "Publish to NPM" (shipping `.astro`), and `reference/container-reference`.
## order
Migration order across kuhy's repos:
1. `web_ui` first (this file), because every other repo waits for its tag.
2. Content sites next (public sites, e.g. teatr-pw's Astro version).
3. Small apps after.
4. `control-panel` and `steam-backlog-enforcer` last, after every other repo.
REMOVE ME AFTER FINISH

View File

@ -162,59 +162,3 @@ body {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}
/* Print default (brennenputh.me/blog/printable-websites). Colour tokens are
* dropped for paper: black on white, links spelled out, code boxed. Elements
* marked .noPrint (nav, header, controls) vanish; .onlyPrint is the inverse
* and is hidden on screen by the rule below the block. */
@media print {
.noPrint,
nav.noPrint,
header.noPrint {
display: none;
}
body {
background: white;
color: black;
font-size: 12pt;
}
h1 {
font-size: 16pt;
}
h2 {
font-size: 14pt;
}
h3 {
font-size: 13pt;
}
pre,
code {
border: 1px solid black;
font-size: 11pt;
break-inside: avoid;
}
figure,
img {
break-inside: avoid;
}
a {
color: black;
}
a[href^="http"]::after {
content: " (" attr(href) ")";
}
}
@media screen {
.onlyPrint {
display: none;
}
}

View File

@ -162,59 +162,3 @@ body {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}
/* Print default (brennenputh.me/blog/printable-websites). Colour tokens are
* dropped for paper: black on white, links spelled out, code boxed. Elements
* marked .noPrint (nav, header, controls) vanish; .onlyPrint is the inverse
* and is hidden on screen by the rule below the block. */
@media print {
.noPrint,
nav.noPrint,
header.noPrint {
display: none;
}
body {
background: white;
color: black;
font-size: 12pt;
}
h1 {
font-size: 16pt;
}
h2 {
font-size: 14pt;
}
h3 {
font-size: 13pt;
}
pre,
code {
border: 1px solid black;
font-size: 11pt;
break-inside: avoid;
}
figure,
img {
break-inside: avoid;
}
a {
color: black;
}
a[href^="http"]::after {
content: " (" attr(href) ")";
}
}
@media screen {
.onlyPrint {
display: none;
}
}

View File

@ -139,13 +139,4 @@ describe("tokens.css", () => {
// Shadows are ink-tinted rgba; neutrals are never pure.
expect(css).not.toMatch(/#fff\b|#ffffff\b|#000\b|#000000\b|rgba\(0,\s*0,\s*0/i);
});
it("ships a print block that hides .noPrint and boxes code", () => {
const print = css.slice(css.indexOf("@media print"));
expect(print).toContain(".noPrint");
expect(print).toMatch(/font-size:\s*12pt/);
expect(print).toMatch(/pre,\s*code\s*{[^}]*1px solid black[^}]*11pt[^}]*break-inside:\s*avoid/);
expect(print).toContain('a[href^="http"]::after');
expect(css).toMatch(/@media screen\s*{\s*\.onlyPrint\s*{\s*display:\s*none/);
});
});