generateCloudflareWorkerEntry function
Generates the Dart Worker entrypoint used by a Cloudflare deployment.
importPath must identify the application library that exports the
selected factory. With the default engine factory, that library must
expose createEngine; with environment, it must expose
createCloudflareEngine. Names in durableObjectClasses are emitted as
registrations and must be exported by the same application library.
final entry = generateCloudflareWorkerEntry(
importPath: 'package:todo_app/app.dart',
factory: 'environment',
durableObjectClasses: const ['Counter'],
);
Throws an ArgumentError when factory is not engine or environment.
Implementation
String generateCloudflareWorkerEntry({
required String importPath,
String factory = 'engine',
Iterable<String> durableObjectClasses = const <String>[],
}) {
final factorySource = switch (factory) {
'engine' => 'defineCloudflareFetchFactoryAsync(app.createEngine);',
'environment' =>
'defineCloudflareFetchFactoryWithEnvironmentAsync('
'app.createCloudflareEngine);',
_ => throw ArgumentError.value(
factory,
'factory',
'must be engine or environment',
),
};
final classes = durableObjectClasses.toList(growable: false);
final registration = classes.isEmpty
? ''
: '''
defineCloudflareDurableObjects({
${classes.map((name) => " '$name': app.$name.new,").join('\n')}
});
''';
return '''
import 'package:routed_node/cloudflare.dart';
import '$importPath' as app;
void main() {
$registration $factorySource
}
''';
}