import type { KuboRPCClient } from 'kubo-rpc-client' import type { Provider } from '../data/VMs/ProviderVM' import { blobToAsyncIterable } from '@note3/utils' import { Logger } from 'besonders-logger' import { create as createKuboClient } from 'kubo-rpc-client' import { toSafeInteger } from 'lodash-es' import { createSignal } from 'solid-js' import * as W3Name from 'w3name' const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.DEBUG) // eslint-disable-line unused-imports/no-unused-vars export let kuboClient: KuboRPCClient = null export const [hasKubo, setHasKubo] = createSignal(false) export function initKuboClient() { kuboClient = createKuboClient(getKuboConfig()) DEBUG(`Initialized kubo client:`, kuboClient) void checkKuboConnection() // @ts-expect-error window window.kubo = kuboClient // for devtools } function getKuboConfig() { return { protocol: localStorage.getItem('kubo_protocol') || 'http', port: localStorage.getItem('kubo_port') ? toSafeInteger(localStorage.getItem('kubo_port')) : 5001, gatewayPort: localStorage.getItem('kubo_gateway_port') ? toSafeInteger(localStorage.getItem('kubo_gateway_port')) : 8080, host: localStorage.getItem('kubo_host') || 'localhost', } } export async function checkKuboConnection() { if (!kuboClient) throw ERROR(`Kubo not initialized`) try { const version = await (kuboClient.version()) LOG(`Kubo connection check result:`, version) setHasKubo(!!version) } catch (err) { WARN(`Kubo connection check error:`, err) setHasKubo(false) } } export async function uploadCarToKubo(car: Blob) { DEBUG(`Uploading car to kubo`, kuboClient) for await (const result of kuboClient.dag.import(blobToAsyncIterable(car), { pinRoots: true })) { DEBUG(`Kubo result chunk:`, result) } DEBUG(`Kubo upload done:`) } export async function publishIpnsToKubo( name: W3Name.WritableName, revision: W3Name.Revision, ) { if (!kuboClient) throw ERROR(`Kubo not initialized`) // HACK putting record via routing bc. https://github.com/ipfs/kubo/issues/10484 for await ( const result of kuboClient.routing.put( `/ipns/${revision.name}`, W3Name.Revision.encode(revision), { allowOffline: true }, // TODO: allowOffline? ) ) { DEBUG(`Kubo IPNS publish result:`, result) } DEBUG(`Kubo ipns publish done`) // TODO: publish via name API? // ? kuboClient.key.import(...) } export function getKuboGateway() { if (!kuboClient) throw ERROR(`Kubo not initialized`) const cfg = getKuboConfig() return { type: 'kubo-rpc', name: '[auto] local kubo', url: `${cfg.protocol}://${cfg.host}:${cfg.gatewayPort}`, } satisfies Provider }