"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/netlify/index.ts
var netlify_exports = {};
__export(netlify_exports, {
  connect: () => connect
});
module.exports = __toCommonJS(netlify_exports);

// node_modules/.pnpm/@jspm+core@2.1.0/node_modules/@jspm/core/nodelibs/browser/process.js
var process_exports = {};
__export(process_exports, {
  _debugEnd: () => _debugEnd,
  _debugProcess: () => _debugProcess,
  _events: () => _events,
  _eventsCount: () => _eventsCount,
  _exiting: () => _exiting,
  _fatalExceptions: () => _fatalExceptions,
  _getActiveHandles: () => _getActiveHandles,
  _getActiveRequests: () => _getActiveRequests,
  _kill: () => _kill,
  _linkedBinding: () => _linkedBinding,
  _maxListeners: () => _maxListeners,
  _preload_modules: () => _preload_modules,
  _rawDebug: () => _rawDebug,
  _startProfilerIdleNotifier: () => _startProfilerIdleNotifier,
  _stopProfilerIdleNotifier: () => _stopProfilerIdleNotifier,
  _tickCallback: () => _tickCallback,
  abort: () => abort,
  addListener: () => addListener,
  allowedNodeEnvironmentFlags: () => allowedNodeEnvironmentFlags,
  arch: () => arch,
  argv: () => argv,
  argv0: () => argv0,
  assert: () => assert,
  binding: () => binding,
  browser: () => browser,
  chdir: () => chdir,
  config: () => config,
  cpuUsage: () => cpuUsage,
  cwd: () => cwd,
  debugPort: () => debugPort,
  default: () => process,
  dlopen: () => dlopen,
  domain: () => domain,
  emit: () => emit,
  emitWarning: () => emitWarning,
  env: () => env,
  execArgv: () => execArgv,
  execPath: () => execPath,
  exit: () => exit,
  features: () => features,
  hasUncaughtExceptionCaptureCallback: () => hasUncaughtExceptionCaptureCallback,
  hrtime: () => hrtime,
  kill: () => kill,
  listeners: () => listeners,
  memoryUsage: () => memoryUsage,
  moduleLoadList: () => moduleLoadList,
  nextTick: () => nextTick,
  off: () => off,
  on: () => on,
  once: () => once,
  openStdin: () => openStdin,
  pid: () => pid,
  platform: () => platform,
  ppid: () => ppid,
  prependListener: () => prependListener,
  prependOnceListener: () => prependOnceListener,
  reallyExit: () => reallyExit,
  release: () => release,
  removeAllListeners: () => removeAllListeners,
  removeListener: () => removeListener,
  resourceUsage: () => resourceUsage,
  setSourceMapsEnabled: () => setSourceMapsEnabled,
  setUncaughtExceptionCaptureCallback: () => setUncaughtExceptionCaptureCallback,
  stderr: () => stderr,
  stdin: () => stdin,
  stdout: () => stdout,
  title: () => title,
  umask: () => umask,
  uptime: () => uptime,
  version: () => version,
  versions: () => versions
});
function unimplemented(name) {
  throw new Error("Node.js process " + name + " is not supported by JSPM core outside of Node.js");
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
  if (!draining || !currentQueue)
    return;
  draining = false;
  if (currentQueue.length) {
    queue = currentQueue.concat(queue);
  } else {
    queueIndex = -1;
  }
  if (queue.length)
    drainQueue();
}
function drainQueue() {
  if (draining)
    return;
  var timeout = setTimeout(cleanUpNextTick, 0);
  draining = true;
  var len = queue.length;
  while (len) {
    currentQueue = queue;
    queue = [];
    while (++queueIndex < len) {
      if (currentQueue)
        currentQueue[queueIndex].run();
    }
    queueIndex = -1;
    len = queue.length;
  }
  currentQueue = null;
  draining = false;
  clearTimeout(timeout);
}
function nextTick(fun) {
  var args = new Array(arguments.length - 1);
  if (arguments.length > 1) {
    for (var i = 1; i < arguments.length; i++)
      args[i - 1] = arguments[i];
  }
  queue.push(new Item(fun, args));
  if (queue.length === 1 && !draining)
    setTimeout(drainQueue, 0);
}
function Item(fun, array) {
  this.fun = fun;
  this.array = array;
}
Item.prototype.run = function() {
  this.fun.apply(null, this.array);
};
var title = "browser";
var arch = "x64";
var platform = "browser";
var env = {
  PATH: "/usr/bin",
  LANG: typeof navigator !== "undefined" ? navigator.language + ".UTF-8" : void 0,
  PWD: "/",
  HOME: "/home",
  TMP: "/tmp"
};
var argv = ["/usr/bin/node"];
var execArgv = [];
var version = "v16.8.0";
var versions = {};
var emitWarning = function(message, type) {
  console.warn((type ? type + ": " : "") + message);
};
var binding = function(name) {
  unimplemented("binding");
};
var umask = function(mask) {
  return 0;
};
var cwd = function() {
  return "/";
};
var chdir = function(dir) {
};
var release = {
  name: "node",
  sourceUrl: "",
  headersUrl: "",
  libUrl: ""
};
function noop() {
}
var browser = true;
var _rawDebug = noop;
var moduleLoadList = [];
function _linkedBinding(name) {
  unimplemented("_linkedBinding");
}
var domain = {};
var _exiting = false;
var config = {};
function dlopen(name) {
  unimplemented("dlopen");
}
function _getActiveRequests() {
  return [];
}
function _getActiveHandles() {
  return [];
}
var reallyExit = noop;
var _kill = noop;
var cpuUsage = function() {
  return {};
};
var resourceUsage = cpuUsage;
var memoryUsage = cpuUsage;
var kill = noop;
var exit = noop;
var openStdin = noop;
var allowedNodeEnvironmentFlags = {};
function assert(condition, message) {
  if (!condition) throw new Error(message || "assertion error");
}
var features = {
  inspector: false,
  debug: false,
  uv: false,
  ipv6: false,
  tls_alpn: false,
  tls_sni: false,
  tls_ocsp: false,
  tls: false,
  cached_builtins: true
};
var _fatalExceptions = noop;
var setUncaughtExceptionCaptureCallback = noop;
function hasUncaughtExceptionCaptureCallback() {
  return false;
}
var _tickCallback = noop;
var _debugProcess = noop;
var _debugEnd = noop;
var _startProfilerIdleNotifier = noop;
var _stopProfilerIdleNotifier = noop;
var stdout = void 0;
var stderr = void 0;
var stdin = void 0;
var abort = noop;
var pid = 2;
var ppid = 1;
var execPath = "/bin/usr/node";
var debugPort = 9229;
var argv0 = "node";
var _preload_modules = [];
var setSourceMapsEnabled = noop;
var _performance = {
  now: typeof performance !== "undefined" ? performance.now.bind(performance) : void 0,
  timing: typeof performance !== "undefined" ? performance.timing : void 0
};
if (_performance.now === void 0) {
  nowOffset = Date.now();
  if (_performance.timing && _performance.timing.navigationStart) {
    nowOffset = _performance.timing.navigationStart;
  }
  _performance.now = () => Date.now() - nowOffset;
}
var nowOffset;
function uptime() {
  return _performance.now() / 1e3;
}
var nanoPerSec = 1e9;
function hrtime(previousTimestamp) {
  var baseNow = Math.floor((Date.now() - _performance.now()) * 1e-3);
  var clocktime = _performance.now() * 1e-3;
  var seconds = Math.floor(clocktime) + baseNow;
  var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0];
    nanoseconds = nanoseconds - previousTimestamp[1];
    if (nanoseconds < 0) {
      seconds--;
      nanoseconds += nanoPerSec;
    }
  }
  return [seconds, nanoseconds];
}
hrtime.bigint = function(time) {
  var diff = hrtime(time);
  if (typeof BigInt === "undefined") {
    return diff[0] * nanoPerSec + diff[1];
  }
  return BigInt(diff[0] * nanoPerSec) + BigInt(diff[1]);
};
var _maxListeners = 10;
var _events = {};
var _eventsCount = 0;
function on() {
  return process;
}
var addListener = on;
var once = on;
var off = on;
var removeListener = on;
var removeAllListeners = on;
var emit = noop;
var prependListener = on;
var prependOnceListener = on;
function listeners(name) {
  return [];
}
var process = {
  version,
  versions,
  arch,
  platform,
  browser,
  release,
  _rawDebug,
  moduleLoadList,
  binding,
  _linkedBinding,
  _events,
  _eventsCount,
  _maxListeners,
  on,
  addListener,
  once,
  off,
  removeListener,
  removeAllListeners,
  emit,
  prependListener,
  prependOnceListener,
  listeners,
  domain,
  _exiting,
  config,
  dlopen,
  uptime,
  _getActiveRequests,
  _getActiveHandles,
  reallyExit,
  _kill,
  cpuUsage,
  resourceUsage,
  memoryUsage,
  kill,
  exit,
  openStdin,
  allowedNodeEnvironmentFlags,
  assert,
  features,
  _fatalExceptions,
  setUncaughtExceptionCaptureCallback,
  hasUncaughtExceptionCaptureCallback,
  emitWarning,
  nextTick,
  _tickCallback,
  _debugProcess,
  _debugEnd,
  _startProfilerIdleNotifier,
  _stopProfilerIdleNotifier,
  stdout,
  stdin,
  stderr,
  abort,
  umask,
  chdir,
  cwd,
  env,
  title,
  argv,
  execArgv,
  pid,
  ppid,
  execPath,
  debugPort,
  hrtime,
  argv0,
  _preload_modules,
  setSourceMapsEnabled
};

// src/connection-from-store.ts
var import_cement = require("@adviser/cement");
var import_core = require("@fireproof/core");
var ConnectionFromStore = class extends import_core.bs.ConnectionBase {
  constructor(sthis, url) {
    const logger = (0, import_core.ensureLogger)(sthis, "ConnectionFromStore", {
      url: () => url.toString(),
      this: 1,
      log: 1
    });
    super(url, logger);
    this.stores = void 0;
    this.sthis = sthis;
  }
  async onConnect() {
    this.logger.Debug().Msg("onConnect-start");
    const stores = {
      base: this.url
      // data: this.urlData,
      // meta: this.urlMeta,
    };
    const rName = this.url.getParamResult("name");
    if (rName.isErr()) {
      throw this.logger.Error().Err(rName).Msg("missing Parameter").AsError();
    }
    const storeRuntime = import_core.bs.toStoreRuntime({ stores }, this.sthis);
    const loader = {
      name: rName.Ok(),
      ebOpts: {
        logger: this.logger,
        store: { stores },
        storeRuntime
      },
      sthis: this.sthis
    };
    this.stores = {
      data: await storeRuntime.makeDataStore(loader),
      meta: await storeRuntime.makeMetaStore(loader)
    };
    this.logger.Debug().Msg("onConnect-done");
    return;
  }
};
function connectionFactory(sthis, iurl) {
  return new ConnectionFromStore(sthis, import_cement.URI.from(iurl));
}
function makeKeyBagUrlExtractable(sthis) {
  let base = sthis.env.get("FP_KEYBAG_URL");
  if (!base) {
    if ((0, import_cement.runtimeFn)().isBrowser) {
      base = "indexdb://fp-keybag";
    } else {
      base = "file://./dist/kb-dir-partykit";
    }
  }
  const kbUrl = import_cement.BuildURI.from(base);
  kbUrl.defParam("extractKey", "_deprecated_internal_api");
  sthis.env.set("FP_KEYBAG_URL", kbUrl.toString());
  sthis.logger.Debug().Url(kbUrl, "keyBagUrl").Msg("Make keybag url extractable");
}

// src/netlify/gateway.ts
var import_cement2 = require("@adviser/cement");
var import_core2 = require("@fireproof/core");
var NetlifyGateway = class {
  constructor(sthis) {
    this.sthis = (0, import_core2.ensureSuperLog)(sthis, "NetlifyGateway");
    this.logger = this.sthis.logger;
  }
  async buildUrl(baseUrl, key) {
    return import_cement2.Result.Ok(baseUrl.build().setParam("key", key).URI());
  }
  async destroy(url) {
    const { store } = (0, import_core2.getStore)(url, this.sthis, (...args) => args.join("/"));
    if (store !== "meta") {
      return import_cement2.Result.Ok(void 0);
    }
    const rName = url.getParamResult("name");
    if (rName.isErr()) {
      return import_cement2.Result.Err(rName.Err());
    }
    let name = rName.Ok();
    const index = url.getParam("index");
    if (index) {
      name += `-${index}`;
    }
    name += ".fp";
    const remoteBaseUrl = url.getParam("remoteBaseUrl");
    if (!remoteBaseUrl) {
      return import_cement2.Result.Err(new Error("Remote base URL not found in the URI"));
    }
    const fetchUrl = import_cement2.BuildURI.from(remoteBaseUrl).setParam("meta", name).URI();
    const response = await fetch(fetchUrl.asURL(), { method: "DELETE" });
    if (!response.ok) {
      return this.logger.Error().Str("status", response.statusText).Msg("Failed to destroy meta database").ResultError();
    }
    return import_cement2.Result.Ok(void 0);
  }
  async start(uri) {
    const protocol = uri.host.startsWith("localhost") ? "http" : "https";
    const host = uri.host;
    const path = "/fireproof";
    const urlString = `${protocol}://${host}${path}`;
    const baseUrl = import_cement2.BuildURI.from(urlString).URI();
    const ret = uri.build().defParam("version", "v0.1-netlify").defParam("remoteBaseUrl", baseUrl.toString()).URI();
    return import_cement2.Result.Ok(ret);
  }
  async close() {
    return import_cement2.Result.Ok(void 0);
  }
  async put(url, body) {
    const { store } = (0, import_core2.getStore)(url, this.sthis, (...args) => args.join("/"));
    const rParams = url.getParamsResult("key", "name");
    if (rParams.isErr()) {
      return this.logger.Error().Url(url).Err(rParams).Msg("Put Error").ResultError();
    }
    const { key } = rParams.Ok();
    let { name } = rParams.Ok();
    const index = url.getParam("index");
    if (index) {
      name += `-${index}`;
    }
    name += ".fp";
    const remoteBaseUrl = url.getParam("remoteBaseUrl");
    if (!remoteBaseUrl) {
      return import_cement2.Result.Err(new Error("Remote base URL not found in the URI"));
    }
    const fetchUrl = import_cement2.BuildURI.from(remoteBaseUrl);
    switch (store) {
      case "meta":
        fetchUrl.setParam("meta", name);
        break;
      default:
        fetchUrl.setParam("car", key);
        break;
    }
    if (store === "meta") {
      const bodyRes = await import_core2.bs.addCryptoKeyToGatewayMetaPayload(url, this.sthis, body);
      if (bodyRes.isErr()) {
        return import_cement2.Result.Err(bodyRes.Err());
      }
      body = bodyRes.Ok();
    }
    const done = await fetch(fetchUrl.URI().asURL(), { method: "PUT", body });
    if (!done.ok) {
      return this.logger.Error().Url(fetchUrl.URI()).Int("status", done.status).Msg(`failed to upload ${store}`).ResultError();
    }
    return import_cement2.Result.Ok(void 0);
  }
  async get(url) {
    const { store } = (0, import_core2.getStore)(url, this.sthis, (...args) => args.join("/"));
    const rParams = url.getParamsResult("key", "name", "remoteBaseUrl");
    if (rParams.isErr()) {
      return import_cement2.Result.Err(rParams.Err());
    }
    const { key, remoteBaseUrl } = rParams.Ok();
    let { name } = rParams.Ok();
    const index = url.getParam("index");
    if (index) {
      name += `-${index}`;
    }
    name += ".fp";
    const fetchUrl = import_cement2.BuildURI.from(remoteBaseUrl);
    switch (store) {
      case "meta":
        fetchUrl.setParam("meta", name);
        break;
      default:
        fetchUrl.setParam("car", key);
        break;
    }
    const rresponse = await (0, import_cement2.exception2Result)(() => {
      return fetch(fetchUrl.URI().asURL());
    });
    if (rresponse.isErr()) {
      return this.logger.Error().Url(fetchUrl).Err(rresponse).Msg("Failed to fetch").ResultError();
    }
    const response = rresponse.Ok();
    if (!response.ok) {
      return import_cement2.Result.Err(new import_core2.NotFoundError(`${store} not found: ${url}`));
    }
    const data = new Uint8Array(await response.arrayBuffer());
    if (store === "meta") {
      const res = await import_core2.bs.setCryptoKeyFromGatewayMetaPayload(url, this.sthis, data);
      if (res.isErr()) {
        return import_cement2.Result.Err(res.Err());
      }
    }
    return import_cement2.Result.Ok(data);
  }
  async delete(url) {
    const { store } = (0, import_core2.getStore)(url, this.sthis, (...args) => args.join("/"));
    const rParams = url.getParamsResult("key", "name", "remoteBaseUrl");
    if (rParams.isErr()) {
      return import_cement2.Result.Err(rParams.Err());
    }
    const { key, remoteBaseUrl } = rParams.Ok();
    let { name } = rParams.Ok();
    const index = url.getParam("index");
    if (index) {
      name += `-${index}`;
    }
    name += ".fp";
    const fetchUrl = import_cement2.BuildURI.from(remoteBaseUrl);
    switch (store) {
      case "meta":
        fetchUrl.setParam("meta", name);
        break;
      default:
        if (!key) {
          return import_cement2.Result.Err(new Error("Key not found in the URI"));
        }
        fetchUrl.setParam("car", key);
        break;
    }
    const response = await fetch(fetchUrl.URI().asURL(), { method: "DELETE" });
    if (!response.ok) {
      return import_cement2.Result.Err(new Error(`Failed to delete car: ${response.statusText}`));
    }
    return import_cement2.Result.Ok(void 0);
  }
  async subscribe(url, callback) {
    url = url.build().setParam("key", "main").defParam("interval", "100").defParam("maxInterval", "3000").URI();
    let lastData = void 0;
    const initInterval = parseInt(url.getParam("interval") || "100", 10);
    const maxInterval = parseInt(url.getParam("maxInterval") || "3000", 10);
    let interval = initInterval;
    const fetchData = async () => {
      const result = await this.get(url);
      if (result.isOk()) {
        const data = result.Ok();
        if (!lastData || !data.every((value, index) => lastData && value === lastData[index])) {
          lastData = data;
          callback(data);
          interval = initInterval;
        } else {
          interval = Math.min(interval * 2, maxInterval);
        }
      }
      timeoutId = setTimeout(fetchData, interval);
    };
    let timeoutId = setTimeout(fetchData, interval);
    return import_cement2.Result.Ok(() => {
      clearTimeout(timeoutId);
    });
  }
};
var NetlifyTestStore = class {
  constructor(sthis, gw) {
    this.sthis = (0, import_core2.ensureSuperLog)(sthis, "NetlifyTestStore");
    this.logger = this.sthis.logger;
    this.gateway = gw;
  }
  async get(iurl, key) {
    const url = iurl.build().setParam("key", key).URI();
    const buffer = await this.gateway.get(url);
    return buffer.Ok();
  }
};
var onceRegisterNetlifyStoreProtocol = new import_cement2.KeyedResolvOnce();
function registerNetlifyStoreProtocol(protocol = "netlify:", overrideBaseURL) {
  return onceRegisterNetlifyStoreProtocol.get(protocol).once(() => {
    import_cement2.URI.protocolHasHostpart(protocol);
    return import_core2.bs.registerStoreProtocol({
      protocol,
      overrideBaseURL,
      gateway: async (sthis) => {
        return new NetlifyGateway(sthis);
      },
      test: async (sthis) => {
        const gateway = new NetlifyGateway(sthis);
        return new NetlifyTestStore(sthis, gateway);
      }
    });
  });
}

// src/netlify/index.ts
var import_cement3 = require("@adviser/cement");
if (!(0, import_cement3.runtimeFn)().isBrowser) {
  const url = import_cement3.BuildURI.from(process_exports.env.FP_KEYBAG_URL || "file://./dist/kb-dir-netlify");
  url.setParam("extractKey", "_deprecated_internal_api");
  process_exports.env.FP_KEYBAG_URL = url.toString();
}
registerNetlifyStoreProtocol();
var connectionCache = new import_cement3.KeyedResolvOnce();
var connect = (db, remoteDbName = "", url = "netlify://localhost:8888?protocol=ws") => {
  const { sthis, blockstore, name: dbName } = db;
  if (!dbName) {
    throw new Error("dbName is required");
  }
  const urlObj = import_cement3.BuildURI.from(url);
  const existingName = urlObj.getParam("name");
  urlObj.defParam("name", remoteDbName || existingName || dbName);
  urlObj.defParam("localName", dbName);
  urlObj.defParam("storekey", `@${dbName}:data@`);
  return connectionCache.get(urlObj.toString()).once(() => {
    makeKeyBagUrlExtractable(sthis);
    const connection = connectionFactory(sthis, urlObj);
    connection.connect_X(blockstore);
    return connection;
  });
};
//# sourceMappingURL=index.cjs.map