From 471badef077d6046207385240e69d52e9af6ea2c Mon Sep 17 00:00:00 2001 From: jakedev99 <6440039+jake-dev-99@users.noreply.github.com> Date: Mon, 20 Apr 2026 00:18:41 -0400 Subject: [PATCH 01/23] v1.0.0-rc.2: expand golden tests to top 10 consumer languages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the last actionable gap from the war-plan audit (item 52i) before cutting 1.0.0 GA. Adds goldens for kotlin, swift, typescript, csharp, python, java, go, rust, cpp on top of the existing dart case. Each consumes a shared user_sample.input.json and produces an expected-output file. Languages with a `justTypes` option use it for leaner goldens; the rest emit quicktype-core defaults. Regenerate all in one pass via GOLDEN=update dart test test/integration/golden_test.dart --tags=integration The remaining 12 TargetType values (elixir, elm, flow, haskell, javascript, objc, php, proptypes, ruby, scala, smithy, +Smithy) stay uncovered — gated on a consumer ask; trivial to add later. Co-Authored-By: Claude Opus 4.7 (1M context) --- CHANGELOG.md | 35 ++++++++ android/build.gradle | 2 +- ios/quicktype_dart.podspec | 2 +- lib/src/version.dart | 2 +- macos/quicktype_dart.podspec | 2 +- pubspec.yaml | 2 +- test/integration/golden_test.dart | 89 ++++++++++++++++--- .../goldens/user_cpp_just_types.cpp.txt | 58 ++++++++++++ test/integration/goldens/user_csharp.cs.txt | 67 ++++++++++++++ .../goldens/user_go_just_types.go.txt | 12 +++ .../goldens/user_java_just_types.java.txt | 41 +++++++++ test/integration/goldens/user_kotlin.kt.txt | 28 ++++++ .../goldens/user_python_just_types.py.txt | 25 ++++++ test/integration/goldens/user_rust.rs.txt | 34 +++++++ ...ypes.input.json => user_sample.input.json} | 0 .../goldens/user_swift_just_types.swift.txt | 20 +++++ .../goldens/user_typescript_just_types.ts.txt | 12 +++ 17 files changed, 413 insertions(+), 18 deletions(-) create mode 100644 test/integration/goldens/user_cpp_just_types.cpp.txt create mode 100644 test/integration/goldens/user_csharp.cs.txt create mode 100644 test/integration/goldens/user_go_just_types.go.txt create mode 100644 test/integration/goldens/user_java_just_types.java.txt create mode 100644 test/integration/goldens/user_kotlin.kt.txt create mode 100644 test/integration/goldens/user_python_just_types.py.txt create mode 100644 test/integration/goldens/user_rust.rs.txt rename test/integration/goldens/{user_dart_just_types.input.json => user_sample.input.json} (100%) create mode 100644 test/integration/goldens/user_swift_just_types.swift.txt create mode 100644 test/integration/goldens/user_typescript_just_types.ts.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 296743e..e736461 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,40 @@ # Changelog +## 1.0.0-rc.2 + +**Golden test coverage expansion** — closes the last actionable gap +from the war-plan audit before cutting 1.0.0 GA. Adds 9 new +golden-file cases to `test/integration/golden_test.dart` so +regressions in the top 10 consumer target languages get caught on +every PR. + +### Added + +- **Goldens for 9 additional target languages** — `kotlin`, `swift`, + `typescript`, `csharp`, `python`, `java`, `go`, `rust`, `cpp`. Each + consumes a shared input (`test/integration/goldens/user_sample.input.json`) + and produces an expected-output file + (`test/integration/goldens/..txt`). Languages with a + `justTypes` renderer option use it for leaner, review-friendlier + goldens; the rest emit quicktype-core defaults. +- **Regenerate all goldens in one pass**: `GOLDEN=update dart test + test/integration/golden_test.dart --tags=integration`. + +### Changed + +- `test/integration/golden_test.dart` refactored to share a single + `user_sample.input.json` fixture across every case. The existing + `user_dart_just_types.input.json` was renamed accordingly — cases + now reference `_sharedInput` instead of per-case input files. + +### Still intentionally uncovered (post-1.0 tracking) + +The 12 remaining `TargetType` values (elixir, elm, flow, haskell, +javascript, objc, php, proptypes, ruby, scala, smithy, and the +`Smithy` variant) don't have goldens yet. Adding one is a two-line +change — append a `_Case` + rerun `GOLDEN=update`. Gated on a +consumer asking. + ## 1.0.0-rc.1 **First release candidate for 1.0.** No code changes on top of 0.9.0 — diff --git a/android/build.gradle b/android/build.gradle index 5c170b6..04d84ba 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -4,7 +4,7 @@ // Flutter's plugin system expects this file at `android/build.gradle`. group = "io.simplezen.quicktype_dart" -version = "1.0.0-rc.1" +version = "1.0.0-rc.2" buildscript { repositories { diff --git a/ios/quicktype_dart.podspec b/ios/quicktype_dart.podspec index b9129dd..f5bae18 100644 --- a/ios/quicktype_dart.podspec +++ b/ios/quicktype_dart.podspec @@ -8,7 +8,7 @@ Pod::Spec.new do |s| s.name = 'quicktype_dart' - s.version = '1.0.0-rc.1' + s.version = '1.0.0-rc.2' s.summary = 'Cross-platform type generation from JSON.' s.description = <<-DESC Embeds quicktype-core inside a QuickJS-NG runtime via FFI so Flutter diff --git a/lib/src/version.dart b/lib/src/version.dart index 06e19f6..e7e3f07 100644 --- a/lib/src/version.dart +++ b/lib/src/version.dart @@ -4,4 +4,4 @@ /// The current `quicktype_dart` package version. Mirrors the `version:` /// entry in pubspec.yaml so the CLI, native podspecs, and Gradle build /// files stay in lockstep. -const String packageVersion = '1.0.0-rc.1'; +const String packageVersion = '1.0.0-rc.2'; diff --git a/macos/quicktype_dart.podspec b/macos/quicktype_dart.podspec index 4ef98cd..1105604 100644 --- a/macos/quicktype_dart.podspec +++ b/macos/quicktype_dart.podspec @@ -10,7 +10,7 @@ Pod::Spec.new do |s| s.name = 'quicktype_dart' - s.version = '1.0.0-rc.1' + s.version = '1.0.0-rc.2' s.summary = 'Cross-platform type generation from JSON.' s.description = <<-DESC Embeds quicktype-core inside a QuickJS-NG runtime via FFI so Flutter diff --git a/pubspec.yaml b/pubspec.yaml index b4bded0..54c75ef 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,7 +4,7 @@ description: >- Produces Dart, Kotlin, Swift, TypeScript, and 18 other languages — at build time via build_runner, or at runtime from in-memory data. A pigeon-analogue for arbitrarily-nested typed data. -version: 1.0.0-rc.1 +version: 1.0.0-rc.2 homepage: https://www.simplezen.io repository: https://github.com/jake-dev-99/quicktype_dart issue_tracker: https://github.com/jake-dev-99/quicktype_dart/issues diff --git a/test/integration/golden_test.dart b/test/integration/golden_test.dart index 8572229..c470d59 100644 --- a/test/integration/golden_test.dart +++ b/test/integration/golden_test.dart @@ -1,17 +1,28 @@ -// Golden-file tests for the public `QuicktypeDart.generate` surface. +// Golden-file tests for the public `QuicktypeDart.generate` surface, +// covering each primary consumer target language so a quicktype-core +// upgrade or renderer-option change can't silently regress output. // -// Each golden consists of: -// * test/integration/goldens/.input.json — payload -// * test/integration/goldens/..txt — expected output +// Layout: +// test/integration/goldens/user_sample.input.json — shared payload +// test/integration/goldens/..txt — expected output +// where is the `name` on `_Case` and is +// `target.extensions.first.substring(1)`. // -// To update a golden after an intentional output change, re-run with -// the `GOLDEN=update` environment variable: +// To update every golden after an intentional output change, re-run +// with the `GOLDEN=update` environment variable: // // GOLDEN=update dart test test/integration/golden_test.dart \ // --tags=integration // // Any quicktype-core upgrade or renderer-option change that affects // output has to land with a matching golden update in the same PR. +// +// Primary consumer targets covered today: +// dart, kotlin, swift, typescript, csharp, python, java, go, rust, +// cpp (10 of 22 `TargetType` values). The remaining 12 (elixir, +// elm, flow, haskell, javascript, objc, php, proptypes, ruby, scala, +// smithy) are intentionally uncovered until a consumer asks; adding +// them is trivial — append another `_Case` + regenerate. @Tags(['integration']) library; @@ -23,32 +34,81 @@ import 'package:quicktype_dart/quicktype_dart.dart'; import 'package:test/test.dart'; const _goldenDir = 'test/integration/goldens'; +const _sharedInput = 'user_sample'; class _Case { const _Case(this.name, this.target, this.options); + + /// Short identifier used as the golden filename stem. final String name; + + /// Target language. final TargetType target; + + /// Language-specific renderer options. `null` = quicktype-core + /// defaults. Targets that expose `justTypes` use it to produce + /// leaner, more review-friendly goldens. final RendererOptions? options; } void main() { + // Cases intentionally use `justTypes: true` where available so the + // goldens focus on type-shape regressions (not serializer + // boilerplate). Languages without a `justTypes` option fall back to + // the quicktype-core default shape. final cases = <_Case>[ const _Case( 'user_dart_just_types', TargetType.dart, DartRendererOptions(justTypes: true), ), + const _Case('user_kotlin', TargetType.kotlin, null), + const _Case( + 'user_swift_just_types', + TargetType.swift, + SwiftRendererOptions(justTypes: true), + ), + const _Case( + 'user_typescript_just_types', + TargetType.typescript, + TypeScriptRendererOptions(justTypes: true), + ), + const _Case('user_csharp', TargetType.csharp, null), + const _Case( + 'user_python_just_types', + TargetType.python, + PythonRendererOptions(justTypes: true), + ), + const _Case( + 'user_java_just_types', + TargetType.java, + JavaRendererOptions(justTypes: true), + ), + const _Case( + 'user_go_just_types', + TargetType.go, + GoRendererOptions(justTypes: true), + ), + const _Case('user_rust', TargetType.rust, null), + const _Case( + 'user_cpp_just_types', + TargetType.cpp, + CppRendererOptions(justTypes: true), + ), ]; final updateMode = Platform.environment['GOLDEN'] == 'update'; group('golden files', () { + final input = + File(p.join(_goldenDir, '$_sharedInput.input.json')).readAsStringSync(); + for (final c in cases) { test(c.name, () async { - final inputPath = p.join(_goldenDir, '${c.name}.input.json'); - final goldenPath = p.join(_goldenDir, - '${c.name}.${c.target.extensions.first.substring(1)}.txt'); - final input = File(inputPath).readAsStringSync(); + final goldenPath = p.join( + _goldenDir, + '${c.name}.${c.target.extensions.first.substring(1)}.txt', + ); final actual = await QuicktypeDart.generateFromString( label: 'User', json: input, @@ -60,9 +120,12 @@ void main() { return; } final expected = File(goldenPath).readAsStringSync(); - expect(actual, equals(expected), - reason: 'Golden drift for ${c.name}. ' - 'Regenerate with GOLDEN=update if intentional.'); + expect( + actual, + equals(expected), + reason: 'Golden drift for ${c.name}. ' + 'Regenerate with GOLDEN=update if intentional.', + ); }); } }); diff --git a/test/integration/goldens/user_cpp_just_types.cpp.txt b/test/integration/goldens/user_cpp_just_types.cpp.txt new file mode 100644 index 0000000..d136e53 --- /dev/null +++ b/test/integration/goldens/user_cpp_just_types.cpp.txt @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include + +class Profile { + public: + Profile() = default; + virtual ~Profile() = default; + + private: + int64_t age; + bool active; + + public: + const int64_t & get_age() const { return age; } + int64_t & get_mutable_age() { return age; } + void set_age(const int64_t & value) { this->age = value; } + + const bool & get_active() const { return active; } + bool & get_mutable_active() { return active; } + void set_active(const bool & value) { this->active = value; } +}; + +class User { + public: + User() = default; + virtual ~User() = default; + + private: + int64_t id; + std::string name; + std::string email; + std::vector roles; + Profile profile; + + public: + const int64_t & get_id() const { return id; } + int64_t & get_mutable_id() { return id; } + void set_id(const int64_t & value) { this->id = value; } + + const std::string & get_name() const { return name; } + std::string & get_mutable_name() { return name; } + void set_name(const std::string & value) { this->name = value; } + + const std::string & get_email() const { return email; } + std::string & get_mutable_email() { return email; } + void set_email(const std::string & value) { this->email = value; } + + const std::vector & get_roles() const { return roles; } + std::vector & get_mutable_roles() { return roles; } + void set_roles(const std::vector & value) { this->roles = value; } + + const Profile & get_profile() const { return profile; } + Profile & get_mutable_profile() { return profile; } + void set_profile(const Profile & value) { this->profile = value; } +}; diff --git a/test/integration/goldens/user_csharp.cs.txt b/test/integration/goldens/user_csharp.cs.txt new file mode 100644 index 0000000..0b90b56 --- /dev/null +++ b/test/integration/goldens/user_csharp.cs.txt @@ -0,0 +1,67 @@ +// +// +// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do: +// +// using QuickType; +// +// var user = User.FromJson(jsonString); + +namespace QuickType +{ + using System; + using System.Collections.Generic; + + using System.Globalization; + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + + public partial class User + { + [JsonProperty("id")] + public long Id { get; set; } + + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("email")] + public string Email { get; set; } + + [JsonProperty("roles")] + public string[] Roles { get; set; } + + [JsonProperty("profile")] + public Profile Profile { get; set; } + } + + public partial class Profile + { + [JsonProperty("age")] + public long Age { get; set; } + + [JsonProperty("active")] + public bool Active { get; set; } + } + + public partial class User + { + public static User FromJson(string json) => JsonConvert.DeserializeObject(json, QuickType.Converter.Settings); + } + + public static class Serialize + { + public static string ToJson(this User self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings); + } + + internal static class Converter + { + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings + { + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, + DateParseHandling = DateParseHandling.None, + Converters = + { + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } + }, + }; + } +} diff --git a/test/integration/goldens/user_go_just_types.go.txt b/test/integration/goldens/user_go_just_types.go.txt new file mode 100644 index 0000000..5892910 --- /dev/null +++ b/test/integration/goldens/user_go_just_types.go.txt @@ -0,0 +1,12 @@ +type User struct { + ID int64 `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + Roles []string `json:"roles"` + Profile Profile `json:"profile"` +} + +type Profile struct { + Age int64 `json:"age"` + Active bool `json:"active"` +} diff --git a/test/integration/goldens/user_java_just_types.java.txt b/test/integration/goldens/user_java_just_types.java.txt new file mode 100644 index 0000000..3c0a141 --- /dev/null +++ b/test/integration/goldens/user_java_just_types.java.txt @@ -0,0 +1,41 @@ +// User.java + +package io.quicktype; + +public class User { + private long id; + private String name; + private String email; + private String[] roles; + private Profile profile; + + public long getID() { return id; } + public void setID(long value) { this.id = value; } + + public String getName() { return name; } + public void setName(String value) { this.name = value; } + + public String getEmail() { return email; } + public void setEmail(String value) { this.email = value; } + + public String[] getRoles() { return roles; } + public void setRoles(String[] value) { this.roles = value; } + + public Profile getProfile() { return profile; } + public void setProfile(Profile value) { this.profile = value; } +} + +// Profile.java + +package io.quicktype; + +public class Profile { + private long age; + private boolean active; + + public long getAge() { return age; } + public void setAge(long value) { this.age = value; } + + public boolean getActive() { return active; } + public void setActive(boolean value) { this.active = value; } +} diff --git a/test/integration/goldens/user_kotlin.kt.txt b/test/integration/goldens/user_kotlin.kt.txt new file mode 100644 index 0000000..46116cb --- /dev/null +++ b/test/integration/goldens/user_kotlin.kt.txt @@ -0,0 +1,28 @@ +// To parse the JSON, install Klaxon and do: +// +// val user = User.fromJson(jsonString) + +package quicktype + +import com.beust.klaxon.* + +private val klaxon = Klaxon() + +data class User ( + val id: Long, + val name: String, + val email: String, + val roles: List, + val profile: Profile +) { + public fun toJson() = klaxon.toJsonString(this) + + companion object { + public fun fromJson(json: String) = klaxon.parse(json) + } +} + +data class Profile ( + val age: Long, + val active: Boolean +) diff --git a/test/integration/goldens/user_python_just_types.py.txt b/test/integration/goldens/user_python_just_types.py.txt new file mode 100644 index 0000000..4493dce --- /dev/null +++ b/test/integration/goldens/user_python_just_types.py.txt @@ -0,0 +1,25 @@ +from typing import List + + +class Profile: + age: int + active: bool + + def __init__(self, age: int, active: bool) -> None: + self.age = age + self.active = active + + +class User: + id: int + name: str + email: str + roles: List[str] + profile: Profile + + def __init__(self, id: int, name: str, email: str, roles: List[str], profile: Profile) -> None: + self.id = id + self.name = name + self.email = email + self.roles = roles + self.profile = profile diff --git a/test/integration/goldens/user_rust.rs.txt b/test/integration/goldens/user_rust.rs.txt new file mode 100644 index 0000000..608e896 --- /dev/null +++ b/test/integration/goldens/user_rust.rs.txt @@ -0,0 +1,34 @@ +// Example code that deserializes and serializes the model. +// extern crate serde; +// #[macro_use] +// extern crate serde_derive; +// extern crate serde_json; +// +// use generated_module::User; +// +// fn main() { +// let json = r#"{"answer": 42}"#; +// let model: User = serde_json::from_str(&json).unwrap(); +// } + +use serde::{Serialize, Deserialize}; + +#[derive(Serialize, Deserialize)] +pub struct User { + id: i64, + + name: String, + + email: String, + + roles: Vec, + + profile: Profile, +} + +#[derive(Serialize, Deserialize)] +pub struct Profile { + age: i64, + + active: bool, +} diff --git a/test/integration/goldens/user_dart_just_types.input.json b/test/integration/goldens/user_sample.input.json similarity index 100% rename from test/integration/goldens/user_dart_just_types.input.json rename to test/integration/goldens/user_sample.input.json diff --git a/test/integration/goldens/user_swift_just_types.swift.txt b/test/integration/goldens/user_swift_just_types.swift.txt new file mode 100644 index 0000000..5d03c38 --- /dev/null +++ b/test/integration/goldens/user_swift_just_types.swift.txt @@ -0,0 +1,20 @@ +// This file was generated from JSON Schema using quicktype, do not modify it directly. +// To parse the JSON, add this file to your project and do: +// +// let user = try User(json) + +import Foundation + +// MARK: - User +struct User { + let id: Int + let name, email: String + let roles: [String] + let profile: Profile +} + +// MARK: - Profile +struct Profile { + let age: Int + let active: Bool +} diff --git a/test/integration/goldens/user_typescript_just_types.ts.txt b/test/integration/goldens/user_typescript_just_types.ts.txt new file mode 100644 index 0000000..a7af67b --- /dev/null +++ b/test/integration/goldens/user_typescript_just_types.ts.txt @@ -0,0 +1,12 @@ +export interface User { + id: number; + name: string; + email: string; + roles: string[]; + profile: Profile; +} + +export interface Profile { + age: number; + active: boolean; +} From 4b4d85aba051fec0aaaa72756f8cf15f7da21027 Mon Sep 17 00:00:00 2001 From: jakedev99 <6440039+jake-dev-99@users.noreply.github.com> Date: Mon, 20 Apr 2026 00:51:09 -0400 Subject: [PATCH 02/23] fix(file-resolver): repair multi-extension glob and drop debug chatter Rewrites FileResolver.getFiles around proper brace-expansion glob syntax. The previous path silently matched nothing whenever a SourceType declared more than one extension (graphql's `{.graphqls, .graphql}` rendered as Set.toString() with spaces, which glob rejects). Also removes the canonicalize() that could corrupt wildcard segments on non-POSIX platforms, surfaces FormatException errors as ConfigException, and drops the library-level Log.off chatter that FileResolver should never have been emitting. Adds unit coverage under test/unit/file_resolver_test.dart for single/multi-extension matching, direct file paths, invalid extensions, empty extension sets, trailing-slash handling, pre-wildcarded patterns, and resolveTargetPath's directory/file-path forms. Backlog: A1.1, A1.2, A1.3, A1.10, A2.1, B1.1. --- lib/src/utils/file_resolver.dart | 150 +++++++++++++++--------------- test/unit/file_resolver_test.dart | 140 ++++++++++++++++++++++++++++ 2 files changed, 216 insertions(+), 74 deletions(-) create mode 100644 test/unit/file_resolver_test.dart diff --git a/lib/src/utils/file_resolver.dart b/lib/src/utils/file_resolver.dart index 184dee4..72f6765 100644 --- a/lib/src/utils/file_resolver.dart +++ b/lib/src/utils/file_resolver.dart @@ -1,104 +1,106 @@ import 'dart:io'; -import 'package:path/path.dart' as p; - import 'package:glob/glob.dart'; import 'package:glob/list_local_fs.dart'; -import 'package:quicktype_dart/src/models/type.dart'; -import 'logging.dart'; +import 'package:path/path.dart' as p; + import '../config.dart'; +import '../models/type.dart'; -/// Handles file pattern matching and path resolution +/// Expands config-declared paths into concrete source-file lists, filtered +/// by the [TypeEnum.extensions] set of the declaring type. +/// +/// Package-private. The Config/Quicktype orchestration layer is the only +/// caller; end users reach for `QuicktypeDart.generate` or the build_runner +/// builders instead. class FileResolver { - /// Finds all files matching a pattern + FileResolver._(); + + /// Returns the set of absolute file paths under [pattern] whose extension + /// is one of [extensions]. + /// + /// [pattern] may be: + /// * A specific file whose extension is already in [extensions] — the + /// file is returned as-is if it exists. + /// * A directory — every immediate child with a matching extension + /// (via `{ext1,ext2}` brace expansion) is returned. + /// * A glob — passed through; matches filtered against [extensions]. /// - /// Handles glob patterns and directory traversal + /// [extensions] entries include the leading dot (e.g. `.json`, + /// `.schema.json`). At least one entry is required. /// - /// @param pattern File pattern to match (e.g., "*.json" or "/path/to/file.json") - /// @return List of matching file paths + /// Throws [ConfigException] if [extensions] is empty, if [pattern] has an + /// extension outside [extensions], or if the glob is malformed. static Set getFiles(String pattern, Set extensions) { - // Set to store the matched files (to avoid duplicates) - final matches = {}; - final validExtensions = extensions; - try { - pattern = p.canonicalize(pattern); - final String patternExtension = p.extension(pattern); - String searchExtensions = validExtensions.length > 1 - ? validExtensions.toSet().toString() - : validExtensions.first; - - // Sanity check the extensions list, and finalize which extensions to search - if (patternExtension.isEmpty) { - pattern = pattern.endsWith('*') ? pattern : '$pattern/*'; - } else { - if (validExtensions.contains(patternExtension)) { - searchExtensions = patternExtension; - } else { - throw ConfigException( - 'Invalid extension: $patternExtension', - ); - } - } + if (extensions.isEmpty) { + throw ConfigException( + 'FileResolver.getFiles requires at least one extension; ' + 'got an empty set for pattern "$pattern".', + ); + } - // Build the list of matched files - Log.off(''); - Log.off('Searching for $searchExtensions'); - Log.off(pattern); - try { - final glob = Glob('$pattern$searchExtensions'); - final files = glob.listSync().toList(); - for (final file in files) { - if (file is File) { - final String fileExtension = p.extension(file.path, 2); - if (searchExtensions.contains(fileExtension)) { - matches.add(file.absolute.path); - } - } - } - } catch (e) { - Log.severe('Error: $e'); - } + final matchedExt = _longestEndsWithMatch(pattern, extensions); + final String globPattern; + if (matchedExt != null) { + globPattern = pattern; + } else if (p.extension(pattern).isNotEmpty) { + throw ConfigException( + 'Invalid extension "${p.extension(pattern)}" in pattern "$pattern". ' + 'Allowed: ${extensions.join(", ")}.', + ); + } else { + final prefix = pattern.endsWith('*') ? pattern : '$pattern/*'; + final extAlt = extensions.length == 1 + ? extensions.first + : '{${extensions.join(',')}}'; + globPattern = '$prefix$extAlt'; + } - if (matches.isNotEmpty) { - int counter = 0; - for (final file in matches) { - counter++; - Log.info(' ($counter/${matches.length}): $file'); + final matches = {}; + try { + for (final entity in Glob(globPattern).listSync()) { + if (entity is! File) continue; + if (_longestEndsWithMatch(entity.path, extensions) != null) { + matches.add(entity.absolute.path); } - } else { - Log.info(' (0/0): No files found'); } - return matches; - } catch (e) { - throw ConfigException('Error resolving files for pattern: $pattern', e); + } on FormatException catch (e) { + throw ConfigException( + 'Invalid glob pattern "$globPattern": ${e.message}', + e, + ); } + return matches; } - /// Determines a target path based on source file and configuration + /// Derives the on-disk output path for a generated artifact. /// - /// @param sourcePath The source file path - /// @param targetConfig The target configuration - /// @param targetType The target Type type - /// @return The resolved target path + /// The result directory is [TypeConfig.path] when it already points at a + /// directory, or its parent when it points at a file. The file stem is + /// taken from [sourcePath]; the extension from [TargetType.extensions]. static String resolveTargetPath( String sourcePath, TargetType targetType, TypeConfig targetConfig, ) { final sourceName = p.basenameWithoutExtension(sourcePath); + final targetExt = targetType.extensions.first; + final targetName = '$sourceName$targetExt'; final targetPath = targetConfig.path; - final targetPathExt = p.extension(targetPath); - - final targetExt = - targetType.extensions.first; // Default to the first extension value - final targetName = '$sourceName$targetExt'; + final parent = p.extension(targetPath).isEmpty + ? targetPath + : p.dirname(targetPath); + return p.join(parent, targetName); + } - // Make sure you're referencing a folder - String parentFolder = targetPath; - if (targetPathExt.isNotEmpty) { - parentFolder = p.dirname(targetPath); + static String? _longestEndsWithMatch(String path, Set extensions) { + String? best; + for (final ext in extensions) { + if (path.endsWith(ext) && (best == null || ext.length > best.length)) { + best = ext; + } } - return p.join(parentFolder, targetName); + return best; } } diff --git a/test/unit/file_resolver_test.dart b/test/unit/file_resolver_test.dart new file mode 100644 index 0000000..316e095 --- /dev/null +++ b/test/unit/file_resolver_test.dart @@ -0,0 +1,140 @@ +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:quicktype_dart/src/config.dart'; +import 'package:quicktype_dart/src/models/type.dart'; +import 'package:quicktype_dart/src/utils/file_resolver.dart'; +import 'package:test/test.dart'; + +void main() { + group('FileResolver.getFiles', () { + late Directory sandbox; + + setUp(() { + sandbox = Directory.systemTemp.createTempSync('qt_fileresolver_'); + }); + + tearDown(() { + sandbox.deleteSync(recursive: true); + }); + + File touch(String rel, [String body = '{}']) => + File(p.join(sandbox.path, rel)) + ..parent.createSync(recursive: true) + ..writeAsStringSync(body); + + test('returns matching files under a directory (single extension)', () { + touch('a.json'); + touch('b.json'); + touch('c.txt'); + final matches = FileResolver.getFiles(sandbox.path, {'.json'}); + expect(matches.length, 2); + expect(matches.every((m) => m.endsWith('.json')), isTrue); + }); + + test('multi-extension brace expansion matches every listed extension', () { + touch('schema.graphql', 'type A { a: Int }'); + touch('other.graphqls', 'type B { b: Int }'); + touch('skip.txt', 'nope'); + final matches = FileResolver.getFiles( + sandbox.path, + {'.graphql', '.graphqls'}, + ); + expect(matches.length, 2); + expect( + matches.map(p.basename).toSet(), + {'schema.graphql', 'other.graphqls'}, + ); + }); + + test('matches multi-dot extensions (.schema.json) without collapsing', () { + touch('user.schema.json'); + touch('other.json'); + final matches = + FileResolver.getFiles(sandbox.path, {'.schema.json'}); + expect(matches.length, 1); + expect(matches.single, endsWith('user.schema.json')); + }); + + test('accepts a pattern that points directly at a file', () { + final f = touch('direct.json'); + final matches = FileResolver.getFiles(f.path, {'.json'}); + expect(matches.single, f.absolute.path); + }); + + test('rejects a pattern whose extension is not in the allowed set', () { + expect( + () => FileResolver.getFiles('models/file.xml', {'.json'}), + throwsA(isA().having( + (e) => e.message, + 'message', + contains('.xml'), + )), + ); + }); + + test('rejects an empty extension set', () { + expect( + () => FileResolver.getFiles(sandbox.path, {}), + throwsA(isA()), + ); + }); + + test('returns an empty set when the directory has no matches', () { + touch('a.txt'); + final matches = FileResolver.getFiles(sandbox.path, {'.json'}); + expect(matches, isEmpty); + }); + + test('trailing slash vs no trailing slash both resolve the directory', + () { + touch('a.json'); + final withSlash = FileResolver.getFiles('${sandbox.path}/', {'.json'}); + final without = FileResolver.getFiles(sandbox.path, {'.json'}); + expect(withSlash, without); + }); + + test('pre-existing trailing wildcard is preserved (no double /*)', () { + touch('a.json'); + touch('b.json'); + final matches = + FileResolver.getFiles('${sandbox.path}/*', {'.json'}); + expect(matches.length, 2); + }); + }); + + group('FileResolver.resolveTargetPath', () { + test('joins the source stem and target extension under a directory', () { + const cfg = TypeConfig(type: TargetType.dart, path: 'lib/models/'); + final out = FileResolver.resolveTargetPath( + '/tmp/user.json', + TargetType.dart, + cfg, + ); + expect(out, p.join('lib/models/', 'user.dart')); + }); + + test('uses the parent of a file-shaped target path', () { + const cfg = TypeConfig(type: TargetType.dart, path: 'lib/models/x.dart'); + final out = FileResolver.resolveTargetPath( + '/tmp/user.json', + TargetType.dart, + cfg, + ); + expect(p.dirname(out), 'lib/models'); + expect(p.basename(out), 'user.dart'); + }); + + test('multi-dot source extensions strip only the last segment', () { + // Behavior note: `user.schema.json` yields `user.schema.dart`. Users + // who want cleaner names should pre-strip or rename the source. + const cfg = TypeConfig(type: TargetType.dart, path: 'lib/models/'); + final out = FileResolver.resolveTargetPath( + '/tmp/user.schema.json', + TargetType.dart, + cfg, + ); + expect(p.basename(out), 'user.schema.dart'); + }); + }); +} From 9fff79ff7919116f2ac86baa42f645b7e6b5239e Mon Sep 17 00:00:00 2001 From: jakedev99 <6440039+jake-dev-99@users.noreply.github.com> Date: Mon, 20 Apr 2026 00:54:47 -0400 Subject: [PATCH 03/23] refactor(process): unify quicktype subprocess runner + argv builder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Collapses two parallel Process-transport implementations into one path: * Adds lib/src/internal/quicktype_process.dart exposing resolveQuicktypeExecutable(), findOnPath(), and runQuicktypeProcess(). Timeout, launch failures, and command formatting live here. * Adds lib/src/internal/argv.dart with rendererOptionsToArgv(), used by both backend_io's auto/process path and QuicktypeCommand.argv. Single source of truth for --flag / --no-flag / --flag value encoding. * backend_io._runViaProcess, Quicktype.execute, and Quicktype.executeNative now all go through the shared runner — no more CWD-relative exe in quicktype.dart (was './tool/node_modules/.bin/quicktype', silently broken whenever the CLI was invoked from any other directory). * Quicktype.execute now honors QuicktypeDart.processTimeout, surfaces stdout/stderr on Log.info/Log.warning consistently with backend_io, and preserves stack traces instead of splitting them line-by-line through Log.severe. * Fixes the result.stdout.toString().isNotEmpty idiom — stdout from Process.run (default encoding) is already String. Backlog: A1.4, A1.5, A1.9, A3.1, A3.3, A3.4, A8.1, E8.3. --- lib/src/backend_io.dart | 90 +++---------------------- lib/src/internal/argv.dart | 25 +++++++ lib/src/internal/quicktype_process.dart | 89 ++++++++++++++++++++++++ lib/src/models/command.dart | 34 ++++------ lib/src/quicktype.dart | 89 +++++++++--------------- 5 files changed, 167 insertions(+), 160 deletions(-) create mode 100644 lib/src/internal/argv.dart create mode 100644 lib/src/internal/quicktype_process.dart diff --git a/lib/src/backend_io.dart b/lib/src/backend_io.dart index 100b989..5c8e642 100644 --- a/lib/src/backend_io.dart +++ b/lib/src/backend_io.dart @@ -12,13 +12,13 @@ import 'dart:io'; import 'package:crypto/crypto.dart' as crypto; import 'package:path/path.dart' as p; -import 'facade.dart' show GenerateTransport, QuicktypeDart; +import 'facade.dart' show GenerateTransport; import 'ffi/ffi_runtime.dart'; +import 'internal/argv.dart'; +import 'internal/quicktype_process.dart'; import 'models/type.dart'; import 'quicktype.dart'; import 'utils/logging.dart'; -import 'utils/paths.dart'; -import 'utils/shell.dart'; /// Backend entry point. Platform-independent argument handling already /// happened in [QuicktypeDart.generateFromString]; this function just @@ -70,7 +70,6 @@ Future _runViaProcess({ required TargetType target, required Map rendererOptions, }) async { - final exe = await _resolveQuicktypeExecutable(); final tempDir = await Directory.systemTemp.createTemp('quicktype_dart_'); try { final safeLabel = _sanitizeLabel(label); @@ -89,45 +88,14 @@ Future _runViaProcess({ target.argName, '--out', targetFile.path, + ...rendererOptionsToArgv(rendererOptions), ]; - // Serialize renderer options as CLI flags. Boolean-style "false" values - // become --no-; "true" collapses to --; everything else - // is -- . - for (final entry in rendererOptions.entries) { - if (entry.value == 'true') { - argv.add('--${entry.key}'); - } else if (entry.value == 'false') { - argv.add('--no-${entry.key}'); - } else { - argv.addAll(['--${entry.key}', entry.value]); - } - } - final timeout = QuicktypeDart.processTimeout; - final commandStr = formatCommand(exe, argv); - final ProcessResult result; - try { - result = await Process.run(exe, argv).timeout(timeout); - } on TimeoutException { - throw QuicktypeException( - 'quicktype subprocess timed out after ${timeout.inSeconds}s. ' - 'Raise the limit via QuicktypeDart.processTimeout if generations ' - 'legitimately take longer.', - command: commandStr, - ); - } catch (e, st) { - throw QuicktypeException( - 'Failed to run quicktype: $e', - command: commandStr, - cause: e, - stackTrace: st, - ); - } + final result = await runQuicktypeProcess(argv); if (result.exitCode != 0) { throw QuicktypeException( 'quicktype exited with code ${result.exitCode}: ${result.stderr}', - command: commandStr, exitCode: result.exitCode, ); } @@ -135,19 +103,14 @@ Future _runViaProcess({ // Surface any advisory output the child emitted on success. Previously // deprecation notices and compatibility warnings were discarded; they // now land on Log.info / Log.warning so callers can see them. - final stdoutStr = result.stdout.toString(); - if (stdoutStr.trim().isNotEmpty) { - Log.info(stdoutStr.trimRight()); - } - final stderrStr = result.stderr.toString(); - if (stderrStr.trim().isNotEmpty) { - Log.warning(stderrStr.trimRight()); - } + final stdoutStr = result.stdout as String; + if (stdoutStr.trim().isNotEmpty) Log.info(stdoutStr.trimRight()); + final stderrStr = result.stderr as String; + if (stderrStr.trim().isNotEmpty) Log.warning(stderrStr.trimRight()); if (!targetFile.existsSync()) { throw QuicktypeException( 'quicktype reported success but no output file was produced', - command: commandStr, exitCode: result.exitCode, ); } @@ -197,41 +160,6 @@ void _sweepOrphans() { ..addAll(still); } -/// Resolves a usable `quicktype` executable, independent of caller CWD. -/// Checks the bundled `tool/node_modules/.bin/quicktype` first; falls back -/// to a `quicktype` found on `PATH`. -Future _resolveQuicktypeExecutable() async { - final bundled = await bundledQuicktypeExe(); - if (bundled != null) return bundled; - - final onPath = _findOnPath('quicktype'); - if (onPath != null) return onPath; - - throw const QuicktypeException( - 'quicktype not found. Install it with `npm install -g quicktype`, or ' - 'make sure the bundled binary exists at ' - '/$bundledQuicktypeExeRelative. Alternatively, use ' - '`transport: GenerateTransport.ffi` to run via the embedded ' - 'QuickJS runtime.', - ); -} - -String? _findOnPath(String name) { - final pathEnv = Platform.environment['PATH']; - if (pathEnv == null || pathEnv.isEmpty) return null; - final separator = Platform.isWindows ? ';' : ':'; - final candidates = - Platform.isWindows ? ['$name.cmd', '$name.exe', name] : [name]; - for (final dir in pathEnv.split(separator)) { - if (dir.isEmpty) continue; - for (final cand in candidates) { - final full = p.join(dir, cand); - if (File(full).existsSync()) return full; - } - } - return null; -} - /// Makes [label] safe to use as a filename stem. Non-alphanumeric chars /// collapse to `_`; a leading digit gets a `T_` prefix. When any /// substitution actually happened, a short content-hash suffix is diff --git a/lib/src/internal/argv.dart b/lib/src/internal/argv.dart new file mode 100644 index 0000000..48e84f3 --- /dev/null +++ b/lib/src/internal/argv.dart @@ -0,0 +1,25 @@ +// Shared conversion from the `Map` renderer-options shape +// that quicktype-core expects into the argv fragment the quicktype CLI +// accepts. Used by both the Process-transport runner and the +// QuicktypeCommand builder so any future convention change (e.g. flipping +// bool encoding) is a one-file edit. + +/// Flattens [options] into `--flag value` pairs: +/// +/// * `'true'` → `--flag` +/// * `'false'` → `--no-flag` +/// * anything else → `--flag value` +List rendererOptionsToArgv(Map options) { + final out = []; + for (final entry in options.entries) { + switch (entry.value) { + case 'true': + out.add('--${entry.key}'); + case 'false': + out.add('--no-${entry.key}'); + default: + out.addAll(['--${entry.key}', entry.value]); + } + } + return out; +} diff --git a/lib/src/internal/quicktype_process.dart b/lib/src/internal/quicktype_process.dart new file mode 100644 index 0000000..518b754 --- /dev/null +++ b/lib/src/internal/quicktype_process.dart @@ -0,0 +1,89 @@ +// Shared subprocess helpers for the Process transport. Used by both the +// facade's auto/process path (backend_io.dart) and the config-driven +// Quicktype orchestrator (quicktype.dart) so they agree on: +// +// 1. How the quicktype executable is located (bundled node_modules first, +// then PATH). Nobody resolves relative to `Directory.current` any more. +// 2. How timeouts, launch failures, and command-line formatting surface +// as QuicktypeException. +// +// dart:io only — never imported from backend_web.dart. + +import 'dart:async'; +import 'dart:io'; + +import 'package:path/path.dart' as p; + +import '../facade.dart' show QuicktypeDart; +import '../quicktype.dart' show QuicktypeException; +import '../utils/paths.dart'; +import '../utils/shell.dart'; + +/// Resolves the on-disk `quicktype` executable. Checks the bundled +/// `tool/node_modules/.bin/quicktype` (independent of caller CWD) and +/// falls back to a `PATH` lookup. Throws [QuicktypeException] when +/// neither is available so callers don't have to repeat the message. +Future resolveQuicktypeExecutable() async { + final bundled = await bundledQuicktypeExe(); + if (bundled != null) return bundled; + final onPath = findOnPath('quicktype'); + if (onPath != null) return onPath; + throw const QuicktypeException( + 'quicktype not found. Install it with `npm install -g quicktype`, or ' + 'make sure the bundled binary exists at ' + '/$bundledQuicktypeExeRelative. Alternatively, use ' + '`transport: GenerateTransport.ffi` to run via the embedded ' + 'QuickJS runtime.', + ); +} + +/// Locates [name] on the current `PATH`. Returns null if not found. +/// Honors platform-specific separators and Windows extensions. +String? findOnPath(String name) { + final pathEnv = Platform.environment['PATH']; + if (pathEnv == null || pathEnv.isEmpty) return null; + final separator = Platform.isWindows ? ';' : ':'; + final candidates = + Platform.isWindows ? ['$name.cmd', '$name.exe', name] : [name]; + for (final dir in pathEnv.split(separator)) { + if (dir.isEmpty) continue; + for (final cand in candidates) { + final full = p.join(dir, cand); + if (File(full).existsSync()) return full; + } + } + return null; +} + +/// Runs the resolved quicktype CLI with [argv] and returns the +/// [ProcessResult]. The caller inspects `exitCode`/`stdout`/`stderr`. +/// +/// Throws [QuicktypeException] when the subprocess can't be launched or +/// exceeds [timeout] (defaulting to [QuicktypeDart.processTimeout]). +/// Does *not* throw on non-zero exit codes — the caller decides how to +/// interpret those. +Future runQuicktypeProcess( + List argv, { + Duration? timeout, +}) async { + final exe = await resolveQuicktypeExecutable(); + final effectiveTimeout = timeout ?? QuicktypeDart.processTimeout; + final commandStr = formatCommand(exe, argv); + try { + return await Process.run(exe, argv).timeout(effectiveTimeout); + } on TimeoutException { + throw QuicktypeException( + 'quicktype subprocess timed out after ${effectiveTimeout.inSeconds}s. ' + 'Raise the limit via QuicktypeDart.processTimeout if generations ' + 'legitimately take longer.', + command: commandStr, + ); + } catch (e, st) { + throw QuicktypeException( + 'Failed to run quicktype: $e', + command: commandStr, + cause: e, + stackTrace: st, + ); + } +} diff --git a/lib/src/models/command.dart b/lib/src/models/command.dart index daca605..cc96a67 100644 --- a/lib/src/models/command.dart +++ b/lib/src/models/command.dart @@ -2,6 +2,7 @@ import 'package:build/build.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; +import '../internal/argv.dart'; import '../utils/type_infer.dart'; import 'type.dart'; @@ -75,26 +76,15 @@ class QuicktypeCommand { /// Argv list suitable for `Process.run`. List get argv => _toArgv(); - List _toArgv() { - final out = [ - '--src', - path.canonicalize(sourcePath), - '--src-lang', - sourceArg, - '--lang', - targetArg, - '--out', - path.canonicalize(targetPath), - ]; - for (final entry in rendererOptions.entries) { - if (entry.value == 'true') { - out.add('--${entry.key}'); - } else if (entry.value == 'false') { - out.add('--no-${entry.key}'); - } else { - out.addAll(['--${entry.key}', entry.value]); - } - } - return out; - } + List _toArgv() => [ + '--src', + path.canonicalize(sourcePath), + '--src-lang', + sourceArg, + '--lang', + targetArg, + '--out', + path.canonicalize(targetPath), + ...rendererOptionsToArgv(rendererOptions), + ]; } diff --git a/lib/src/quicktype.dart b/lib/src/quicktype.dart index e64f608..de78851 100644 --- a/lib/src/quicktype.dart +++ b/lib/src/quicktype.dart @@ -6,18 +6,12 @@ import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'config.dart'; +import 'internal/quicktype_process.dart'; import 'models/command.dart'; import 'models/result.dart'; import 'utils/file_resolver.dart'; import 'utils/logging.dart'; -/// Default path to the bundled quicktype Node CLI relative to the package -/// root. Used by the `quicktype.json`-driven flow (see [Quicktype.execute]) -/// so dev tooling can exercise the Process transport without requiring -/// a global install. If the bundled binary isn't present, callers fall -/// through to a PATH lookup via [Quicktype.executeNative]. -const String _quicktypeExe = './tool/node_modules/.bin/quicktype'; - /// Thrown when a quicktype subprocess call fails or its output can't be /// consumed. Carries the failing command and exit code when available, /// plus the underlying [cause] and its [stackTrace] when wrapping another @@ -151,43 +145,36 @@ class Quicktype { try { final parentDir = Directory(path.dirname(targetPath)); - if (!parentDir.existsSync()) { - parentDir.createSync(recursive: true); - } + if (!parentDir.existsSync()) parentDir.createSync(recursive: true); - final ProcessResult result; - try { - result = await Process.run(_quicktypeExe, command.argv); - } catch (e, st) { - throw QuicktypeException( - 'Failed to run quicktype: $e', - command: '$_quicktypeExe ${command.argv.join(' ')}', - cause: e, - stackTrace: st, - ); - } - if (result.exitCode == 0) { - if (result.stdout.toString().isNotEmpty) { - Log.off('${result.stdout}'); - } - Log.off('Done!'); - } else { - Log.severe('Error: ${result.stderr}'); + final result = await runQuicktypeProcess(command.argv); + + final stdoutStr = (result.stdout as String).trimRight(); + final stderrStr = (result.stderr as String).trimRight(); + + if (result.exitCode != 0) { + if (stderrStr.isNotEmpty) Log.warning(stderrStr); return QuicktypeResult.failure( sourcePath: sourcePath, targetPath: targetPath, - errorMessage: result.stderr.toString(), + errorMessage: stderrStr.isNotEmpty + ? stderrStr + : 'quicktype exited with code ${result.exitCode}', + stdout: stdoutStr.isEmpty ? null : stdoutStr, + stderr: stderrStr.isEmpty ? null : stderrStr, ); } + + if (stdoutStr.isNotEmpty) Log.info(stdoutStr); + if (stderrStr.isNotEmpty) Log.warning(stderrStr); return QuicktypeResult.success( sourcePath: sourcePath, targetPath: targetPath, + stdout: stdoutStr.isEmpty ? null : stdoutStr, + stderr: stderrStr.isEmpty ? null : stderrStr, ); } catch (e, s) { - Log.severe('Error: $e'); - for (final line in s.toString().split('\n')) { - Log.severe(line); - } + Log.severe('Error: $e\n$s'); return QuicktypeResult.failure( sourcePath: sourcePath, targetPath: targetPath, @@ -196,33 +183,21 @@ class Quicktype { } } - /// Passes [args] straight through to the `quicktype` on `PATH`, bypassing - /// config and command construction. Used when the CLI is invoked with - /// positional args beyond the known flags. + /// Passes [args] straight through to the resolved `quicktype` CLI + /// (bundled first, then PATH), bypassing config and command construction. + /// Used when the CLI is invoked with positional args beyond the known + /// flags. static Future executeNative(List args) async { - Log.off(''); - Log.off('Running native quicktype: ${args.join(' ')}'); - + Log.info('Running quicktype ${args.join(' ')}'); try { - final result = await Process.run('quicktype', args); - - if (result.stdout.toString().isNotEmpty) { - Log.off('Result: ${result.stdout}'); - } - - if (result.stderr.toString().isNotEmpty) { - Log.off('Result: ${result.stderr}'); - } - + final result = await runQuicktypeProcess(args); + final stdoutStr = (result.stdout as String).trimRight(); + final stderrStr = (result.stderr as String).trimRight(); + if (stdoutStr.isNotEmpty) Log.info(stdoutStr); + if (stderrStr.isNotEmpty) Log.warning(stderrStr); return result.exitCode; - } catch (e) { - if (e is ProcessException && e.executable == 'quicktype') { - Log.off(''); - Log.off('Error: Native quicktype not found'); - Log.off('Install with: npm install -g quicktype'); - } else { - Log.off('Error: $e'); - } + } on QuicktypeException catch (e) { + Log.severe(e.toString()); return 1; } } From 1396dce7dca78c21c198d74c6d5271919c4d49f1 Mon Sep 17 00:00:00 2001 From: jakedev99 <6440039+jake-dev-99@users.noreply.github.com> Date: Mon, 20 Apr 2026 00:56:10 -0400 Subject: [PATCH 04/23] fix(backend_web): cancel listeners, handle missing , extract polling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hardens the web bundle loader against three failure modes: * Null-safe parent resolution — falls back from to to , throwing a clear QuicktypeException if none exist. Removes the previous `document.head!` force-unwrap. * Cancels every script.onLoad / script.onError StreamSubscription in a finally block. Retried loads no longer accumulate stale listeners. * Folds the existing-script polling loop into _pollForQtConvert() and splits the fresh-inject path into _injectAndWait() for readability. The injection path now also carries its own Future.timeout() guard. Backlog: A1.6, A1.7, A7.1. --- lib/src/backend_web.dart | 147 ++++++++++++++++++++++++++------------- 1 file changed, 99 insertions(+), 48 deletions(-) diff --git a/lib/src/backend_web.dart b/lib/src/backend_web.dart index 33aadc8..5aa0564 100644 --- a/lib/src/backend_web.dart +++ b/lib/src/backend_web.dart @@ -85,51 +85,92 @@ Future _loadBundle() async { final existing = web.document.querySelector('script[data-quicktype-dart="bundle"]'); if (existing == null) { - final script = web.document.createElement('script') as web.HTMLScriptElement - ..src = url - ..async = true - ..setAttribute('data-quicktype-dart', 'bundle'); - if (integrity != null) { - script.setAttribute('integrity', integrity); - script.setAttribute('crossorigin', 'anonymous'); + await _injectAndWait(url, integrity); + } else { + await _waitForExistingScript(existing as web.HTMLScriptElement, url); + } + + if (_qtConvertRaw == null) { + throw QuicktypeException( + 'quicktype_dart: the bundle script finished loading but ' + 'globalThis.qtConvert is not defined. The JS bundle at $url is ' + 'either corrupt or not a quicktype_dart bundle.', + ); + } +} + +/// Creates a fresh `