From 2877b51aa7deda450ddfe3ca64df5d4af6aee2f8 Mon Sep 17 00:00:00 2001 From: flutter-skills-sync-bot Date: Thu, 3 Dec 2026 00:31:28 +0000 Subject: [PATCH] chore: auto-sync skills directory from dart-lang/skills --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- .../dart-migrate-to-checks-package/SKILL.md | 2 +- skills/dart-use-doc-examples/SKILL.md | 154 ++++++++++++++---- skills/dart-use-path-package/SKILL.md | 10 +- skills/dart-use-pattern-matching/SKILL.md | 30 +++- .../examples/filename_patterns.dart | 45 +++++ tool/.dart_skills_githash | 2 +- 9 files changed, 204 insertions(+), 45 deletions(-) create mode 100644 skills/dart-use-pattern-matching/examples/filename_patterns.dart diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 91490f0f..bca87ff7 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "dart-flutter", "displayName": "Dart and Flutter", - "version": "1.0.7", + "version": "1.0.8", "description": "Official Claude plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase", "author": { "name": "Dart and Flutter", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index f959b05e..5b13f82c 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "dart-flutter", - "version": "1.0.8", + "version": "1.0.9", "description": "Official Codex plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase.", "author": { "name": "Google LLC", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index b4ea8377..4692d843 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "dart-flutter", "displayName": "Dart and Flutter", - "version": "1.0.7", + "version": "1.0.8", "description": "Official Cursor plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase.", "author": { "name": "Dart and Flutter Team", diff --git a/skills/dart-migrate-to-checks-package/SKILL.md b/skills/dart-migrate-to-checks-package/SKILL.md index 3daf8944..fb392516 100644 --- a/skills/dart-migrate-to-checks-package/SKILL.md +++ b/skills/dart-migrate-to-checks-package/SKILL.md @@ -171,7 +171,7 @@ For any target test file: ..has((e) => e.message, 'message').equals('invalid input'); // NO (Passing a callback to sync throws will cause a compiler error!) - check(() => triggerSync").throws((it) => ...); // ERROR! + check(() => triggerSyncError()).throws((it) => ...); // ERROR! ``` - **Asynchronous** (`Subject>`): `.throws()` returns `Future`. Because you cannot chain directly off a `Future`, this diff --git a/skills/dart-use-doc-examples/SKILL.md b/skills/dart-use-doc-examples/SKILL.md index a9b4f153..5b78eda8 100644 --- a/skills/dart-use-doc-examples/SKILL.md +++ b/skills/dart-use-doc-examples/SKILL.md @@ -1,61 +1,75 @@ --- name: dart-use-doc-examples -description: "How to inject external code examples into Dartdoc using the {@example} directive, and how to filter those files using #hide, #region, and #endregion tags." +description: "Reference example code in dartdoc documentation comments and markdown files using the {@example} directive, with #region , #endregion and #hide markers." --- -# Using Examples in Dartdoc +# Using Examples in Documentation ## Contents * [1. The `{@example}` Directive](#1-the-example-directive) * [2. Using Regions](#2-using-regions) -* [3. Hiding Setup Code](#3-hiding-setup-code) -* [4. Marker Filtering Rules](#4-marker-filtering-rules) -* [5. Placement and Path Resolution](#5-placement-and-path-resolution) -* [6. Verification](#6-verification) +* [3. Placement of example code](#3-placement-of-example-code) +* [4. Examples in markdown files](#4-examples-in-markdown-files) +* [5. Verification](#5-verification) -When writing documentation that requires multi-line code examples, you should generally extract those examples into standalone `.dart` files and inject them using the `{@example}` directive, rather than writing them inline inside `///` comments. This ensures the examples can be analyzed, linted, and executed. +When putting example code in documentation, prefer to write the examples as standalone `.dart` files and reference their contents with the `{@example}` directive. +This is better than inline example code, because standalone dart files are analyzed and linted, ensuring example code is maintained. ## 1. The `{@example}` Directive The `{@example}` directive parses an external file and resolves it into a fenced Markdown code block in the generated documentation. -**Syntax:** `{@example [#] [lang=LANGUAGE] [indent=keep|strip]}` +**Syntax:** `/// {@example [#] [lang=LANGUAGE] [indent=keep|strip]}` * **``**: The path to the file. A leading `/` evaluates from the package root. Otherwise, it is relative to the current file. * **`lang`**: The language for the markdown fence. Auto-detected from the file extension (e.g., `dart`), but can be explicit (e.g., `lang=text`). * **`indent`**: `strip` (default) aggressively removes shared leading indentation from the code block. -*Bad (Inline Markdown):* +*Bad (inline example code):* ```dart /// Makes a client service request to the backend. /// /// ```dart /// final client = Client(); -/// client.send(); +/// await client.get(Uri.parse('https://example.com')); /// ``` ``` -*Good (External File Injection):* +*Good (reference example code from a file):* ```dart /// Makes a client service request to the backend. /// /// {@example /example/client_request.dart} ``` +The `{@example }` directive is a block-directive and should be on its own line. The `` is a URI relative to the current file, +it may use `../`, but may not reach outside the _package root_ (the folder containing `pubspec.yaml`). +If the `` starts with `/`, it is relative to _package root_, this is often the preferred manner to reference example files. + +> [!NOTE] +> The `` uses forward slashes as separators on all platforms and URI encoded characters like `%20` to encode space. +> Absolute URIs (like `https://...`) are not supported. + ## 2. Using Regions -Often, an external example file contains imports, setup, or `void main()` wrappers that you don't want to show in the documentation. You can extract a specific block of code by appending `#` to the `{@example}` directive path, and wrapping that code with `#region` and `#endregion` comments in the target file. +An example file often contains license headers, imports, setup, or `void main()` wrappers that you don't want in the documentation. +You can extract a specific _region_ of code by appending `#` to the `{@example}` directive path, and wrapping that code +with `#region ` and `#endregion` comments in the target file. **Dart Code (e.g., `/example/client.dart`):** ```dart import 'package:http/http.dart'; -void main() { +Future main() async { // #region request_snippet final client = Client(); - client.send(); + await client.get(Uri.parse('https://example.com')); // #endregion request_snippet } ``` +> [!NOTE] +> The `` is only required on the `#region ` tag. +> Writing `#endregion ` as above is merely good practice. + **Dartdoc Usage:** ```dart /// Connects the client to the server and sends a request. @@ -63,34 +77,104 @@ void main() { /// {@example /example/client.dart#request_snippet} ``` -## 3. Hiding Setup Code -If there is a specific line of code within your extracted region that is necessary for the compiler/analyzer to pass but irrelevant (or distracting) for the documentation reader, append `#hide` to that line. +Regions can be closed and reopened (using the same region name), this can be used to hide a block of code in the middle of a region. +To hide a single line use `#hide`. + +**Dart Code with region (e.g., `/example/client.dart`):** +```dart +import 'package:http/http.dart'; + +Future main() async { + // #region request_snippet + // Make a request + final client = Client(); // #hide + // #endregion request_snippet + startFakeServer() + ..domain = 'example.com'; + // #region request_snippet + await client.get(Uri.parse('https://example.com')); + // #endregion request_snippet +} +``` -**Dart Code:** +**Dartdoc Usage:** ```dart -final mockServer = startServer(); // #hide -final data = await fetch(mockServer.url); +/// Connects the client to the server and sends a request. +/// +/// {@example /example/client.dart#request_snippet} ``` -In the generated documentation, only `final data = await fetch(mockServer.url);` will be visible. The line with `#hide` is completely dropped. -## 4. Marker Filtering Rules -When working with `#hide`, `#region`, and `#endregion` markers, you must follow these two technical constraints: +Fenced code block rendered by `dartdoc`: +```dart +// Make a request +await client.get(Uri.parse('https://example.com')); +``` -* **Region Required:** The markers are only processed and stripped when you target a specific region suffix (e.g., `{@example file.dart#region_name}`). If you inject an entire file without a region suffix, the file is embedded exactly as it appears in the source, including any marker text like `// #hide`. -* **Format Agnosticism:** The marker system is completely format-agnostic. Dartdoc simply runs a regex to strip lines containing the marker strings, meaning it works identically in non-Dart files (e.g., inside YAML comments `# #region` or HTML comments ``). +> [!NOTE] +> `#hide`, `#region`, and `#endregion` markers are only processed (and removed) when referencing a specific region (e.g., `{@example file.dart#region_name}`). +> If referencing an entire file (e.g., `{@example file.dart}`) these markers are ignored and the file is embedded as it appears (including any `// #hide` markers). + +The `#region `, `#endregion` and `#hide` markers are format-agnostic, and will be processed as text. +Meaning they can appear in Dart, YAML, HTML comments (``) or inside strings (granted using region markers in strings is discouraged). + +## 3. Placement of example code + +These are guidelines for where to place example code. + + * (A) Dedicated file in `example/`, like `example/say_hello.dart`: + * Suitable for small simple examples (like call function and print results). + * Pros: Easy for a user to run the example file on their machine (or dartpad.dev). + * Cons: Nothing tests that the example does what it claims when executed. + + * (B) Region in a `test/` file, like `test/example/request_example_test.dart`: + ```dart + import 'package:test/test.dart'; + import 'package:http/http.dart'; + + void main() { + test('request example.com', () async { + final client = Client(); + // #region request_snippet + await client.get(Uri.parse('https://example.com')); + // #endregion request_snippet + }); + } + ``` + * Suitable for complex examples that have setup and where testing is warranted. + * Pros: Package author will be testing the example code with `dart test` (typically also in CI). + * Cons: Package consumers can't easily run the example code. + + * (C) Dedicated example app in `example/`, like `example/my_demo_app/`: + * Suitable when an example is a full app (like a flutter app) or needs dependencies the root package doesn't want. + * Pros: Enables high fidelity examples, easy for users to run on their machine (or dartpad.dev). + * Cons: An example app might need its own test suite (like `example/my_demo_app/test/`), which you might want to run in CI. + +`dart analyze` will run analysis on all files in a project, so (A), (B) and (C) all get static analysis errors and lints surfaced. +This helps ensure that example code stays up-to-date as the package API changes. In many cases (A) is the simplest way to write examples. +The biggest downside of doing (A) is that nothing tests the examples. + +Use your best judgement to decide where to put an example (A), (B) or (C). +Regardless of where you put it, you'll often put it in a different top-level folder than the code referencing it, +so prefer using package root relative `/` paths in `{@example /...}` directives. + +## 4. Examples in markdown files +Similar to `{@example}` in documentation comments, you can use `package:snippets` to embed examples from external files in a markdown file. +One simply writes a _fenced markdown code block_ with `@example [#]` in the _info-string_, as illustrated below: + +~~~md +```dart @example /example/example.dart#greeting +final message = 'Hello, world!'; +print(message); +``` +~~~ -## 5. Placement and Path Resolution -The `{@example}` directive is a block-level directive. It must appear on its own line prefixed with `///`. Its internal `` parser follows strict URI reference rules: +Then run `dart run snippets@ update` which will update the contents of the _fenced code block_ in the file on disk. +(if doing this, consider using `dart run snippets@ validate` in CI. Note `dart run snippets@` is a _global run_, so no dependency is needed). -* **Package-Root Paths (`/`)**: Paths starting with a leading slash automatically resolve directly to the root of the Dart package. Use this when the destination file is deep. - * *Example:* `{@example /test/data/sample.txt}` exactly maps to `/test/data/sample.txt`. -* **Relative Paths**: Paths without a leading slash resolve relative to the directory of the file containing the doc comment. - * *Example:* `{@example ../utils/demo.dart}` -* **Boundary Enforcement:** Using `..` segments to traverse upward is perfectly acceptable, but dartdoc natively stops directory traversal at the package root (it will never escape the package). -* **No Network URLs:** Absolute URIs (e.g., starting with `https://`) are strictly not supported. The example file *must* sit natively somewhere in the local filesystem. -* **Separators & Encoding:** Because dartdoc resolves the path as a URI, you must always use forward slashes (`/`) as folder separators (even on Windows). You can natively include URI-encoded characters (like `%20` for spaces) as permitted by URI reference rules. +See also: https://pub.dev/packages/snippets -## 6. Verification +## 5. Verification After injecting examples: -1. Run `dart analyze` on the example files to ensure the hidden setup code compiles. +1. Run `dart analyze` on the example files to ensure there are no analysis errors. 2. (Optional) Run `dart doc` to verify that dartdoc successfully parsed the directive without throwing a "Failed to read file" or "missing region" warning. +3. (If applicable) Run `dart run snippets@ validate` to verify that examples in markdown files are up-to-date. diff --git a/skills/dart-use-path-package/SKILL.md b/skills/dart-use-path-package/SKILL.md index 5f9fe324..be21b842 100644 --- a/skills/dart-use-path-package/SKILL.md +++ b/skills/dart-use-path-package/SKILL.md @@ -4,7 +4,7 @@ description: >- Cross-platform file and directory path manipulation, segment splitting, extension extraction, and context conversion using `package:path` and `package:file`. Use when writing, inspecting, joining, splitting, or refactoring file paths, directory names, or extensions, or replacing raw string path operations (`.split('/')`, `'$dir/$file'`, `.endsWith('.ext')`, `.replaceAll('\\', '/')`). Don't use for HTTP network URI routing, database query strings, or non-path string processing. metadata: model: models/gemini-3.1-pro-preview - last_modified: Wed, 23 Sep 2026 22:10:00 GMT + last_modified: Fri, 13 Nov 2026 03:41:00 GMT --- # Safe Cross-Platform Path Manipulation in Dart @@ -34,9 +34,10 @@ metadata: * **POSIX-Only Tools & Static Subpath Greppability**: In codebases exclusively targeting Linux/macOS (or when joining a dynamic base path to a known static subpath), decomposing 5–6 static segments into separate arguments (`p.join(home, '.local', 'share', 'app', 'bin', 'config.json')`) causes `dart format` to wrap across 6–8 vertical lines and **destroys substring greppability** (`grep` / `code_search` for `.local/share/app/bin`). * **Rule for POSIX Targets**: Prefer **2-argument boundary joining** (`p.join(home, '.local/share/app/bin/config.json')`). This prevents duplicate-slash bugs (`//`) at variable boundaries while preserving single-line readability and exact string searchability. -### Normalization vs. Canonicalization (`p.normalize` vs. `p.canonicalize`) -* `p.normalize(path)` resolves `.` and `..` segments purely lexically without consulting the filesystem or standardizing case. -* When deduplicating directory paths or comparing physical file identity across symlinks, relative roots, or case-insensitive filesystems, use `p.canonicalize(path)`. +### Lexical Canonicalization vs. Physical Symlink Resolution +* `p.normalize(path)` resolves `.`, `..`, and redundant separators purely lexically while preserving relative vs. absolute form and case. +* `p.canonicalize(path)` converts to an absolute path, normalizes segments, and standardizes ASCII case on Windows—still purely lexically (`package:path` never consults the filesystem and **does not resolve symlinks**). +* When comparing physical file or directory identity on disk or keying caches across symlinks (such as macOS `/tmp` -> `/private/tmp`) and relative CLI flags (`-o out`), resolve symlinks via `Directory(path).resolveSymbolicLinksSync()` or `File(path).resolveSymbolicLinksSync()` (or `fileSystem.directory(path).resolveSymbolicLinksSync()` in `package:file`). Unlike lexical `p.canonicalize(path)`, `resolveSymbolicLinksSync()` throws a `FileSystemException` if the path does not exist yet—ensure the target exists first or fall back to `p.canonicalize(path)` / `directory.absolute.path` on `FileSystemException`. ### Strip Location Specifiers & Convert URIs Safely * Strings formatted as `:-` or `:` are not pure file paths. Passing them directly to `p.normalize` or `Uri.parse` causes bugs (on Windows, `Uri.parse` mistakes `C:` for a URI scheme and `:line` for a port). @@ -197,6 +198,7 @@ String insertContentHash(String filename, String hash) { - [ ] Replace `.endsWith('.ext')` on file paths with `p.extension(path) == '.ext'`. - [ ] Replace manual dot-index slicing with `p.withoutExtension(path)` and `p.extension(path, [level])`. - [ ] Verify that code using `package:file` accesses `fileSystem.path` instead of global `p.*`. +- [ ] Use `resolveSymbolicLinksSync()` (catching `FileSystemException` when paths may not exist yet) instead of lexical `p.canonicalize(path)` when comparing physical on-disk paths across symlinks. - [ ] Ensure Git paths, `.gitignore` entries, and symlink targets use `p.posix` forward slashes. --- diff --git a/skills/dart-use-pattern-matching/SKILL.md b/skills/dart-use-pattern-matching/SKILL.md index 34dfee49..0eb8c8b3 100644 --- a/skills/dart-use-pattern-matching/SKILL.md +++ b/skills/dart-use-pattern-matching/SKILL.md @@ -10,7 +10,7 @@ description: >- type promotion (use `is`), or basic collection filtering. metadata: model: models/gemini-3.1-pro-preview - last_modified: Tue, 13 Oct 2026 19:45:00 GMT + last_modified: Fri, 13 Nov 2026 02:48:00 GMT --- # Implementing Dart Patterns @@ -225,6 +225,34 @@ String? resolveAllowedAssetSubpath(List segments) { } ``` +### Compound Filename Classification (Replacing Multi-Dot RegExp) +Split basenames on `'.'` and switch on list patterns with rest elements (`...`) +and inline `when` guards (such as `int.tryParse`) instead of maintaining nested +regular expressions that risk over-matching sibling files. See +[examples/filename_patterns.dart](examples/filename_patterns.dart) for an +executable implementation. + +```dart +enum BuildArtifact { + entrypoint, + sourceMap, + deferredPart, + supportRuntime; + + static BuildArtifact? tryParse(String name) => switch (name.split('.')) { + ['main', 'dart', 'js'] => entrypoint, + ['main', 'dart', 'js', 'map'] => sourceMap, + // Matches numbered chunks like 'main.dart.1.part.js'. + ['main', 'dart', final part, ..., 'part', 'js'] + when int.tryParse(part) != null => + deferredPart, + // Stays distinct instead of being swallowed by 'main.dart.*.js'. + ['main', 'dart', 'support', 'js'] => supportRuntime, + _ => null, + }; +} +``` + ### Algebraic Data Types (Sealed Classes) Use Object patterns with switch expressions to handle family types exhaustively. diff --git a/skills/dart-use-pattern-matching/examples/filename_patterns.dart b/skills/dart-use-pattern-matching/examples/filename_patterns.dart new file mode 100644 index 00000000..5bea5cef --- /dev/null +++ b/skills/dart-use-pattern-matching/examples/filename_patterns.dart @@ -0,0 +1,45 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/// Classifies multi-dot build artifacts using list patterns instead of nested +/// regular expressions. +library; + +/// Known build output artifacts for a compiled web entrypoint. +enum BuildArtifact { + entrypoint, + sourceMap, + deferredPart, + supportRuntime; + + /// Parses [name] into a [BuildArtifact], or returns `null` for unrecognized + /// files. + static BuildArtifact? tryParse(String name) => switch (name.split('.')) { + ['main', 'dart', 'js'] => entrypoint, + ['main', 'dart', 'js', 'map'] => sourceMap, + // Matches numbered chunks like 'main.dart.1.part.js' or 'main.dart.1.min.part.js'. + ['main', 'dart', final part, ..., 'part', 'js'] + when int.tryParse(part) != null => + deferredPart, + // Stays distinct instead of being swallowed by a 'main.dart.*.js' wildcard. + ['main', 'dart', 'support', 'js'] => supportRuntime, + _ => null, + }; +} + +void main() { + const samples = [ + 'main.dart.js', + 'main.dart.js.map', + 'main.dart.1.part.js', + 'main.dart.12.min.part.js', + 'main.dart.support.js', + 'main.dart.alpha.part.js', + 'main.dart.js.info.json', + ]; + + for (final sample in samples) { + print('$sample -> ${BuildArtifact.tryParse(sample)}'); + } +} diff --git a/tool/.dart_skills_githash b/tool/.dart_skills_githash index b0445a0c..dad4266a 100644 --- a/tool/.dart_skills_githash +++ b/tool/.dart_skills_githash @@ -1 +1 @@ -bf984f3ef223dd85e92036f934bbcb6bf301e4ce +20cd17cd8ffb1e4502dbc9facd5bc91f5800aac4