loadCatalog function

Future<A2uiCatalog> loadCatalog(
  1. Genkit ai, {
  2. required String id,
  3. A2uiCatalog? catalog,
  4. String? file,
})

Registers an A2UI catalog under an id so the a2ui() middleware can look it up (via a2ui(catalog: id)). Provide either catalog or file.

Returns the registered catalog (with its id set to the catalog's own id if present, otherwise the given id).

Implementation

Future<A2uiCatalog> loadCatalog(
  Genkit ai, {
  required String id,
  A2uiCatalog? catalog,
  String? file,
}) async {
  if (id.isEmpty) {
    throw ArgumentError('loadCatalog(): `id` is required.');
  }

  A2uiCatalog resolved;
  if (file != null) {
    resolved = await _readCatalogFile(file, fallbackId: id);
  } else if (catalog != null) {
    resolved = catalog;
  } else {
    throw ArgumentError('loadCatalog(): provide either `catalog` or `file`.');
  }

  // Register under the requested id. Keep the catalog's own `id` (used as the
  // `catalogId` on surfaces) intact if present; otherwise default it to the id.
  final registered = resolved.id.isNotEmpty ? resolved : resolved.withId(id);
  // Validate now rather than on the first generate call, where the error
  // would name neither the catalog nor its file.
  try {
    registered.toCore();
  } catch (e, st) {
    Error.throwWithStackTrace(
      StateError(
        'loadCatalog(): catalog "$id"${file == null ? '' : ' ($file)'} is not '
        'a valid A2UI catalog: $e',
      ),
      st,
    );
  }
  ai.registry.registerValue(a2uiCatalogValueType, id, registered);
  return registered;
}