diff --git a/lib/features/earthquake/domain/earthquake_share_input.dart b/lib/features/earthquake/domain/earthquake_share_input.dart new file mode 100644 index 000000000..52a2475f3 --- /dev/null +++ b/lib/features/earthquake/domain/earthquake_share_input.dart @@ -0,0 +1,414 @@ +/// Converts an evidenced ExpTech Core v2 detail snapshot into share input v2. +library; + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; + +enum ReportIntensityScale { cwa2020, legacy } + +/// Evidence for one independently checked Core v2 detail snapshot. +/// +/// The caller must establish the dataset, requested ID, magnitude kind and +/// intensity scale from the source contract and its applicability to this +/// snapshot. Check integer fields and key uniqueness on the raw record +/// before decoding: the detail parser can discard that information. +/// [sourceDecimals] holds the original decimal tokens by source JSON +/// Pointer, before the API decoder converts them to binary doubles. +/// [countyCodes] uses verified MOI county codes valid for this snapshot. +/// [stationCodes] uses verified CWA codes looked up by county and station name +/// within this snapshot. The names are lookup keys for the supplied evidence. +final class ExpTechReportEvidence { + ExpTechReportEvidence({ + required EarthquakeReport snapshot, + required this.requestedReportId, + required Map sourceDecimals, + required Map countyCodes, + required Map<(String, String), String> stationCodes, + this.scale, + this.magnitudeIsMl = false, + }) : _snapshot = snapshot.copyWith( + list: { + for (final entry in snapshot.list.entries) + entry.key: entry.value.copyWith(town: Map.of(entry.value.town)), + }, + ), + _sourceDecimals = Map.unmodifiable(sourceDecimals), + _countyCodes = Map.unmodifiable(countyCodes), + _stationCodes = Map.unmodifiable(stationCodes); + + final EarthquakeReport _snapshot; + final String requestedReportId; + final ReportIntensityScale? scale; + final bool magnitudeIsMl; + final Map _sourceDecimals; + final Map _countyCodes; + final Map<(String, String), String> _stationCodes; +} + +sealed class EarthquakeShareInput { + const EarthquakeShareInput(); +} + +final class EarthquakeShareInputV2 extends EarthquakeShareInput { + EarthquakeShareInputV2._(List bytes) + : bytes = Uint8List.fromList(bytes).asUnmodifiableView(); + + /// Complete, deterministic UTF-8 envelope for the v2 renderer. + final Uint8List bytes; +} + +enum EarthquakeShareInputError { + missingSourceIdentity, + snapshotMismatch, + unsupportedIntensityScale, + unknownMagnitudeType, + missingAreaIdentity, + missingStationIdentity, + duplicateIdentity, + missingCoordinates, + missingSourceDecimal, + conflictingIntensity, + malformedSource, + inputLimit, +} + +final class UnsupportedEarthquakeShareInput extends EarthquakeShareInput + implements Exception { + const UnsupportedEarthquakeShareInput._(this.code, this.path, this.detail); + + final EarthquakeShareInputError code; + + /// JSON Pointer into the source detail record. Empty denotes the root. + final String path; + final String detail; +} + +final _fullReportId = RegExp(r'^[0-9]{6}-[0-9]{4}-[0-9]{4}-[0-9]{6}$'); +final _countyCode = RegExp(r'^[0-9]{5}$'); +final _stationCode = RegExp(r'^[A-Za-z0-9][A-Za-z0-9._:-]{0,123}$'); +final _decimalToken = RegExp(r'^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?$'); +final _forbiddenText = RegExp(r'[\x00-\x1f\x7f-\x9f\u2028\u2029]'); +const _scaleReference = 'https://exptech.dev/docs/api/earthquake/report/'; + +/// Validation precedes byte emission. Ordinary detail models without matching +/// source evidence cannot establish the identities required by v2. +EarthquakeShareInput adaptEarthquakeShareInput( + EarthquakeReport report, { + ExpTechReportEvidence? evidence, +}) { + try { + if (evidence == null || + !_matches(_fullReportId, report.id) || + report.id != evidence.requestedReportId) { + _reject( + EarthquakeShareInputError.missingSourceIdentity, + '/id', + 'A verified Core v2 detail request and its complete matching ID are required.', + ); + } + if (report != evidence._snapshot) { + _reject( + EarthquakeShareInputError.snapshotMismatch, + '', + 'The supplied evidence belongs to a different report snapshot.', + ); + } + return _adapt(report, evidence); + } on UnsupportedEarthquakeShareInput catch (failure) { + return failure; + } +} + +EarthquakeShareInputV2 _adapt( + EarthquakeReport report, + ExpTechReportEvidence evidence, +) { + if (evidence.scale != ReportIntensityScale.cwa2020) { + _reject( + EarthquakeShareInputError.unsupportedIntensityScale, + '/list', + 'The Core v2 modern intensity encoding must be established for this snapshot.', + ); + } + if (!evidence.magnitudeIsMl) { + _reject( + EarthquakeShareInputError.unknownMagnitudeType, + '/mag', + 'Verify that the Core v2 ML magnitude definition applies to this snapshot.', + ); + } + if (report.time < -62135625600000 || report.time > 253402271999999) { + _malformed('/time', 'Expected Unix milliseconds within the v2 time range.'); + } + + final epicenter = _coordinates( + report.latitude, + report.longitude, + '', + evidence, + ); + final depth = _fixedPoint(report.depth, '/depth', evidence, 1000, 0, 1000000); + final magnitude = _fixedPoint( + report.magnitude, + '/mag', + evidence, + 100, + -200, + 1000, + ); + final location = _localized(report.location, '/loc'); + + if (report.list.length > 256) { + _reject(EarthquakeShareInputError.inputLimit, '/list', 'Too many areas.'); + } + final areas = >{}; + final observations = >{}; + final countyNames = report.list.keys.toList()..sort(); + for (final countyName in countyNames) { + final area = report.list[countyName]!; + final areaPath = '/list/${_pointerToken(countyName)}'; + final areaName = _localized(countyName, areaPath); + final countyCode = evidence._countyCodes[countyName]; + if (countyCode == null || !_matches(_countyCode, countyCode)) { + _reject( + EarthquakeShareInputError.missingAreaIdentity, + areaPath, + 'Provide a verified MOI county code applicable to this snapshot.', + ); + } + if (areas.containsKey(countyCode)) { + _reject( + EarthquakeShareInputError.duplicateIdentity, + areaPath, + 'Repeated county identity.', + ); + } + _validateIntensity(area.intensity, '$areaPath/int'); + areas[countyCode] = { + 'id': countyCode, + 'intensity': area.intensity, + 'name': areaName, + 'region_id': {'id': countyCode, 'namespace': 'tw.moi.county'}, + }; + + final stationNames = area.town.keys.toList()..sort(); + for (final stationName in stationNames) { + final station = area.town[stationName]!; + final stationPath = '$areaPath/town/${_pointerToken(stationName)}'; + if (observations.length == 2048) { + _reject( + EarthquakeShareInputError.inputLimit, + stationPath, + 'Too many observations.', + ); + } + final name = _localized(stationName, stationPath); + final code = evidence._stationCodes[(countyName, stationName)]; + if (code == null || !_matches(_stationCode, code)) { + _reject( + EarthquakeShareInputError.missingStationIdentity, + stationPath, + 'Provide a verified CWA station code for this observation.', + ); + } + // Core detail has one reading per verified station. Reject ambiguous + // duplicates before using its scoped station identity as the local ID. + final id = 'cwa:$code'; + if (observations.containsKey(id)) { + _reject( + EarthquakeShareInputError.duplicateIdentity, + stationPath, + 'Repeated station identity.', + ); + } + _validateIntensity(station.intensity, '$stationPath/int'); + if (station.intensity > area.intensity) { + _reject( + EarthquakeShareInputError.conflictingIntensity, + '$stationPath/int', + 'The observation exceeds its source area maximum.', + ); + } + observations[id] = { + 'area_id': countyCode, + 'id': id, + 'intensity': station.intensity, + 'name': name, + 'position': _coordinates( + station.latitude, + station.longitude, + stationPath, + evidence, + ), + 'station_id': {'id': code, 'namespace': 'cwa'}, + }; + } + } + + final bytes = utf8.encode( + jsonEncode({ + 'locale': 'zh-Hant', + 'report': { + 'areas': _ordered(areas), + 'depth_m': depth, + 'epicenter': epicenter, + 'intensity_scale': 'cwa-2020', + 'location': location, + 'magnitude': {'centi': magnitude, 'kind': 'ml'}, + 'observations': _ordered(observations), + 'origin_time_unix_ms': report.time, + 'published_max_intensity': null, + }, + 'schema_version': 2, + 'source': { + 'event_id': null, + 'namespace': 'exptech.eq-report-v2', + 'publication': null, + 'report_id': report.id, + 'revision': null, + 'scale_evidence': { + 'kind': 'dataset_contract', + 'reference': _scaleReference, + }, + }, + }), + ); + if (bytes.length > 1024 * 1024) { + _reject( + EarthquakeShareInputError.inputLimit, + '', + 'The v2 envelope exceeds 1 MiB.', + ); + } + return EarthquakeShareInputV2._(bytes); +} + +List _ordered(Map values) => [ + for (final id in values.keys.toList()..sort()) values[id]!, +]; + +Map _localized(String value, String path) { + final bytes = utf8.encode(value); + if (value.replaceAll(' ', '').isEmpty || + _forbiddenText.hasMatch(value) || + bytes.length > 512 || + utf8.decode(bytes) != value) { + _malformed(path, 'Expected non-blank v2 text of at most 512 UTF-8 bytes.'); + } + return {'en-US': null, 'zh-Hant': value}; +} + +Map _coordinates( + double latitude, + double longitude, + String path, + ExpTechReportEvidence evidence, +) { + final latPath = '$path/lat'; + final lonPath = '$path/lon'; + final lat = _tryFixedPoint( + latitude, + latPath, + evidence, + 1000000, + -90000000, + 90000000, + ); + final lon = _tryFixedPoint( + longitude, + lonPath, + evidence, + 1000000, + -180000000, + 180000000, + ); + if (lat == null || lon == null) { + _reject( + EarthquakeShareInputError.missingCoordinates, + lat == null ? latPath : lonPath, + 'The original source coordinate token is required.', + ); + } + return {'lat_e6': lat, 'lon_e6': lon}; +} + +int _fixedPoint( + double modelValue, + String path, + ExpTechReportEvidence evidence, + int scale, + int min, + int max, +) => + _tryFixedPoint(modelValue, path, evidence, scale, min, max) ?? + _reject( + EarthquakeShareInputError.missingSourceDecimal, + path, + 'The original source decimal token is required.', + ); + +int? _tryFixedPoint( + double modelValue, + String path, + ExpTechReportEvidence evidence, + int scale, + int min, + int max, +) { + if (!modelValue.isFinite) { + _malformed(path, 'Expected a finite source number.'); + } + final token = evidence._sourceDecimals[path]; + if (token == null) return null; + final match = token.length <= 128 ? _decimalToken.matchAsPrefix(token) : null; + if (match == null || + match.end != token.length || + double.tryParse(token) != modelValue) { + _malformed( + path, + 'Expected a plain decimal token matching the decoded value.', + ); + } + + // Validate the exact decimal before rounding. Binary double and rounding + // alone could admit a just-outside coordinate or move a half tie. + final fraction = match.group(3) ?? ''; + final digits = BigInt.parse('${match.group(2)}$fraction'); + final negative = match.group(1) == '-'; + if (negative && digits == BigInt.zero) { + _malformed(path, 'Negative zero is unsupported.'); + } + final denominator = BigInt.from(10).pow(fraction.length); + final scaled = digits * BigInt.from(scale); + final signed = negative ? -scaled : scaled; + if (signed < BigInt.from(min) * denominator || + signed > BigInt.from(max) * denominator) { + _malformed( + path, + 'The source value is outside the v2 range before rounding.', + ); + } + final rounded = + (scaled * BigInt.two + denominator) ~/ (denominator * BigInt.two); + return (negative ? -rounded : rounded).toInt(); +} + +void _validateIntensity(int value, String path) { + if (value < 0 || value > 9) { + _malformed(path, 'Expected a Core v2 intensity ordinal from 0 to 9.'); + } +} + +String _pointerToken(String value) => + value.replaceAll('~', '~0').replaceAll('/', '~1'); + +bool _matches(RegExp expression, String value) => + expression.matchAsPrefix(value)?.end == value.length; + +Never _malformed(String path, String detail) => + _reject(EarthquakeShareInputError.malformedSource, path, detail); + +Never _reject(EarthquakeShareInputError code, String path, String detail) => + throw UnsupportedEarthquakeShareInput._(code, path, detail); diff --git a/test/features/earthquake/domain/earthquake_share_input_test.dart b/test/features/earthquake/domain/earthquake_share_input_test.dart new file mode 100644 index 000000000..e00ad287e --- /dev/null +++ b/test/features/earthquake/domain/earthquake_share_input_test.dart @@ -0,0 +1,415 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/domain/earthquake_share_input.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _fixtureDir = 'test/features/earthquake/domain/fixtures/share_input'; +const _requestId = '115000-2026-0422-111524'; +const _decimals = { + '/lat': '23.09', + '/lon': '121.4', + '/mag': '3.9', + '/depth': '43.5', + '/list/臺東縣/town/成功/lat': '23.1', + '/list/臺東縣/town/成功/lon': '121.37', + '/list/臺東縣/town/長濱/lat': '23.32', + '/list/臺東縣/town/長濱/lon': '121.45', + '/list/臺東縣/town/池上/lat': '23.1', + '/list/臺東縣/town/池上/lon': '121.22', + '/list/臺東縣/town/東河/lat': '22.97', + '/list/臺東縣/town/東河/lon': '121.3', + '/list/花蓮縣/town/紅葉/lat': '23.5', + '/list/花蓮縣/town/紅葉/lon': '121.33', +}; +const _counties = {'臺東縣': '10014', '花蓮縣': '10015'}; +const _stations = { + ('臺東縣', '成功'): 'CHK', + ('臺東縣', '長濱'): 'ECB', + ('臺東縣', '池上'): 'ECS', + ('臺東縣', '東河'): 'EDH', + ('花蓮縣', '紅葉'): 'EHY', +}; + +Map _readSource(String name) => + jsonDecode(File('$_fixtureDir/exptech-$name.json').readAsStringSync()) + as Map; + +ExpTechReportEvidence _evidence( + EarthquakeReport snapshot, { + String requestedId = _requestId, + Map decimals = _decimals, + Map counties = _counties, + Map<(String, String), String> stations = _stations, + ReportIntensityScale? scale = ReportIntensityScale.cwa2020, + bool magnitudeIsMl = true, +}) => ExpTechReportEvidence( + snapshot: snapshot, + requestedReportId: requestedId, + sourceDecimals: decimals, + countyCodes: counties, + stationCodes: stations, + scale: scale, + magnitudeIsMl: magnitudeIsMl, +); + +EarthquakeShareInputV2 _convert(EarthquakeReport report) => + adaptEarthquakeShareInput(report, evidence: _evidence(report)) + as EarthquakeShareInputV2; + +Map _decode(EarthquakeShareInputV2 input) => + jsonDecode(utf8.decode(input.bytes)) as Map; + +void _expectFailure( + EarthquakeShareInput result, + EarthquakeShareInputError code, + String path, +) { + expect( + result, + isA() + .having((failure) => failure.code, 'code', code) + .having((failure) => failure.path, 'source JSON Pointer', path) + .having((failure) => failure.detail, 'detail', isNotEmpty), + ); +} + +void main() { + final modern = EarthquakeReport.fromJson(_readSource('modern')); + + test( + 'full modern detail matches the independent Rust-validated envelope', + () { + final result = _convert(modern); + expect( + result.bytes, + File('$_fixtureDir/exptech-modern.v2.json').readAsBytesSync(), + ); + final envelope = _decode(result); + final source = envelope['source'] as Map; + final report = envelope['report'] as Map; + expect(source['report_id'], _requestId); + expect(source['revision'], isNull); + expect(source['event_id'], isNull); + expect(source['publication'], isNull); + expect( + report['origin_time_unix_ms'], + DateTime.parse('2026-04-22T11:15:24+08:00').millisecondsSinceEpoch, + ); + expect(report['epicenter'], {'lat_e6': 23090000, 'lon_e6': 121400000}); + expect(report['location'], {'en-US': null, 'zh-Hant': modern.location}); + expect(report['magnitude'], {'centi': 390, 'kind': 'ml'}); + expect(report['depth_m'], 43500); + expect(report['published_max_intensity'], isNull); + expect(modern.maxIntensity, 2); + final canonicalContent = utf8.encode( + jsonEncode({'report': report, 'schema_version': 2}), + ); + expect( + sha256.convert(canonicalContent).toString(), + '6eac3077aae8b992e8c752c2c71a137a5601ad94e52c8d8952e7261b179c9e95', + ); + }, + ); + + test( + 'retains the regional maximum independently of station and publication', + () { + final report = modern.copyWith( + list: { + '臺東縣': modern.list['臺東縣']!.copyWith(intensity: 3), + '花蓮縣': modern.list['花蓮縣']!, + }, + ); + final input = _decode(_convert(report))['report'] as Map; + expect(input['published_max_intensity'], isNull); + final areas = (input['areas'] as List).cast>(); + expect(areas.first['intensity'], 3); + expect(report.maxIntensity, 2); + }, + ); + + test( + 'keeps explicit observed zero and leaves an empty observation set empty', + () { + final zero = modern.copyWith( + list: { + '花蓮縣': AreaIntensity( + intensity: 0, + town: { + '紅葉': modern.list['花蓮縣']!.town['紅葉']!.copyWith(intensity: 0), + }, + ), + }, + ); + final zeroReport = + _decode(_convert(zero))['report'] as Map; + final area = (zeroReport['areas'] as List).single as Map; + final obs = + (zeroReport['observations'] as List).single as Map; + expect(area['intensity'], 0); + expect(obs['intensity'], 0); + expect(zeroReport['published_max_intensity'], isNull); + + final empty = modern.copyWith(list: {}); + expect(empty.maxIntensity, 0); + final emptyReport = + _decode(_convert(empty))['report'] as Map; + expect(emptyReport['areas'], isEmpty); + expect(emptyReport['observations'], isEmpty); + expect(emptyReport['published_max_intensity'], isNull); + }, + ); + + test( + 'orders by evidence IDs and emits identical immutable bytes repeatedly', + () { + final reordered = modern.copyWith( + list: { + for (final entry in modern.list.entries.toList().reversed) + entry.key: entry.value.copyWith( + town: Map.fromEntries(entry.value.town.entries.toList().reversed), + ), + }, + ); + final first = _convert(modern); + final second = adaptEarthquakeShareInput( + reordered, + evidence: _evidence(modern), + ) as EarthquakeShareInputV2; + expect(second.bytes, first.bytes); + expect(_convert(modern).bytes, first.bytes); + expect(() => first.bytes[0] = 0, throwsUnsupportedError); + + final report = _decode(first)['report'] as Map; + final areas = (report['areas'] as List).cast>(); + final observations = (report['observations'] as List) + .cast>(); + expect(areas.map((area) => area['id']), ['10014', '10015']); + expect(observations.map((obs) => obs['id']), [ + 'cwa:CHK', + 'cwa:ECB', + 'cwa:ECS', + 'cwa:EDH', + 'cwa:EHY', + ]); + }, + ); + + test('missing coordinate evidence identifies the specific source axis', () { + final decimals = Map.of(_decimals)..remove('/list/花蓮縣/town/紅葉/lon'); + _expectFailure( + adaptEarthquakeShareInput( + modern, + evidence: _evidence(modern, decimals: decimals), + ), + EarthquakeShareInputError.missingCoordinates, + '/list/花蓮縣/town/紅葉/lon', + ); + + // Actual omissions fail the existing non-nullable model decode upstream. + final raw = _readSource('modern')..remove('lat'); + expect(() => EarthquakeReport.fromJson(raw), throwsA(isA())); + }); + + test('validates a supplied axis even when its partner is missing', () { + final decimals = Map.of(_decimals) + ..remove('/lat') + ..['/lon'] = 'invalid'; + _expectFailure( + adaptEarthquakeShareInput( + modern, + evidence: _evidence(modern, decimals: decimals), + ), + EarthquakeShareInputError.malformedSource, + '/lon', + ); + }); + + test('rejects missing and duplicate station identities', () { + _expectFailure( + adaptEarthquakeShareInput( + modern, + evidence: _evidence(modern, stations: {}), + ), + EarthquakeShareInputError.missingStationIdentity, + '/list/臺東縣/town/成功', + ); + _expectFailure( + adaptEarthquakeShareInput( + modern, + evidence: _evidence( + modern, + stations: {..._stations, ('花蓮縣', '紅葉'): 'CHK'}, + ), + ), + EarthquakeShareInputError.duplicateIdentity, + '/list/花蓮縣/town/紅葉', + ); + }); + + test('rejects unknown magnitude kind and missing exact measurement', () { + _expectFailure( + adaptEarthquakeShareInput( + modern, + evidence: _evidence(modern, magnitudeIsMl: false), + ), + EarthquakeShareInputError.unknownMagnitudeType, + '/mag', + ); + _expectFailure( + adaptEarthquakeShareInput( + modern, + evidence: _evidence( + modern, + decimals: Map.of(_decimals)..remove('/mag'), + ), + ), + EarthquakeShareInputError.missingSourceDecimal, + '/mag', + ); + }); + + test('rejects an unproven or legacy scale and needs historical identity evidence', () { + final historical = EarthquakeReport.fromJson(_readSource('historical')); + expect(historical.list['臺南市']!.intensity, 9); + for (final scale in [null, ReportIntensityScale.legacy]) { + _expectFailure( + adaptEarthquakeShareInput( + historical, + evidence: _evidence( + historical, + requestedId: historical.id, + scale: scale, + ), + ), + EarthquakeShareInputError.unsupportedIntensityScale, + '/list', + ); + } + _expectFailure( + adaptEarthquakeShareInput( + historical, + evidence: _evidence( + historical, + requestedId: historical.id, + decimals: { + '/lat': '22.92', + '/lon': '120.54', + '/mag': '6.6', + '/depth': '14.6', + }, + counties: {}, + ), + ), + EarthquakeShareInputError.missingAreaIdentity, + '/list/南投縣', + ); + }); + + test('requires a matching full request ID and snapshot', () { + _expectFailure( + adaptEarthquakeShareInput(modern), + EarthquakeShareInputError.missingSourceIdentity, + '/id', + ); + _expectFailure( + adaptEarthquakeShareInput( + modern, + evidence: _evidence(modern, requestedId: modern.serial), + ), + EarthquakeShareInputError.missingSourceIdentity, + '/id', + ); + _expectFailure( + adaptEarthquakeShareInput( + modern.copyWith(id: modern.serial), + evidence: _evidence(modern, requestedId: modern.serial), + ), + EarthquakeShareInputError.missingSourceIdentity, + '/id', + ); + _expectFailure( + adaptEarthquakeShareInput( + modern.copyWith(time: modern.time + 1), + evidence: _evidence(modern), + ), + EarthquakeShareInputError.snapshotMismatch, + '', + ); + }); + + test('snapshot evidence owns a copy of the model maps', () { + final list = Map.of(modern.list); + final model = modern.copyWith(list: list); + final evidence = _evidence(model); + list.clear(); + _expectFailure( + adaptEarthquakeShareInput(model, evidence: evidence), + EarthquakeShareInputError.snapshotMismatch, + '', + ); + }); + + test('exact decimal conversion rounds both signs away from zero at ties', () { + final report = modern.copyWith( + latitude: 23.0900005, + longitude: -121.4000005, + ); + final bytes = adaptEarthquakeShareInput( + report, + evidence: _evidence( + report, + decimals: {..._decimals, '/lat': '23.0900005', '/lon': '-121.4000005'}, + ), + ) as EarthquakeShareInputV2; + final content = _decode(bytes)['report'] as Map; + expect(content['epicenter'], {'lat_e6': 23090001, 'lon_e6': -121400001}); + }); + + test('rejects malformed decimal source values before rounding', () { + final boundary = modern.copyWith(latitude: 90); + _expectFailure( + adaptEarthquakeShareInput( + boundary, + evidence: _evidence( + boundary, + decimals: {..._decimals, '/lat': '90.0000000000000001'}, + ), + ), + EarthquakeShareInputError.malformedSource, + '/lat', + ); + final nonFinite = modern.copyWith(latitude: double.infinity); + _expectFailure( + adaptEarthquakeShareInput(nonFinite, evidence: _evidence(nonFinite)), + EarthquakeShareInputError.malformedSource, + '/lat', + ); + final negativeZero = modern.copyWith(latitude: -0.0); + _expectFailure( + adaptEarthquakeShareInput( + negativeZero, + evidence: _evidence( + negativeZero, + decimals: {..._decimals, '/lat': '-0.00'}, + ), + ), + EarthquakeShareInputError.malformedSource, + '/lat', + ); + }); + + test('rejects an observation that exceeds its source regional maximum', () { + final report = modern.copyWith( + list: {...modern.list, '臺東縣': modern.list['臺東縣']!.copyWith(intensity: 0)}, + ); + _expectFailure( + adaptEarthquakeShareInput(report, evidence: _evidence(report)), + EarthquakeShareInputError.conflictingIntensity, + '/list/臺東縣/town/成功/int', + ); + }); +} diff --git a/test/features/earthquake/domain/fixtures/share_input/README.md b/test/features/earthquake/domain/fixtures/share_input/README.md new file mode 100644 index 000000000..2d014c791 --- /dev/null +++ b/test/features/earthquake/domain/fixtures/share_input/README.md @@ -0,0 +1,32 @@ +# 地震報告分享輸入 v2 離線樣本 + +兩份來源檔都是 2026-11-22 從 ExpTech Core v2 取得的完整 HTTP 本文。解碼後與 +eq-report-pic `b135d02bd1ba5103cd3d116a951b1b63a710a312` 的既有封存樣本相符。 +測試直接使用本機檔案。 + +| 檔案 | 來源 | 原始本文 SHA-256 | +| --- | --- | --- | +| `exptech-modern.json` | [2026-04-22 臺東縣近海](https://api.core-tnn1.exptech.dev/api/v2/eq/report/115000-2026-0422-111524) | `e6761038a7eea6b8afa58c936693f35d663bd5ca1ecdb2ad4613b72e2d46e4c1` | +| `exptech-historical.json` | [2016-02-06 美濃](https://api.core-tnn1.exptech.dev/api/v2/eq/report/105006-2016-0206-035726) | `45846febd73dde3e0d2bb29f456093cdb27663dee9b0217a6655c9eaf59a4971` | + +現代樣本沿用 eq-report-pic 已核對的完整測站對照。兩個縣市為臺東縣 `10014`、花蓮縣 +`10015`。五筆測站為成功 `CHK`、長濱 `ECB`、池上 `ECS`、東河 `EDH`、紅葉 `EHY`。 +對照適用於此快照。相關的氣象署附件、同事件公開報告及對照過程見既有來源紀錄。 +[eq-report-pic 來源紀錄](https://github.com/ExpTechTW/eq-report-pic/blob/b135d02bd1ba5103cd3d116a951b1b63a710a312/testdata/report-adapters/README.md) · +[內政部縣市代碼](https://data.gov.tw/dataset/17341) · +[氣象署公開報告](https://scweb.cwa.gov.tw/zh-tw/earthquake/details/2026042211152439) + +`exptech-modern.v2.json` 以既有獨立核對的 ExpTech 報告金樣本為基礎,加上 v2 envelope +與已查證的區域/測站 scoped ID。由 Dart 測試逐位元組比對完整 envelope。Rust +`ShareRenderInputV2::parse` 應產生區域來源的最大震度 2,以及下列 canonical content +SHA-256。 + +``` +6eac3077aae8b992e8c752c2c71a137a5601ad94e52c8d8952e7261b179c9e95 +``` + +美濃樣本保留 Core v2 序碼 9。氣象署原報告的舊制 7 級屬於另一份來源資料。測試覆蓋 +未知或舊制量表,以及採 Core v2 量表時仍欠缺適用於歷史快照的區域與測站身分。 +其他變體(例如明確 0、清單為空、缺座標證據與縣市最大值衝突)為合成測試。 +[ExpTech Core v2 API](https://exptech.dev/docs/api/earthquake/report/) · +[氣象署美濃原報告](https://scweb.cwa.gov.tw/zh-tw/earthquake/details/2016020603572666006) diff --git a/test/features/earthquake/domain/fixtures/share_input/exptech-historical.json b/test/features/earthquake/domain/fixtures/share_input/exptech-historical.json new file mode 100644 index 000000000..88cb2283f --- /dev/null +++ b/test/features/earthquake/domain/fixtures/share_input/exptech-historical.json @@ -0,0 +1 @@ +{"depth":14.6,"id":"105006-2016-0206-035726","lat":22.92,"list":{"南投縣":{"int":4,"town":{"南投市":{"lat":23.91,"lon":120.68,"int":3},"合歡山":{"lat":24.14,"lon":121.27,"int":3},"名間":{"lat":23.88,"lon":120.69,"int":4},"埔里":{"lat":24.01,"lon":120.96,"int":2},"日月潭":{"lat":23.88,"lon":120.91,"int":4},"魚池":{"lat":23.91,"lon":120.87,"int":3}}},"嘉義市":{"int":5,"town":{"嘉義市":{"lat":23.5,"lon":120.43,"int":5}}},"嘉義縣":{"int":5,"town":{"大埔":{"lat":23.24,"lon":120.62,"int":5},"草山":{"lat":23.35,"lon":120.59,"int":5},"阿里山":{"lat":23.51,"lon":120.81,"int":5}}},"基隆市":{"int":1,"town":{"基隆市":{"lat":25.15,"lon":121.77,"int":1}}},"宜蘭縣":{"int":3,"town":{"內城":{"lat":24.72,"lon":121.68,"int":2},"南山":{"lat":24.44,"lon":121.38,"int":3},"南澳":{"lat":24.43,"lon":121.75,"int":2},"宜蘭市":{"lat":24.76,"lon":121.76,"int":1},"牛鬥":{"lat":24.64,"lon":121.57,"int":2},"蘇澳":{"lat":24.61,"lon":121.86,"int":2},"龜山島":{"lat":24.84,"lon":121.94,"int":1}}},"屏東縣":{"int":5,"town":{"三地門":{"lat":22.74,"lon":120.64,"int":5},"九如":{"lat":22.72,"lon":120.5,"int":4},"南灣":{"lat":21.96,"lon":120.75,"int":3},"墾丁":{"lat":21.94,"lon":120.81,"int":2},"小琉球":{"lat":22.35,"lon":120.37,"int":3},"屏東市":{"lat":22.68,"lon":120.5,"int":4},"恆春":{"lat":22,"lon":120.75,"int":3},"枋寮":{"lat":22.37,"lon":120.63,"int":3},"鵝鑾鼻":{"lat":21.9,"lon":120.86,"int":2}}},"彰化縣":{"int":4,"town":{"員林":{"lat":23.96,"lon":120.58,"int":4},"大城":{"lat":23.86,"lon":120.29,"int":4}}},"新北市":{"int":2,"town":{"三貂角":{"lat":25.01,"lon":122,"int":1},"五分山":{"lat":25.07,"lon":121.78,"int":2},"五股":{"lat":25.1,"lon":121.42,"int":1},"萬里":{"lat":25.2,"lon":121.66,"int":1}}},"新竹市":{"int":2,"town":{"新竹市":{"lat":24.78,"lon":121.02,"int":2}}},"新竹縣":{"int":2,"town":{"竹北市":{"lat":24.83,"lon":121.01,"int":2},"竹東":{"lat":24.74,"lon":121.09,"int":2}}},"桃園市":{"int":2,"town":{"三光":{"lat":24.67,"lon":121.37,"int":2},"中壢":{"lat":24.97,"lon":121.19,"int":2},"桃園市":{"lat":25,"lon":121.3,"int":2}}},"澎湖縣":{"int":4,"town":{"東吉島":{"lat":23.26,"lon":119.67,"int":4},"馬公市":{"lat":23.57,"lon":119.56,"int":4}}},"臺中市":{"int":3,"town":{"德基":{"lat":24.25,"lon":121.16,"int":3},"臺中市":{"lat":24.15,"lon":120.68,"int":3}}},"臺北市":{"int":2,"town":{"信義區":{"lat":25.04,"lon":121.57,"int":2},"指南宮":{"lat":24.98,"lon":121.59,"int":1},"臺北市":{"lat":25.04,"lon":121.51,"int":2},"陽明山":{"lat":25.18,"lon":121.53,"int":1}}},"臺南市":{"int":9,"town":{"七股":{"lat":23.15,"lon":120.09,"int":5},"佳里":{"lat":23.17,"lon":120.2,"int":5},"善化":{"lat":23.14,"lon":120.29,"int":5},"新化":{"lat":23.08,"lon":120.36,"int":9},"東山":{"lat":23.27,"lon":120.5,"int":4},"楠西":{"lat":23.18,"lon":120.53,"int":5},"永康":{"lat":23.04,"lon":120.24,"int":5},"臺南市":{"lat":22.99,"lon":120.2,"int":5}}},"臺東縣":{"int":3,"town":{"利稻":{"lat":23.19,"lon":121.03,"int":3},"卑南":{"lat":22.82,"lon":121.08,"int":3},"大武":{"lat":22.36,"lon":120.9,"int":2},"太麻里":{"lat":22.6,"lon":120.96,"int":3},"安朔":{"lat":22.38,"lon":120.86,"int":3},"成功":{"lat":23.1,"lon":121.37,"int":3},"東河":{"lat":22.97,"lon":121.3,"int":3},"池上":{"lat":23.1,"lon":121.22,"int":3},"綠島":{"lat":22.67,"lon":121.47,"int":2},"臺東市":{"lat":22.75,"lon":121.16,"int":3},"蘭嶼":{"lat":22.04,"lon":121.56,"int":2},"長濱":{"lat":23.32,"lon":121.45,"int":3}}},"花蓮縣":{"int":3,"town":{"和平":{"lat":24.31,"lon":121.75,"int":2},"太魯閣":{"lat":24.16,"lon":121.62,"int":2},"玉里":{"lat":23.35,"lon":121.31,"int":2},"磯崎":{"lat":23.71,"lon":121.55,"int":3},"秀林":{"lat":24.08,"lon":121.6,"int":2},"紅葉":{"lat":23.5,"lon":121.33,"int":3},"花蓮市":{"lat":23.98,"lon":121.61,"int":3},"西林":{"lat":23.81,"lon":121.44,"int":2},"銅門":{"lat":23.97,"lon":121.49,"int":3},"鹽寮":{"lat":23.9,"lon":121.6,"int":3}}},"苗栗縣":{"int":3,"town":{"三義":{"lat":24.41,"lon":120.77,"int":3},"獅頭山":{"lat":24.63,"lon":121.01,"int":2},"竹南":{"lat":24.68,"lon":120.87,"int":2},"苗栗市":{"lat":24.56,"lon":120.83,"int":2},"鯉魚潭":{"lat":24.35,"lon":120.78,"int":3}}},"雲林縣":{"int":6,"town":{"古坑":{"lat":23.68,"lon":120.57,"int":5},"四湖":{"lat":23.64,"lon":120.23,"int":5},"斗六市":{"lat":23.71,"lon":120.54,"int":4},"草嶺":{"lat":23.6,"lon":120.68,"int":6}}},"高雄市":{"int":5,"town":{"旗山":{"lat":22.82,"lon":120.43,"int":5},"桃源":{"lat":23.16,"lon":120.77,"int":5}}}},"loc":"屏東縣政府北偏東方 27.1 公里 (位於高雄市美濃區)","lon":120.54,"mag":6.6,"time":1454702246000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/domain/fixtures/share_input/exptech-modern.json b/test/features/earthquake/domain/fixtures/share_input/exptech-modern.json new file mode 100644 index 000000000..4025bb351 --- /dev/null +++ b/test/features/earthquake/domain/fixtures/share_input/exptech-modern.json @@ -0,0 +1 @@ +{"depth":43.5,"id":"115000-2026-0422-111524","lat":23.09,"list":{"臺東縣":{"int":2,"town":{"成功":{"lat":23.1,"lon":121.37,"int":2},"東河":{"lat":22.97,"lon":121.3,"int":1},"池上":{"lat":23.1,"lon":121.22,"int":1},"長濱":{"lat":23.32,"lon":121.45,"int":2}}},"花蓮縣":{"int":1,"town":{"紅葉":{"lat":23.5,"lon":121.33,"int":1}}}},"loc":"臺東縣政府東北方 44.9 公里 (位於臺東縣近海)","lon":121.4,"mag":3.9,"time":1776827724000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/domain/fixtures/share_input/exptech-modern.v2.json b/test/features/earthquake/domain/fixtures/share_input/exptech-modern.v2.json new file mode 100644 index 000000000..3c4f35593 --- /dev/null +++ b/test/features/earthquake/domain/fixtures/share_input/exptech-modern.v2.json @@ -0,0 +1 @@ +{"locale":"zh-Hant","report":{"areas":[{"id":"10014","intensity":2,"name":{"en-US":null,"zh-Hant":"臺東縣"},"region_id":{"id":"10014","namespace":"tw.moi.county"}},{"id":"10015","intensity":1,"name":{"en-US":null,"zh-Hant":"花蓮縣"},"region_id":{"id":"10015","namespace":"tw.moi.county"}}],"depth_m":43500,"epicenter":{"lat_e6":23090000,"lon_e6":121400000},"intensity_scale":"cwa-2020","location":{"en-US":null,"zh-Hant":"臺東縣政府東北方 44.9 公里 (位於臺東縣近海)"},"magnitude":{"centi":390,"kind":"ml"},"observations":[{"area_id":"10014","id":"cwa:CHK","intensity":2,"name":{"en-US":null,"zh-Hant":"成功"},"position":{"lat_e6":23100000,"lon_e6":121370000},"station_id":{"id":"CHK","namespace":"cwa"}},{"area_id":"10014","id":"cwa:ECB","intensity":2,"name":{"en-US":null,"zh-Hant":"長濱"},"position":{"lat_e6":23320000,"lon_e6":121450000},"station_id":{"id":"ECB","namespace":"cwa"}},{"area_id":"10014","id":"cwa:ECS","intensity":1,"name":{"en-US":null,"zh-Hant":"池上"},"position":{"lat_e6":23100000,"lon_e6":121220000},"station_id":{"id":"ECS","namespace":"cwa"}},{"area_id":"10014","id":"cwa:EDH","intensity":1,"name":{"en-US":null,"zh-Hant":"東河"},"position":{"lat_e6":22970000,"lon_e6":121300000},"station_id":{"id":"EDH","namespace":"cwa"}},{"area_id":"10015","id":"cwa:EHY","intensity":1,"name":{"en-US":null,"zh-Hant":"紅葉"},"position":{"lat_e6":23500000,"lon_e6":121330000},"station_id":{"id":"EHY","namespace":"cwa"}}],"origin_time_unix_ms":1776827724000,"published_max_intensity":null},"schema_version":2,"source":{"event_id":null,"namespace":"exptech.eq-report-v2","publication":null,"report_id":"115000-2026-0422-111524","revision":null,"scale_evidence":{"kind":"dataset_contract","reference":"https://exptech.dev/docs/api/earthquake/report/"}}} \ No newline at end of file