pub repository
mirror.p-hatan.comhooks
2.2.0A library that contains a Dart API for the JSON-based protocol for `hook/build.dart` and `hook/link.dart`.
Cached in Iran · Upstream SHA-256 matched
Readme
dart Coverage Status pub package package publisher
This package provides the API for hooks in Dart. Hooks are Dart
scripts placed in the hook/ directory of a Dart package, designed to automate
tasks for a Dart package.
This API supports two hooks: the build hook (hook/build.dart) and the link
hook (hook/link.dart).
The build hook is executed during a Dart build and enables you to build or
gather assets for a Dart package. The link hook is executed after all build
hooks and enables you to perform whole-application optimization and linking
(such as tree-shaking dead native code based on
@RecordUse()
usages).
The main supported asset type is a code asset, code written in other languages
that are compiled into machine code. You can use a build hook to do things such
as compile or download code assets, and then call these assets from the Dart
code of a package. The
CodeAsset
API is an extension to this package and is available in
package:code_assets.
When compiling C, C++ or Objective-C code from source, consider using
package:native_toolchain_c
with a build hook and a link hook. First, define the C library specification in
a shared file:
import 'package:native_toolchain_c/native_toolchain_c.dart';
/// The C build specification for the sqlite library.
///
/// It is used by the build and link hooks in the `hook/` directory.
final cLibrary = CLibrary(
name: 'sqlite3',
assetName: 'src/third_party/sqlite3.g.dart',
sources: ['third_party/sqlite/sqlite3.c'],
);
Next, compile the library in the build hook:
import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';
import 'package:sqlite/src/c_library.dart';
void main(List<String> args) async {
await build(args, (input, output) async {
if (input.config.buildCodeAssets) {
await cLibrary.build(
input: input,
output: output,
defines: {
if (input.config.code.targetOS == OS.windows)
// Ensure symbols are exported in dll.
'SQLITE_API': '__declspec(dllexport)',
},
);
}
});
}
Finally, tree-shake and link the library in the link hook:
import 'package:hooks/hooks.dart';
import 'package:native_toolchain_c/native_toolchain_c.dart';
import 'package:record_use/record_use.dart';
import 'package:sqlite/src/c_library.dart';
import 'package:sqlite/src/third_party/record_use_mapping.dart';
void main(List<String> arguments) async {
await link(arguments, (input, output) async {
await cLibrary.link(
input: input,
output: output,
linkerOptions: LinkerOptions.treeshake(
symbolsToKeep: input.recordedUses?.calls.keys.cast<Method>().map(
(e) => recordUseMapping[e.name]!,
),
),
);
});
}
See the full example in package:code_assets example/sqlite/.
When bundling precompiled dynamic libraries, use package:code_assets directly:
import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';
void main(List<String> args) async {
await build(args, (input, output) async {
if (input.config.buildCodeAssets) {
final packageName = input.packageName;
final assetPathInPackage = input.packageRoot.resolve('...');
final assetPathDownload = input.outputDirectoryShared.resolve('...');
output.assets.code.add(
CodeAsset(
package: packageName,
name: '...',
linkMode: DynamicLoadingBundled(),
file: assetPathInPackage,
),
);
}
});
}
For more information see dart.dev/tools/hooks.
User-defines
Because build hooks execute in a semi-hermetic environment where most environment variables are stripped for reproducibility and caching purposes, you should use user-defines to pass custom configurations, flags, or paths to your hooks from pubspec.yaml.
1. Define in pubspec.yaml
In your package (or workspace root pubspec.yaml if using workspaces), add the hooks.user_defines section:
hooks:
user_defines:
my_package_name:
enable_debug_logging: true
custom_asset: assets/data.json
[!IMPORTANT]
Workspace Scope: If a project is set up as a pub workspace, thehooks.user_definesconfiguration block must be placed in the workspace rootpubspec.yamlfile. Defines inside member packagepubspec.yamlfiles are ignored when workspace resolution is active.
2. Read in hook/build.dart or hook/link.dart
Access the values using input.userDefines:
import 'dart:io';
import 'package:hooks/hooks.dart';
void main(List<String> args) async {
await build(args, (input, output) async {
// Access raw user-defines value
final debugLogging = input.userDefines['enable_debug_logging'];
if (debugLogging is! bool?) {
throw const FormatException(
'hooks.user_defines.my_package.enable_debug_logging must be a '
'boolean (or omitted)',
);
}
if (debugLogging == true) {
print('Debug logging is enabled.');
}
// Resolve relative path against pubspec.yaml base path
final customAssetUri = input.userDefines.path('custom_asset');
if (customAssetUri != null) {
final file = File.fromUri(customAssetUri);
output.dependencies.add(file.uri); // Declare cache dependency
// Use the file...
}
});
}
Documentation
For detailed documentation on debugging and the configuration schema, see the documentation.
Changelog
2.2.0
- Add
ProtocolExtension.setupLogger, which the hooks runner calls to provide the logger used for validation diagnostics before any other method is invoked on the extension. - Fix
HookInputUserDefines.pathmangling absolute Windows paths: the drive letter was parsed as a URI scheme. Absolute paths are now returned as-is; relative paths are resolved against the source of the path. - Add
HookInputUserDefines.baseUri, which can be used to resolve paths from nested user-defined options.
2.1.0
- Graduate
LinkInput.recordedUsesout of experimental.
2.0.2
- Update documentation for user-defines.
2.0.1
- Updated documentation for hook caching behavior and semi-hermetic environment variables.
2.0.0
- Breaking change: Turned
ProtocolExtensioninto a base class instead of an interface, with default implementations for all methods including the newly addedoutputFiles.
1.0.3
- Deprecated
recordedUsagesFileinLinkInput. - Added
recordedUsesgetter toLinkInput. - Added dependency on
package:record_use.
1.0.2
- Update documentation about
CCACHE_environment variables.
1.0.1
- Update documentation about environment variables.
1.0.0
- Stable release.
0.20.6-wip
- Fix
testBuildHookto emit output validation errors if there are any.
0.20.5
- Document
input.packageRootin more places.
0.20.4
- Improved documentation on debugging and added a documentation index.
0.20.3
- Polished README.md, Dartdocs, and examples.
0.20.2
- Change the length of the checksum used for
outputDirectoryto 10 hexadecimal characters to avoid running out of path length on Windows.
0.20.1
- Update outdated documentation.
- Deprecate
HookOutputBuilder.addDependencyandHookOutputBuilder.addDependenciesin favor ofHookOutputBuilder.dependencies.addandHookOutputBuilder.dependencies.addAll.
0.20.0
- Breaking change Rename
EncodedAsset.jsonPathtoEncodedAsset.encodingJsonPath. This field only governs theEncodedAsset.encodingfield, not the whole object. - Enable passing metadata from link hooks of a package to the link hooks in dependencies, by fixing the link hook execution order.
0.19.5
- Stop leaking unexported symbols.
0.19.4
- Add doc comments to all public members.
0.19.3
- Mark this package as in preview.
0.19.1
- Added links to the
buildandlinkmethods as primary entry points. - Added failure outputs and documented exit codes.
0.19.0
- Split up
package:native_assets_cliinpackage:hooks,package:code_assets, andpackage:data_assets.
0.18.0
- Breaking change Reorganized the libraries structure. Classes are no longer exported multiple times.
- Breaking change multiple classes renamed.
0.17.0
- Breaking change Removed support for old JSONs. Newer SDKs will not work with older hooks, and the lower bound of this package is bumped. #2199
0.16.0
- Support relative paths in user-defines to be loaded as absolute paths.
0.15.0
- Breaking change JSON encoding migration: change written asset type to the namespaced one. Still keep reading the old one. (Old build hooks will keep working with new SDKs.)
- Bump SDK lower bound to version that understands namespaced asset types. (Version 3.8.0-260.0.dev)
0.14.0
- Added support for sending assets between build hooks via the
ToBuildRouting. This replaces the deprecatedMetadata. - Added support for user-defines.
0.13.0
- Breaking change Removed
CodeAsset.type, useEncodedAsset.isCodeAssetinstead. - Breaking change: Removed
CodeAsset.osandCodeAsset.architecture. UseCodeConfig.targetOSandCodeConfig.targetArchitectureinstead. HookInput.outputDirectoryis now based onHookInput.outputDirectoryShared. TheoutputDirectorynow creates its own subdirectory insideoutputDirectoryShared.- Another overhaul of the JSON encoding. (Old encoding still read and emitted for the time being).
0.12.0
- Added validation that all URLs in the
InputandOutputof hooks are absolute. - Added
addDataAssetDirectoriesextension method onBuildOutputBuilder. - Replaced JSON serialization/deserialization logic with code generated from the JSON schemas documenting the protocol.
0.11.0
- Breaking change Complete overhaul of the API used in build and link hooks.
The
BuildConfigis now split inBuildInputandBuildConfig. The input is everything passed in to the hook. The config (a part of the input) is what shouldn't change on subsequent invocations of the same flutter or dart command for the same target. TheoutputDirectoryis the same if the config is the same. - Breaking change The
output.jsonis now part ofBuildInput.
0.10.0
- Breaking change The library import paths changed to be per asset type. (This enables extensibility with custom asset types.)
- Breaking change: Rename
supportedAssetTypestobuildAssetTypes. Hooks should no longer fail. Instead, the code should fail at runtime if an asset is missing. This enables (1) code to run if an asset is missing but that code is not invoked at runtime, and (2) doing fallback implementations in Dart if an asset is missing. - Breaking change Move
BuildModetopackage:native_toolchain_c. This way it can be controlled in the build hook together with theOptimizationLevel. Most likely, every package should ship withrelease.BuildMode.debugshould only be used while developing the package locally. - Breaking change Move
HookConfig.targetOStoCodeConfig.DataAssets and other asset types should not depend on OS for now. - Breaking change: Change the behavior of
testBuildHookandtestCodeBuildHook; instead of defining tests, these methods should now be called from within tests. - Move the
package:testdependency from a regular dependency (exported to calling packages) to a dev_dependency.
0.9.0
- Add
BuildConfigandLinkConfigoutputDirectoryShared. - Remove
package:native_assets_cli/locking.dartwithrunUnderDirectoryLock. Hook writers should not use this, thenative_assets_builderdoes this. - Fix example packages with RecordUse annotations #1586.
- Remove v1.0 / v1.1 related serialization
- Update SDK constraint to 3.5.0+
- Remove (deprecated) support for accepting yaml as config
- Remove usage of
package:cli_configandpackage:args: it minimizes dependencies and it simplifies logic any hook has to do (as it no longer has to look into environment variables, arguments and json file, determine which has presence over other, etc) - Use
DART_HOOK_TESTINGprefix for environment variables used for testing on Dart CI - No longer try to resolve uris encoded in
config.jsonagainst any base uri. Thehook/{build,link}.dartinvoker has to ensure the uris it encodes can be opened as-is (i.e. without resolving against any base uri) - Breaking change Moved some methods to be extension methods.
- Some classes in the
BuildConfigandBuildOutputnow exposefromJsonandtoJson. - Breaking change Removed
Assetclass, removed{Build,Link}Output.assets*. Hook writers should now use e.g.output.dataAssets.add(DataAsset(...))instead ofoutput.addAsset(DataAsset(...)). - Breaking change Introduce builder classes that construct hook configs and hook outputs.
0.8.0
- Add URI for the recorded usages file to the
LinkConfig. - Added a validation step in the
buildandlinkmethods.
0.7.3
- Fix some more cases of:
BuildConfig.dependenciesandLinkConfig.dependenciesno longer have to specify Dart sources. DataAssetexamples report all assets fromassets/dir and default the asset names to the path inside the package.- Add
package:native_assets_cli/test.dartwithtestBuildHookhelper method for testing build hooks. - Add
package:native_assets_cli/locking.dartwithrunUnderDirectoryLock.
0.7.2
- Deprecate metadata concept.
0.7.1
BuildConfig.dependenciesandLinkConfig.dependenciesno longer have to specify Dart sources.
0.7.0
BuildConfigconstructors now have a requiredlinkingEnabledparameter.
0.6.1
- Introduce
BuilderandLinkerinterface. - Copy
resources.jsonto the build directory. - Introduce
HookConfig.targetIosSdkandHookConfig.targetMacosSdkoptional values.
0.6.0
- Add support for
hook/link.dart.
0.5.4
- Update documentation about providing
NativeCodeAsset.filein dry runs.
0.5.3
- Fix V1_0_0 dry run backwards compatibility. https://github.com/dart-lang/native/issues/1053
0.5.2
- Fix test.
0.5.1
- Update documentation about providing
NativeCodeAsset.filein dry runs. https://github.com/dart-lang/native/issues/1049
0.5.0
- Breaking change Completely rewritten API. https://github.com/dart-lang/native/pull/946
- Breaking change Move
build.darttohook/build.dart. https://github.com/dart-lang/native/issues/823 - Breaking change Use JSON instead of YAML in the protocol. https://github.com/dart-lang/native/issues/991
- Bump examples dependencies to path dependencies.
0.4.2
- Fix dartdoc generation. Hide the implementation details.
0.4.1
- Breaking change Removed all code not used in
build.dartscripts out of the public API.
0.4.0
- Added example/use_dart_api/ detailing how to use
dart_api_dl.hfrom the Dart SDK in native code. - Breaking change Moved code not used in
build.darttopackage:native_assets_builder.
0.3.2
- Fixed an issue where
Depenendencies.dependenciescould not be modified when expected to.
0.3.1
- Added
Target.androidRiscv64.
0.3.0
- Breaking change Add required
BuildConfig.packageName(#142).
0.2.0
- Breaking change Rename
Asset.nametoAsset.id(#100). - Added topics.
- Fixed metadata example.
- Throws
FormatExceptions instead ofTypeErrors when failing to parse Yaml (#109).
0.1.0
- Initial version.
Installing
export PUB_HOSTED_URL=https://pub.mirror.p-hatan.com
flutter pub add hookspubspec.yaml
name: hooks
description: >-
A library that contains a Dart API for the JSON-based protocol for
`hook/build.dart` and `hook/link.dart`.
version: 2.2.0
repository: https://github.com/dart-lang/native/tree/main/pkgs/hooks
topics:
- assets
- ffi
- hooks
- interop
- native-assets
resolution: workspace
environment:
sdk: '>=3.10.0 <4.0.0'
dependencies:
collection: ^1.19.1
crypto: ^3.0.6
logging: ^1.3.0
pub_semver: ^2.2.0
record_use: ^1.0.0
yaml: ^3.1.3 # Used for reading pubspec.yaml to obtain the package name.
dev_dependencies:
args: ^2.6.0
code_assets: ^2.0.0 # Used for running tests with real asset types.
dart_flutter_team_lints: ^3.5.2
data_assets: any # Used for running tests with real asset types.
file_testing: ^3.0.2
glob: any
json_schema: ^5.2.0 # May only be used in tool/ and test/json_schema/.
json_syntax_generator:
path: ../json_syntax_generator/
native_test_helpers:
path: ../native_test_helpers/
path: ^1.9.1
test: ^1.25.15
Version history
| Version | Published | Archive | SHA-256 |
|---|---|---|---|
| 0.0.1 | 2013-08-08T07:24:30.015510Z | Cached | b8c525752ff50667a8eac7b88039b7d540ef3194a686f394f9d3003862bee0f7 |
| 0.1.0 | 2013-08-13T05:58:43.221730Z | Cached | 3b0bf27b085c030c0786b5b7c29f860a76a3a93693e7efda10b277cc8b54ff4c |
| 0.1.1 | 2013-09-16T21:55:31.289740Z | Cached | 35ad29232599c07a209a808c6e9051915d2559a20ed16a52826ec8a2b85abcea |
| 0.1.2 | 2013-12-06T17:10:24.120100Z | Cached | e43afeb09752dcd255c4450ff5df49c10d6fa34d06a239da678029722bd003d7 |
| 0.19.0 | 2025-05-01T07:57:27.553413Z | Cached | 851928fff27d0ff030f54af32c5fb6ce4707a37f7d2e2976cea68dea9b939909 |
| 0.19.1 | 2025-05-19T07:28:49.998615Z | Cached | c29b5d113b093995426c9d2d4ce157902f04d426d9fb44206f88d2da7ae3e0f2 |
| 0.19.2 | 2025-05-21T15:59:02.517814Z | Cached | a4389bc0e283f953cae32e3b768178ed3e1051fc11b127af38ab43251e3d301e |
| 0.19.3 | 2025-05-21T17:42:22.098685Z | Cached | 6fa18c99c5fd6456c3edd99e3f857099c8748eb2062bb8374970f7896858512b |
| 0.19.4 | 2025-06-12T11:32:07.585554Z | Cached | c3564567a6b82ad1ef8eef18a4ad6f37f7a56dd3fa59fe7afa1d8d75322fff1a |
| 0.19.5 | 2025-06-12T13:39:54.565049Z | Cached | 75363eae6c0c2db051c4f6b3b1fcdea8a09c4a596cc83bfff847661da6e80dfc |
| 0.20.0 | 2025-08-04T11:08:48.365074Z | Cached | 2bd640e4625fdfe5788ef33d825a8639797d44bce05695ab13543cde0ff9a078 |
| 0.20.1 | 2025-08-27T14:57:22.055231Z | Cached | 22abd27b650a571e53576abe732e4d9053aacaaa6dee23e9ff106c63e3e5b96c |
| 0.20.2 | 2025-10-08T13:20:44.201921Z | Cached | ceee15e2cef1b23e879e2d7adf581b700947b0dff33244ef3a1ee32910fd4938 |
| 0.20.3 | 2025-10-13T07:47:52.463980Z | Cached | 4ad76d2de250aec8345e6acc895f452f17889e7a3005a4b7401479f3f7d84447 |
| 0.20.4 | 2025-10-15T09:15:50.448066Z | Cached | 6274d1fe704962cbb881d437aae11af3e6eecc810da7438cc100c85679b4feb6 |
| 0.20.5 | 2025-10-27T12:25:40.243174Z | Cached | 5410b9f4f6c9f01e8ff0eb81c9801ea13a3c3d39f8f0b1613cda08e27eab3c18 |
| 1.0.0 | 2025-11-07T15:23:19.646021Z | Cached | 5d309c86e7ce34cd8e37aa71cb30cb652d3829b900ab145e4d9da564b31d59f7 |
| 1.0.1 | 2026-02-03T16:57:56.600571Z | Cached | 7a08a0d684cb3b8fb604b78455d5d352f502b68079f7b80b831c62220ab0a4f6 |
| 1.0.2 | 2026-03-06T11:19:50.417879Z | Cached | e79ed1e8e1929bc6ecb6ec85f0cb519c887aa5b423705ded0d0f2d9226def388 |
| 1.0.3 | 2026-04-21T09:33:52.565162Z | Cached | 025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e |
| 2.0.0 | 2026-05-18T15:37:25.524712Z | Cached | a41af4e8fc687cd6d33de9751eb936c8c0204ebe2bcb6c15ecf707504bf47f31 |
| 2.0.1 | 2026-06-01T13:43:56.162384Z | Cached | 62ae9bb76d02526c7c2110a19b6e6ad788fe28d35e553e35efb02a41a46ab43a |
| 2.0.2 | 2026-06-02T15:17:50.909086Z | Cached | 9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba |
| 2.1.0 | 2026-07-13T14:23:01.507731Z | Cached | 03a564c3704524ee0f7fc56fc621e8796cc2eb8c24d1f1a33b34979815b285c4 |
| 2.2.0 | 2026-08-18T07:24:55.187178Z | Cached | eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f |
Dependencies
collection "^1.19.1"
crypto "^3.0.6"
logging "^1.3.0"
pub_semver "^2.2.0"
record_use "^1.0.0"
yaml "^3.1.3"