updateTursoSharedRegionSource function
Registers turso.Functions.turso for the shared database in the region Worker source.
Options other than schemaManifest and databaseBindings are kept.
turso.Functions.tursoToken is removed because a direct connection token would grant
access to the whole shared database. Returns null if the deploy array is not found.
region Workerのsourceに共用DB用のturso.Functions.tursoを登録します。
schemaManifestとdatabaseBindings以外のオプションは保持します。
直接接続トークンは共用DB全体の権限になるためturso.Functions.tursoTokenは削除します。
deploy配列が見つからない場合はnullを返します。
Implementation
String? updateTursoSharedRegionSource(
String source, {
required TursoSharedConfig config,
required bool useSchemaManifest,
}) {
const functionName = "turso.Functions.turso";
var updated = CloudflareSourceUtils.ensureImport(
source,
alias: "turso",
package: "@mathrunet/masamune_cloudflare_turso",
);
const manifestImport =
'import tursoSharedSchemaManifest from "./turso_shared_schema_manifest.json";';
if (useSchemaManifest && !updated.contains(manifestImport)) {
final imports =
RegExp(r"^import .+;$", multiLine: true).allMatches(updated).toList();
updated = imports.isEmpty
? "$manifestImport\n$updated"
: updated.replaceRange(
imports.last.end, imports.last.end, "\n$manifestImport");
}
updated = _removeFunctionCallLines(updated, "turso.Functions.tursoToken");
final arguments =
CloudflareSourceUtils.functionArguments(updated, functionName);
final preserved = <String>[];
if (arguments != null && arguments.isNotEmpty) {
final trimmed = arguments.replaceFirst(RegExp(r",\s*$"), "");
final properties = _objectLiteralProperties(trimmed);
if (properties == null) {
preserved.add("...($trimmed)");
} else {
for (final property in properties) {
final key = RegExp(r'''^["']?([A-Za-z_$][\w$]*)["']?\s*:''')
.firstMatch(property)
?.group(1);
if (key != null && _tursoSharedManagedKeys.contains(key)) {
continue;
}
preserved.add(property);
}
}
}
final bindings = config.databaseBindingsJson().entries.map((entry) {
final binding = (entry.value as Map)[config.logicalName] as Map;
return " ${entry.key}: { ${jsonEncode(config.logicalName)}: "
"{ database: ${jsonEncode(binding["database"])}, group: ${jsonEncode(binding["group"])} } },";
}).join("\n");
final replacement = """
turso.Functions.turso({
${useSchemaManifest ? " schemaManifest: tursoSharedSchemaManifest as turso.TursoSchemaManifest,\n" : ""} databaseBindings: {
$bindings
},
${preserved.map((property) => " $property,\n").join()} }),""";
if (arguments != null) {
return CloudflareSourceUtils.replaceFunctionCall(
updated, functionName, replacement.trimLeft());
}
return CloudflareSourceUtils.insertDeployFunctions(
updated, ["$replacement\n"]);
}