diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d179d57 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,13 @@ +# Force LF line endings on checkout for files the build and tests +# compare byte-for-byte. Git's default `core.autocrlf=true` on Windows +# would otherwise rewrite committed LF to CRLF at checkout, breaking: +# +# * Golden-file comparisons in test/integration/goldens/ — quicktype +# emits LF on every platform; the goldens were generated with LF. +# * API-snapshot drift detection in tool/api_snapshot.txt. +# +# Everything else stays on the repo default (Dart / Markdown / YAML +# round-trip fine under either convention). +test/integration/goldens/*.txt text eol=lf +test/integration/goldens/*.json text eol=lf +tool/api_snapshot.txt text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d7d4fe2..38f5c21 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,8 +74,12 @@ jobs: path: coverage/lcov.info integration: - name: Integration tests (ubuntu) - runs-on: ubuntu-latest + name: Integration tests (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] steps: - uses: actions/checkout@v4 - uses: subosito/flutter-action@v2 @@ -83,13 +87,40 @@ jobs: channel: stable - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' - name: Install quicktype globally - run: npm install -g quicktype + # Pinned to the version whose Process-transport output the + # golden files were generated against. Bump here + regenerate + # goldens (GOLDEN=update) in the same commit when rolling. + run: npm install -g quicktype@23.2.0 - run: flutter pub get - name: Integration tests run: dart test test/integration --tags=integration + ffi-noembed: + name: FFI (no embedded bundle) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + - run: flutter pub get + - name: Install CMake + build deps + run: | + sudo apt-get update + sudo apt-get install -y cmake build-essential + - name: Configure + build with QT_EMBED_BUNDLE=OFF + # QT_EMBED_BUNDLE=OFF skips the embed_bundle.py custom command, + # so the native/bundle/ Node toolchain isn't needed for this + # leg — the binary ships without bundle bytes and relies on a + # runtime fetch via BundleSource.remote(...). + run: | + cmake -S native -B build/native -DQT_EMBED_BUNDLE=OFF + cmake --build build/native + - name: Run ffi_noembed smoke test + run: dart run tool/smoke/ffi_noembed_smoke.dart + example: name: Example build_runner runs-on: ubuntu-latest @@ -100,11 +131,13 @@ jobs: channel: stable - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' - name: Install quicktype globally # build_runner's auto transport falls through to Process on CI # (FFI plugin isn't pre-built); needs `quicktype` on PATH. - run: npm install -g quicktype + # Pinned to the version example/lib/models/user.dart was + # generated against — bump here and regenerate in the same PR. + run: npm install -g quicktype@23.2.0 - name: Install deps working-directory: example run: dart pub get diff --git a/CHANGELOG.md b/CHANGELOG.md index 296743e..74b5077 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,126 @@ # Changelog +## 1.0.0-rc.2 + +**War-on-debt audit pass** — two rounds of code review before 1.0.0 +GA. Fixes two silent-but-real correctness bugs, closes architecture / +hygiene gaps, expands test + CI coverage, tightens the public API +with a few breaking changes that land cleanly pre-1.0. + +### Breaking + +- **`Log` and `inferLangType` dropped from the public barrel.** Both + had leaked out as internal helpers. Tests that need them import + from `package:quicktype_dart/src/...` directly. +- **`Log.off` deleted.** It routed through `dart:developer.log` at + OFF level — nothing consumed it, so running + `quicktype_dart --help` produced zero stdout. CLI code now writes + `stdout`/`stderr` directly; structured events + (`Log.info`/`warning`/`severe`) route through `Logger('quicktype')` + from `package:logging`. +- **`QuicktypeDart.setBundleSource(src)` → field assignment**: + `QuicktypeDart.bundleSource = src`. Getter unchanged. +- **`Config.loadOrDefaults(path)` → named parameters**: + `Config.loadOrDefaults(path: 'foo.json', strict: true)`. Adds + `strict` (defaults to `false`); CLI opts in so malformed configs + don't silently fall back to defaults. +- **`TargetType.smithy` removed.** No variant of the argName round- + trips through the bundled quicktype-core — the Smithy renderer + class is in the JS bundle but not wired to the language-dispatch + API upstream. Re-adds when upstream wires it up. + +### Fixed + +- **`TargetType.c.argName` was `'c'`; quicktype-core needs + `'cjson'`.** The committed golden had been a one-line `"Unknown + language name: c"` that passed trivially by matching the error + string. Fixed; the regenerated golden now contains real cJSON + struct + parse/serialize definitions. +- **FileResolver multi-extension glob** — graphql (two extensions) + silently matched nothing because the set was concatenated as + `'{.graphqls, .graphql}'` (space-padded via `Set.toString()`). + Proper brace-expansion now. +- **CLI silence** — `--help`, `--version`, and error messages were + swallowed by `Log.off` routing through `dart:developer.log`. See + above. +- **Golden test accepts error output** — `_assertLooksLikeCode` now + rejects outputs starting with `Unknown language name:`, `Error:`, + `TypeError:`, `at ReferenceError`, or fewer than 5 lines, even in + `GOLDEN=update` mode. +- **Web backend leaks** — script `onLoad`/`onError` subscriptions + now cancelled in a `finally`; parent element resolves `` → + `` → `` instead of force-unwrapping `.head!`. +- **CWD-relative quicktype path** — `Quicktype.execute` no longer + uses `./tool/node_modules/.bin/quicktype`. Routes through shared + `resolveQuicktypeExecutable()` so invocation from any cwd works. +- **Lossy stack trace** in `Quicktype.execute`'s catch block. +- **Process timeout actually kills the child** — `runQuicktypeProcess` + now uses `Process.start` + manual `.kill()` on timeout instead of + `Process.run().timeout()` (which only times out the Dart Future). + +### Added + +- **Goldens for every `TargetType`** — 21 cases (dart, kotlin, + swift, typescript, csharp, python, java, go, rust, c, elixir, + elm, flow, haskell, javascript, objc, php, proptypes, ruby, + scala). Deterministic under Process transport, `quicktype@23.2.0` + pinned in CI so local + CI agree byte-for-byte. `cpp` intentionally + absent: `quicktype --lang cpp` emits "Error: Internal error: ." + upstream on inputs with nested objects; re-add when fixed. +- **`RendererOptions.raw(Map)` factory** for callers + who already hold the kebab-case map (builder uses it). +- **`coerceRendererOptionsMap` accepts `num`** — YAML + `indentation: 2` Just Works. +- **Shared process runner** (`lib/src/internal/quicktype_process.dart`) + — `resolveQuicktypeExecutable`, `findOnPath`, `runQuicktypeProcess`. + Kills the `Quicktype.execute` ↔ `backend_io._runViaProcess` + duplication. +- **`rendererOptionsToArgv` helper** (`lib/src/internal/argv.dart`) + — single source of truth for `--flag` / `--no-flag` / `--flag + value` encoding. +- **`TempDirSweeper` class** — Windows-retry cleanup encapsulated, + testable, observable via `deferredCount`. +- **`putOpt(map, key, value)` helper** — collapses ~120 lines of + null-check boilerplate across 22 language-option files. +- **CI: integration matrix on Ubuntu + macOS + Windows** (was + Ubuntu-only). +- **CI: `ffi-noembed` job** — builds `native/` with + `-DQT_EMBED_BUNDLE=OFF` and runs `tool/smoke/ffi_noembed_smoke.dart`. +- **`tool/smoke/README.md`** documenting which smoke scripts are + CI-wired vs manual-only. +- **Unit tests** for argv, `RendererOptions.raw`, `TempDirSweeper`, + `package_layout`, and expanded `config_test.dart` (strict mode, + fromMap shape errors, `ConfigException.toString`, mkdir side + effect). + +### Changed + +- **`lib/src/utils/` retired** in favor of purpose-named homes: + `paths.dart` → `internal/package_layout.dart`, `shell.dart` → + `internal/shell.dart`, `type_infer.dart` → `models/type_infer.dart`, + `logging.dart` → `src/logging.dart`, `file_resolver.dart` → + `src/file_resolver.dart`. +- **`TargetType.defaultPath`** rewritten as an exhaustive Dart 3 + switch expression — adding a new `TargetType` is now a compile + error here until handled. +- **`_detectFilesForTarget`** narrows its catch from `Object` to + `FormatException` + `FileSystemException`, with remediation hints. +- **`Config.defaults()`** side effect (mkdir `models/`) now + documented at factory and class level. +- **Tool hardening**: `refresh_bundle.dart` probes `bash`/`python3` + and sanity-checks the repo root; `sync_version.dart` hard-fails on + missing targets (was warn-and-skip); `install_hooks.dart` checks + `chmod` exit; `embed_bundle.py` wraps file I/O with clear errors. + +### Deferred (post-1.0) + +- Upstream fix for `quicktype -l cpp` internal-error; re-add the cpp + golden when it lands. +- Full `Log` migration to richer `package:logging` usage (per- + subsystem filtering, LogRecord formatting, test subscription + harness). Current setup (root INFO forwarded to stdout/stderr in + the CLI) is enough to ship. + ## 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/entrypoint_cli.dart b/lib/entrypoint_cli.dart index 7bfc126..f7975f9 100644 --- a/lib/entrypoint_cli.dart +++ b/lib/entrypoint_cli.dart @@ -1,10 +1,12 @@ import 'dart:async'; import 'dart:io'; + import 'package:args/args.dart'; +import 'package:logging/logging.dart'; import 'src/config.dart'; +import 'src/internal/quicktype_process.dart'; import 'src/quicktype.dart'; -import 'src/utils/logging.dart'; import 'src/version.dart'; /// Entry point for the `quicktype_dart` CLI. @@ -19,6 +21,8 @@ import 'src/version.dart'; class QuicktypeCLI { /// Runs the CLI with [args] and returns the exit code (0 on success). static Future run(List args) async { + _installLogForwarder(); + final parser = ArgParser() ..addOption('config', abbr: 'c', @@ -32,15 +36,13 @@ class QuicktypeCLI { try { final options = parser.parse(args); - // Handle help request if (options.flag('help')) { _printUsage(); return 0; } - // Handle version request if (options.flag('version')) { - _printVersion(); + await _printVersion(); return 0; } @@ -49,12 +51,11 @@ class QuicktypeCLI { return await Quicktype.executeNative(options.rest); } - // Run with specified config final configPath = options.option('config') ?? Config.defaultConfigFile; return await _generateFromConfig(configPath); } catch (e, stackTrace) { - Log.off('Error: $e'); - Log.off('Stack trace: $stackTrace'); + stderr.writeln('Error: $e'); + stderr.writeln(stackTrace); return 1; } } @@ -63,21 +64,26 @@ class QuicktypeCLI { /// commands, and executes them. Returns exit code 0 on full success, /// 1 if any command failed. static Future _generateFromConfig(String configPath) async { - Log.off('Running quicktype with config: $configPath'); + stdout.writeln('Running quicktype with config: $configPath'); - final quicktype = Quicktype(Config.loadOrDefaults(configPath)); + // CLI invocations surface config-parse errors directly instead of + // silently running with defaults — the user asked for this config, + // we don't get to decide it's invalid. + final quicktype = + Quicktype(Config.loadOrDefaults(path: configPath, strict: true)); final commands = await quicktype.buildCommandsFromConfig(); final results = await quicktype.executeAll(commands); final successCount = results.where((r) => r.success).length; - Log.off('Generated $successCount/${results.length} files successfully'); + stdout.writeln( + 'Generated $successCount/${results.length} files successfully'); - // Print any errors final failures = results.where((r) => !r.success).toList(); if (failures.isNotEmpty) { - Log.off('\nErrors:'); + stderr.writeln('\nErrors:'); for (final f in failures) { - Log.off(' - ${f.sourcePath} → ${f.targetPath}: ${f.errorMessage}'); + stderr.writeln( + ' - ${f.sourcePath} → ${f.targetPath}: ${f.errorMessage}'); } return 1; } @@ -85,9 +91,9 @@ class QuicktypeCLI { return 0; } - /// Print CLI usage information + /// Print CLI usage information. static void _printUsage() { - Log.off(''' + stdout.writeln(''' Quicktype Dart - Generate types from schemas Usage: @@ -102,23 +108,51 @@ Examples: quicktype Generate using quicktype.json quicktype -c custom.json Generate using custom.json -For more details: https://github.com/yourusername/quicktype_dart +For more details: https://github.com/jake-dev-99/quicktype_dart '''); } - /// Print version information - static void _printVersion() { - Log.off('Quicktype Dart v$packageVersion'); - + /// Print version information. + static Future _printVersion() async { + stdout.writeln('Quicktype Dart v$packageVersion'); try { - final result = Process.runSync('quicktype', ['--version']); + final exe = await resolveQuicktypeExecutable(); + final result = Process.runSync(exe, ['--version']); if (result.exitCode == 0) { - Log.off('Native quicktype: ${result.stdout.toString().trim()}'); + stdout.writeln('Native quicktype: ${(result.stdout as String).trim()}'); } else { - Log.off('Native quicktype: not available'); + stdout.writeln('Native quicktype: exited ${result.exitCode}'); } - } catch (_) { - Log.off('Native quicktype: not installed'); + } on QuicktypeException { + stdout.writeln('Native quicktype: not installed'); + } catch (e) { + stdout.writeln('Native quicktype: $e'); } } + + /// Wires the **root** logger's records (everything under + /// `Logger.root`, including our `Logger('quicktype')` tree and any + /// transitive `package:logging` consumers) to stdout/stderr so + /// library diagnostics (`Log.info` etc.) reach the terminal when run + /// as a CLI. Sets the root level to INFO on entry. + /// + /// Idempotent: re-runs in the same process (tests) cancel the + /// previous subscription before attaching a new one. + static void _installLogForwarder() { + Logger.root.level = Level.INFO; + _logSubscription?.cancel(); + _logSubscription = Logger.root.onRecord.listen((record) { + // Process stdout/stderr are owned by the runtime; never close them. + if (record.level >= Level.WARNING) { + stderr.writeln('[${record.level.name}] ${record.message}'); + } else { + stdout.writeln('[${record.level.name}] ${record.message}'); + } + }); + } + + // ignore: cancel_subscriptions + // Subscription lives for the process lifetime; cancellation happens + // on re-entry (tests) via _installLogForwarder above. + static StreamSubscription? _logSubscription; } diff --git a/lib/entrypoint_runner.dart b/lib/entrypoint_runner.dart index c1828d0..22e6a8c 100644 --- a/lib/entrypoint_runner.dart +++ b/lib/entrypoint_runner.dart @@ -3,7 +3,7 @@ import 'package:build/build.dart'; import 'src/models/renderer_options.dart'; import 'src/models/type.dart'; import 'src/facade.dart'; -import 'src/utils/logging.dart'; +import 'src/logging.dart'; /// Top-level factory referenced from `build.yaml`. /// @@ -65,7 +65,7 @@ class _QuicktypeBuilder implements Builder { label: label, json: json, target: targetType, - options: _MapRendererOptions(rendererOptions), + options: RendererOptions.raw(rendererOptions), ); final outputId = _outputAssetId(input, targetType); @@ -84,18 +84,6 @@ class _QuicktypeBuilder implements Builder { } } -/// Thin adapter that lets the builder pass an already-coerced -/// `Map` through the typed [options] parameter on -/// [QuicktypeDart.generateFromString] without having to pick a -/// specific `*RendererOptions` subclass per language. -class _MapRendererOptions extends RendererOptions { - const _MapRendererOptions(this._map); - final Map _map; - - @override - Map toRendererOptions() => _map; -} - /// Derives a PascalCase top-level type name from `foo_bar.qt.json`. String _labelFromAsset(AssetId input) { final basename = input.pathSegments.last.replaceAll('.qt.json', ''); diff --git a/lib/quicktype_dart.dart b/lib/quicktype_dart.dart index 29da9fd..ae55ebf 100644 --- a/lib/quicktype_dart.dart +++ b/lib/quicktype_dart.dart @@ -38,7 +38,3 @@ export 'src/models/enums.dart'; // Config + orchestration export 'src/config.dart' show Config, ConfigException; export 'src/quicktype.dart' show Quicktype, QuicktypeException; - -// Utilities -export 'src/utils/logging.dart' show Log; -export 'src/utils/type_infer.dart' show inferLangType; diff --git a/lib/src/backend_io.dart b/lib/src/backend_io.dart index 100b989..c5d5658 100644 --- a/lib/src/backend_io.dart +++ b/lib/src/backend_io.dart @@ -12,13 +12,14 @@ 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 'internal/temp_dir_sweeper.dart'; +import 'logging.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 @@ -48,7 +49,10 @@ Future generateFromString({ rendererOptions: rendererOptions, ); case GenerateTransport.auto: - throw StateError('unreachable'); + // Unreachable: _resolveTransport() below converts `auto` to a + // concrete ffi/process value before this switch runs. The case + // is present only to make the switch exhaustive. + throw StateError('auto should have been resolved to ffi or process'); } } @@ -70,7 +74,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 +92,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,102 +107,35 @@ 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, ); } - return targetFile.readAsString(); + // MUST await — the `finally` block below deletes `tempDir`. + // Without `await`, Dart returns the unread Future *first*, the + // `finally` fires and `cleanup` deletes the temp dir, and only + // then does the file read actually start. On Linux the open FD + // survives the unlink so the read still succeeds; on macOS + // (APFS) it throws PathNotFoundException — which is exactly + // what broke the golden tests on `Integration tests + // (macos-latest)` while Ubuntu stayed green. + return await targetFile.readAsString(); } finally { - _cleanupTempDir(tempDir); - } -} - -/// Deletes [tempDir] best-effort, with one retry + queue for a later -/// sweep if the first attempt hits a Windows file-lock. The second-chance -/// sweep runs on the next `_runViaProcess` invocation via [_sweepOrphans]. -void _cleanupTempDir(Directory tempDir) { - _sweepOrphans(); - try { - if (tempDir.existsSync()) { - tempDir.deleteSync(recursive: true); - } - } catch (e) { - _deferredOrphans.add(tempDir.path); - Log.warning( - 'Failed to clean up temp dir ${tempDir.path}: $e. Will retry on ' - 'next invocation.', - ); + _sweeper.cleanup(tempDir); } } -/// Paths queued for a second-chance cleanup pass. Windows can keep files -/// locked briefly after the subprocess exits; this lets the next run -/// reclaim them instead of leaking into the user's temp dir. -final Set _deferredOrphans = {}; - -void _sweepOrphans() { - if (_deferredOrphans.isEmpty) return; - final still = {}; - for (final path in _deferredOrphans) { - try { - final dir = Directory(path); - if (dir.existsSync()) dir.deleteSync(recursive: true); - } catch (_) { - still.add(path); - } - } - _deferredOrphans - ..clear() - ..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; -} +/// Process-wide sweeper — the Process transport is stateless otherwise, +/// but Windows file-locks sometimes persist past a single call. +final TempDirSweeper _sweeper = TempDirSweeper(); /// Makes [label] safe to use as a filename stem. Non-alphanumeric chars /// collapse to `_`; a leading digit gets a `T_` prefix. When any diff --git a/lib/src/backend_web.dart b/lib/src/backend_web.dart index 33aadc8..14a03aa 100644 --- a/lib/src/backend_web.dart +++ b/lib/src/backend_web.dart @@ -85,51 +85,91 @@ 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 `