p-hatan/ mirror

pub repository

mirror.p-hatan.com

hooks

2.2.0

A 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

Download archive

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, the hooks.user_defines configuration block must be placed in the workspace root pubspec.yaml file. Defines inside member package pubspec.yaml files 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.path mangling 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.recordedUses out 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 ProtocolExtension into a base class instead of an interface, with default implementations for all methods including the newly added outputFiles.

1.0.3

  • Deprecated recordedUsagesFile in LinkInput.
  • Added recordedUses getter to LinkInput.
  • 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 testBuildHook to emit output validation errors if there are any.

0.20.5

  • Document input.packageRoot in 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 outputDirectory to 10 hexadecimal characters to avoid running out of path length on Windows.

0.20.1

  • Update outdated documentation.
  • Deprecate HookOutputBuilder.addDependency and HookOutputBuilder.addDependencies in favor of HookOutputBuilder.dependencies.add and HookOutputBuilder.dependencies.addAll.

0.20.0

  • Breaking change Rename EncodedAsset.jsonPath to EncodedAsset.encodingJsonPath. This field only governs the EncodedAsset.encoding field, 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 build and link methods as primary entry points.
  • Added failure outputs and documented exit codes.

0.19.0

  • Split up package:native_assets_cli in package:hooks, package:code_assets, and package: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 ToBuild Routing. This replaces the deprecated Metadata.
  • Added support for user-defines.

0.13.0

  • Breaking change Removed CodeAsset.type, use EncodedAsset.isCodeAsset instead.
  • Breaking change: Removed CodeAsset.os and CodeAsset.architecture. Use CodeConfig.targetOS and CodeConfig.targetArchitecture instead.
  • HookInput.outputDirectory is now based on HookInput.outputDirectoryShared. The outputDirectory now creates its own subdirectory inside outputDirectoryShared.
  • 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 Input and Output of hooks are absolute.
  • Added addDataAssetDirectories extension method on BuildOutputBuilder.
  • 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 BuildConfig is now split in BuildInput and BuildConfig. 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. The outputDirectory is the same if the config is the same.
  • Breaking change The output.json is now part of BuildInput.

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 supportedAssetTypes to buildAssetTypes. 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 BuildMode to package:native_toolchain_c. This way it can be controlled in the build hook together with the OptimizationLevel. Most likely, every package should ship with release. BuildMode.debug should only be used while developing the package locally.
  • Breaking change Move HookConfig.targetOS to CodeConfig. DataAssets and other asset types should not depend on OS for now.
  • Breaking change: Change the behavior of testBuildHook and testCodeBuildHook; instead of defining tests, these methods should now be called from within tests.
  • Move the package:test dependency from a regular dependency (exported to calling packages) to a dev_dependency.

0.9.0

  • Add BuildConfig and LinkConfig outputDirectoryShared.
  • Remove package:native_assets_cli/locking.dart with runUnderDirectoryLock. Hook writers should not use this, the native_assets_builder does 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_config and package: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_TESTING prefix for environment variables used for testing on Dart CI
  • No longer try to resolve uris encoded in config.json against any base uri. The hook/{build,link}.dart invoker 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 BuildConfig and BuildOutput now expose fromJson and toJson.
  • Breaking change Removed Asset class, removed {Build,Link}Output.assets*. Hook writers should now use e.g. output.dataAssets.add(DataAsset(...)) instead of output.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 build and link methods.

0.7.3

  • Fix some more cases of: BuildConfig.dependencies and LinkConfig.dependencies no longer have to specify Dart sources.
  • DataAsset examples report all assets from assets/ dir and default the asset names to the path inside the package.
  • Add package:native_assets_cli/test.dart with testBuildHook helper method for testing build hooks.
  • Add package:native_assets_cli/locking.dart with runUnderDirectoryLock.

0.7.2

  • Deprecate metadata concept.

0.7.1

  • BuildConfig.dependencies and LinkConfig.dependencies no longer have to specify Dart sources.

0.7.0

  • BuildConfig constructors now have a required linkingEnabled parameter.

0.6.1

  • Introduce Builder and Linker interface.
  • Copy resources.json to the build directory.
  • Introduce HookConfig.targetIosSdk and HookConfig.targetMacosSdk optional values.

0.6.0

  • Add support for hook/link.dart.

0.5.4

  • Update documentation about providing NativeCodeAsset.file in dry runs.

0.5.3

0.5.2

  • Fix test.

0.5.1

0.5.0

0.4.2

  • Fix dartdoc generation. Hide the implementation details.

0.4.1

  • Breaking change Removed all code not used in build.dart scripts out of the public API.

0.4.0

  • Added example/use_dart_api/ detailing how to use dart_api_dl.h from the Dart SDK in native code.
  • Breaking change Moved code not used in build.dart to package:native_assets_builder.

0.3.2

  • Fixed an issue where Depenendencies.dependencies could 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.name to Asset.id (#100).
  • Added topics.
  • Fixed metadata example.
  • Throws FormatExceptions instead of TypeErrors 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 hooks
pubspec.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

VersionPublishedArchiveSHA-256
0.0.12013-08-08T07:24:30.015510ZCachedb8c525752ff50667a8eac7b88039b7d540ef3194a686f394f9d3003862bee0f7
0.1.02013-08-13T05:58:43.221730ZCached3b0bf27b085c030c0786b5b7c29f860a76a3a93693e7efda10b277cc8b54ff4c
0.1.12013-09-16T21:55:31.289740ZCached35ad29232599c07a209a808c6e9051915d2559a20ed16a52826ec8a2b85abcea
0.1.22013-12-06T17:10:24.120100ZCachede43afeb09752dcd255c4450ff5df49c10d6fa34d06a239da678029722bd003d7
0.19.02025-05-01T07:57:27.553413ZCached851928fff27d0ff030f54af32c5fb6ce4707a37f7d2e2976cea68dea9b939909
0.19.12025-05-19T07:28:49.998615ZCachedc29b5d113b093995426c9d2d4ce157902f04d426d9fb44206f88d2da7ae3e0f2
0.19.22025-05-21T15:59:02.517814ZCacheda4389bc0e283f953cae32e3b768178ed3e1051fc11b127af38ab43251e3d301e
0.19.32025-05-21T17:42:22.098685ZCached6fa18c99c5fd6456c3edd99e3f857099c8748eb2062bb8374970f7896858512b
0.19.42025-06-12T11:32:07.585554ZCachedc3564567a6b82ad1ef8eef18a4ad6f37f7a56dd3fa59fe7afa1d8d75322fff1a
0.19.52025-06-12T13:39:54.565049ZCached75363eae6c0c2db051c4f6b3b1fcdea8a09c4a596cc83bfff847661da6e80dfc
0.20.02025-08-04T11:08:48.365074ZCached2bd640e4625fdfe5788ef33d825a8639797d44bce05695ab13543cde0ff9a078
0.20.12025-08-27T14:57:22.055231ZCached22abd27b650a571e53576abe732e4d9053aacaaa6dee23e9ff106c63e3e5b96c
0.20.22025-10-08T13:20:44.201921ZCachedceee15e2cef1b23e879e2d7adf581b700947b0dff33244ef3a1ee32910fd4938
0.20.32025-10-13T07:47:52.463980ZCached4ad76d2de250aec8345e6acc895f452f17889e7a3005a4b7401479f3f7d84447
0.20.42025-10-15T09:15:50.448066ZCached6274d1fe704962cbb881d437aae11af3e6eecc810da7438cc100c85679b4feb6
0.20.52025-10-27T12:25:40.243174ZCached5410b9f4f6c9f01e8ff0eb81c9801ea13a3c3d39f8f0b1613cda08e27eab3c18
1.0.02025-11-07T15:23:19.646021ZCached5d309c86e7ce34cd8e37aa71cb30cb652d3829b900ab145e4d9da564b31d59f7
1.0.12026-02-03T16:57:56.600571ZCached7a08a0d684cb3b8fb604b78455d5d352f502b68079f7b80b831c62220ab0a4f6
1.0.22026-03-06T11:19:50.417879ZCachede79ed1e8e1929bc6ecb6ec85f0cb519c887aa5b423705ded0d0f2d9226def388
1.0.32026-04-21T09:33:52.565162ZCached025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e
2.0.02026-05-18T15:37:25.524712ZCacheda41af4e8fc687cd6d33de9751eb936c8c0204ebe2bcb6c15ecf707504bf47f31
2.0.12026-06-01T13:43:56.162384ZCached62ae9bb76d02526c7c2110a19b6e6ad788fe28d35e553e35efb02a41a46ab43a
2.0.22026-06-02T15:17:50.909086ZCached9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba
2.1.02026-07-13T14:23:01.507731ZCached03a564c3704524ee0f7fc56fc621e8796cc2eb8c24d1f1a33b34979815b285c4
2.2.02026-08-18T07:24:55.187178ZCachedeaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f

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"