@fireproof/core 0.20.0-dev-preview-55 → 0.20.0-dev-preview-58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -126,15 +126,21 @@ var SuperThisImpl = class _SuperThisImpl {
126
126
  });
127
127
  }
128
128
  };
129
- function presetEnv() {
129
+ function presetEnv(ipreset) {
130
+ let preset = {};
131
+ if (ipreset instanceof Map) {
132
+ preset = Object.fromEntries(ipreset.entries());
133
+ } else if (typeof ipreset === "object" && ipreset !== null) {
134
+ preset = ipreset;
135
+ }
130
136
  const penv = new Map([
131
137
  // ["FP_DEBUG", "xxx"],
132
138
  // ["FP_ENV", "development"],
133
139
  ...Array.from(
134
- Object.entries(
135
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
136
- globalThis[Symbol.for("FP_PRESET_ENV")] || {}
137
- )
140
+ Object.entries({
141
+ ...setPresetEnv({}),
142
+ ...preset
143
+ })
138
144
  )
139
145
  // .map(([k, v]) => [k, v as string])
140
146
  ]);
@@ -171,7 +177,7 @@ function onSuperThis(fn) {
171
177
  function ensureSuperThis(osthis) {
172
178
  const env = envFactory({
173
179
  symbol: osthis?.env?.symbol || "FP_ENV",
174
- presetEnv: osthis?.env?.presetEnv || presetEnv()
180
+ presetEnv: presetEnv(osthis?.env?.presetEnv)
175
181
  });
176
182
  const ret = new SuperThisImpl({
177
183
  logger: osthis?.logger || globalLogger(),
@@ -437,6 +443,14 @@ function ensureURIDefaults(sthis, name, curi, uri, store, ctx) {
437
443
  }
438
444
  return ret.URI();
439
445
  }
446
+ function setPresetEnv(o, symbol = "FP_PRESET_ENV") {
447
+ const key = Symbol.for(symbol);
448
+ const env = globalThis[key] ?? {};
449
+ for (const [k, v] of Object.entries(o)) {
450
+ env[k] = v;
451
+ }
452
+ return env;
453
+ }
440
454
 
441
455
  // src/write-queue.ts
442
456
  import { Future } from "@adviser/cement";
@@ -5209,11 +5223,18 @@ function fireproof(name, opts) {
5209
5223
  // src/runtime/index.ts
5210
5224
  var runtime_exports = {};
5211
5225
  __export(runtime_exports, {
5226
+ AddKeyToDbMetaGateway: () => AddKeyToDbMetaGateway,
5212
5227
  FILESTORE_VERSION: () => FILESTORE_VERSION,
5213
5228
  INDEXEDDB_VERSION: () => INDEXEDDB_VERSION,
5214
5229
  KeyBag: () => KeyBag,
5230
+ V2SerializedMetaKeyExtractKey: () => V2SerializedMetaKeyExtractKey,
5231
+ addKeyToDbMetaDecoder: () => addKeyToDbMetaDecoder,
5232
+ addKeyToDbMetaEncoder: () => addKeyToDbMetaEncoder,
5233
+ decodeAsToSerializedMeta: () => decodeAsToSerializedMeta,
5215
5234
  defaultKeyBagOpts: () => defaultKeyBagOpts,
5216
5235
  defaultKeyBagUrl: () => defaultKeyBagUrl,
5236
+ encodeAsV1SerializedMetaKey: () => encodeAsV1SerializedMetaKey,
5237
+ encodeAsV2SerializedMetaKey: () => encodeAsV2SerializedMetaKey,
5217
5238
  files: () => files_exports,
5218
5239
  getFileName: () => getFileName,
5219
5240
  getKeyBag: () => getKeyBag,
@@ -5224,7 +5245,8 @@ __export(runtime_exports, {
5224
5245
  keysByFingerprint: () => keysByFingerprint,
5225
5246
  mf: () => wait_pr_multiformats_exports,
5226
5247
  registerKeyBagProviderFactory: () => registerKeyBagProviderFactory,
5227
- runtimeFn: () => runtimeFn4,
5248
+ runtimeFn: () => runtimeFn5,
5249
+ sts: () => sts_service_exports,
5228
5250
  toKeyWithFingerPrint: () => toKeyWithFingerPrint
5229
5251
  });
5230
5252
 
@@ -5238,13 +5260,109 @@ __export(wait_pr_multiformats_exports, {
5238
5260
  // src/runtime/wait-pr-multiformats/codec-interface.ts
5239
5261
  var codec_interface_exports = {};
5240
5262
 
5263
+ // src/runtime/sts-service/index.ts
5264
+ var sts_service_exports = {};
5265
+ __export(sts_service_exports, {
5266
+ SessionTokenService: () => SessionTokenService,
5267
+ env2jwk: () => env2jwk,
5268
+ envKeyDefaults: () => envKeyDefaults,
5269
+ jwk2env: () => jwk2env
5270
+ });
5271
+ import { exception2Result as exception2Result5 } from "@adviser/cement";
5272
+ import { exportJWK, importJWK, jwtVerify, SignJWT } from "jose";
5273
+ import { generateKeyPair } from "jose/key/generate/keypair";
5274
+ import { base58btc as base58btc4 } from "multiformats/bases/base58";
5275
+ var envKeyDefaults = {
5276
+ SECRET: "CLOUD_SESSION_TOKEN_SECRET",
5277
+ PUBLIC: "CLOUD_SESSION_TOKEN_PUBLIC"
5278
+ };
5279
+ async function jwk2env(jwk, sthis = ensureSuperThis()) {
5280
+ const inPubKey = await exportJWK(jwk);
5281
+ return base58btc4.encode(sthis.txt.encode(JSON.stringify(inPubKey)));
5282
+ }
5283
+ async function env2jwk(env, alg, sthis = ensureSuperThis()) {
5284
+ const inJWT = JSON.parse(sthis.txt.decode(base58btc4.decode(env)));
5285
+ return importJWK(inJWT, alg, { extractable: true });
5286
+ }
5287
+ var SessionTokenService = class _SessionTokenService {
5288
+ #key;
5289
+ #param;
5290
+ static async generateKeyPair(alg = "ES256", options = { extractable: true }, generateKeyPairFN = (alg2, options2) => generateKeyPair(alg2, options2)) {
5291
+ const material = await generateKeyPairFN(alg, options);
5292
+ return {
5293
+ material,
5294
+ strings: {
5295
+ publicKey: await jwk2env(material.publicKey),
5296
+ privateKey: await jwk2env(material.privateKey)
5297
+ }
5298
+ };
5299
+ }
5300
+ static async createFromEnv(sthis, sp = {}) {
5301
+ let envToken = sthis.env.get(sp.privateEnvKey ?? envKeyDefaults.SECRET);
5302
+ if (!envToken) {
5303
+ envToken = sthis.env.get(sp.publicEnvKey ?? envKeyDefaults.PUBLIC);
5304
+ }
5305
+ if (!envToken) {
5306
+ throw new Error(
5307
+ `env not found for: ${sp.privateEnvKey ?? envKeyDefaults.SECRET} or ${sp.publicEnvKey ?? envKeyDefaults.PUBLIC}`
5308
+ );
5309
+ }
5310
+ return _SessionTokenService.create({ token: envToken }, sthis);
5311
+ }
5312
+ static async create(stsparam, sthis = ensureSuperThis()) {
5313
+ const key = await env2jwk(stsparam.token, stsparam.alg ?? "ES256", sthis);
5314
+ return new _SessionTokenService(key, stsparam);
5315
+ }
5316
+ constructor(key, stsparam) {
5317
+ this.#key = key;
5318
+ this.#param = stsparam;
5319
+ }
5320
+ get validFor() {
5321
+ let validFor = this.#param.validFor ?? 3600;
5322
+ if (!(0 <= validFor && validFor <= 36e5)) {
5323
+ validFor = 36e5;
5324
+ }
5325
+ return validFor;
5326
+ }
5327
+ get alg() {
5328
+ return this.#param.alg ?? "ES256";
5329
+ }
5330
+ get isssuer() {
5331
+ return this.#param.issuer ?? "fireproof";
5332
+ }
5333
+ get audience() {
5334
+ return this.#param.audience ?? "fireproof";
5335
+ }
5336
+ async validate(token) {
5337
+ return exception2Result5(async () => {
5338
+ const ret = await jwtVerify(token, this.#key);
5339
+ return ret;
5340
+ });
5341
+ }
5342
+ // async getEnvKey(): Promise<string> {
5343
+ // return jwk2env(ensureSuperThis(), this.#key);
5344
+ // }
5345
+ async tokenFor(p) {
5346
+ if (this.#key.type !== "private") {
5347
+ throw new Error("key must be private");
5348
+ }
5349
+ const token = await new SignJWT({
5350
+ userId: p.userId,
5351
+ tenants: p.tenants,
5352
+ ledgers: p.ledgers
5353
+ }).setProtectedHeader({ alg: this.alg }).setIssuedAt().setIssuer(p.issuer ?? this.isssuer).setAudience(p.audience ?? this.audience).setExpirationTime(Date.now() + (p.validFor ?? this.validFor)).sign(this.#key);
5354
+ return token;
5355
+ }
5356
+ };
5357
+
5241
5358
  // src/runtime/index.ts
5242
- import { runtimeFn as runtimeFn4 } from "@adviser/cement";
5359
+ import { runtimeFn as runtimeFn5 } from "@adviser/cement";
5243
5360
 
5244
5361
  // src/runtime/gateways/index.ts
5245
5362
  var gateways_exports = {};
5246
5363
  __export(gateways_exports, {
5247
5364
  DefSerdeGateway: () => DefSerdeGateway,
5365
+ cloud: () => gateway_exports2,
5248
5366
  dbMetaEvent2Serialized: () => dbMetaEvent2Serialized,
5249
5367
  decode2DbMetaEvents: () => decode2DbMetaEvents,
5250
5368
  file: () => file_exports,
@@ -5260,9 +5378,1848 @@ __export(file_exports, {
5260
5378
  sysFileSystemFactory: () => sysFileSystemFactory
5261
5379
  });
5262
5380
 
5381
+ // src/runtime/gateways/cloud/gateway.ts
5382
+ var gateway_exports2 = {};
5383
+ __export(gateway_exports2, {
5384
+ FireproofCloudGateway: () => FireproofCloudGateway,
5385
+ registerFireproofCloudStoreProtocol: () => registerFireproofCloudStoreProtocol,
5386
+ toCloud: () => toCloud
5387
+ });
5388
+ import {
5389
+ Result as Result17,
5390
+ URI as URI17,
5391
+ KeyedResolvOnce as KeyedResolvOnce6,
5392
+ exception2Result as exception2Result9,
5393
+ param,
5394
+ ResolveOnce as ResolveOnce8,
5395
+ to_uint8
5396
+ } from "@adviser/cement";
5397
+
5398
+ // src/protocols/cloud/msg-types.ts
5399
+ var VERSION = "FP-MSG-1.0";
5400
+ function isAuthTypeFPCloudJWK(a) {
5401
+ return a.type === "fp-cloud-jwk";
5402
+ }
5403
+ function isAuthTypeFPCloud(a) {
5404
+ return a.type === "fp-cloud";
5405
+ }
5406
+ function keyTenantLedger(t) {
5407
+ return `${t.tenant}:${t.ledger}`;
5408
+ }
5409
+ function qsidEqual(a, b) {
5410
+ return a.reqId === b.reqId && a.resId === b.resId;
5411
+ }
5412
+ function qsidKey(qsid) {
5413
+ return `${qsid.reqId}:${qsid.resId}`;
5414
+ }
5415
+ function MsgIsTid(msg, tid) {
5416
+ return msg.tid === tid;
5417
+ }
5418
+ function MsgIsError(rq) {
5419
+ return rq.type === "error";
5420
+ }
5421
+ function MsgIsQSError(rq) {
5422
+ return rq.res.type === "error" || rq.req.type === "error";
5423
+ }
5424
+ function coerceFPStoreTypes(s) {
5425
+ const x = s?.trim();
5426
+ if (x === "meta" || x === "car" || x === "wal" || x === "file") {
5427
+ return x;
5428
+ }
5429
+ throw new Error(`Invalid FPStoreTypes: ${s}`);
5430
+ }
5431
+ function isProtocolCapabilities(s) {
5432
+ const x = s.trim();
5433
+ return x === "reqRes" || x === "stream";
5434
+ }
5435
+ function defaultGestalt(msgP, gestalt) {
5436
+ return {
5437
+ storeTypes: ["meta", "file", "car", "wal"],
5438
+ httpEndpoints: ["/fp"],
5439
+ wsEndpoints: ["/ws"],
5440
+ encodings: ["JSON"],
5441
+ protocolCapabilities: msgP.protocolCapabilities || ["reqRes", "stream"],
5442
+ auth: [],
5443
+ requiresAuth: false,
5444
+ data: msgP.hasPersistent ? {
5445
+ inband: true,
5446
+ outband: true
5447
+ } : void 0,
5448
+ meta: msgP.hasPersistent ? {
5449
+ inband: true,
5450
+ outband: true
5451
+ } : void 0,
5452
+ wal: msgP.hasPersistent ? {
5453
+ inband: true,
5454
+ outband: true
5455
+ } : void 0,
5456
+ reqTypes: [
5457
+ "reqOpen",
5458
+ "reqGestalt",
5459
+ // "reqSignedUrl",
5460
+ "reqSubscribeMeta",
5461
+ "reqPutMeta",
5462
+ "reqBindMeta",
5463
+ "reqDelMeta",
5464
+ "reqPutData",
5465
+ "reqGetData",
5466
+ "reqDelData",
5467
+ "reqPutWAL",
5468
+ "reqGetWAL",
5469
+ "reqDelWAL",
5470
+ "reqUpdateMeta"
5471
+ ],
5472
+ resTypes: [
5473
+ "resOpen",
5474
+ "resGestalt",
5475
+ // "resSignedUrl",
5476
+ "resSubscribeMeta",
5477
+ "resPutMeta",
5478
+ "resGetMeta",
5479
+ "resDelMeta",
5480
+ "resPutData",
5481
+ "resGetData",
5482
+ "resDelData",
5483
+ "resPutWAL",
5484
+ "resGetWAL",
5485
+ "resDelWAL",
5486
+ "updateMeta"
5487
+ ],
5488
+ eventTypes: ["updateMeta"],
5489
+ ...gestalt
5490
+ };
5491
+ }
5492
+ function buildReqChat(sthis, auth, conn, message, targets) {
5493
+ return {
5494
+ tid: sthis.nextId().str,
5495
+ type: "reqChat",
5496
+ version: VERSION,
5497
+ auth,
5498
+ conn,
5499
+ message,
5500
+ targets: targets ?? []
5501
+ };
5502
+ }
5503
+ function buildResChat(req, conn, message, targets, auth) {
5504
+ return {
5505
+ ...req,
5506
+ auth: auth || req.auth,
5507
+ conn: conn || req.conn,
5508
+ message: message || req.message,
5509
+ targets: targets || req.targets,
5510
+ type: "resChat",
5511
+ version: VERSION
5512
+ };
5513
+ }
5514
+ function MsgIsReqChat(msg) {
5515
+ return msg.type === "reqChat";
5516
+ }
5517
+ function MsgIsResChat(msg) {
5518
+ return msg.type === "resChat";
5519
+ }
5520
+ function MsgIsReqGestalt(msg) {
5521
+ return msg.type === "reqGestalt";
5522
+ }
5523
+ function buildReqGestalt(sthis, auth, gestalt, publish) {
5524
+ return {
5525
+ tid: sthis.nextId().str,
5526
+ auth,
5527
+ type: "reqGestalt",
5528
+ version: VERSION,
5529
+ gestalt,
5530
+ publish
5531
+ };
5532
+ }
5533
+ function buildResGestalt(req, gestalt, auth) {
5534
+ return {
5535
+ tid: req.tid,
5536
+ auth: auth || req.auth,
5537
+ type: "resGestalt",
5538
+ version: VERSION,
5539
+ gestalt
5540
+ };
5541
+ }
5542
+ function MsgIsResGestalt(msg) {
5543
+ return msg.type === "resGestalt";
5544
+ }
5545
+ function buildReqOpen(sthis, auth, conn) {
5546
+ return {
5547
+ tid: sthis.nextId().str,
5548
+ auth,
5549
+ type: "reqOpen",
5550
+ version: VERSION,
5551
+ conn: {
5552
+ ...conn,
5553
+ reqId: conn.reqId || sthis.nextId().str
5554
+ }
5555
+ };
5556
+ }
5557
+ function MsgIsReqOpen(imsg) {
5558
+ const msg = imsg;
5559
+ return msg.type === "reqOpen" && !!msg.conn && !!msg.conn.reqId;
5560
+ }
5561
+ function MsgIsWithConn(msg) {
5562
+ const mwc = msg.conn;
5563
+ return mwc && !!mwc.reqId && !!mwc.resId;
5564
+ }
5565
+ function MsgIsWithConnAuth(msg) {
5566
+ return MsgIsWithConn(msg) && !!msg.auth && typeof msg.auth.type === "string";
5567
+ }
5568
+ function MsgIsConnected(msg, qsid) {
5569
+ return MsgIsWithConn(msg) && msg.conn.reqId === qsid.reqId && msg.conn.resId === qsid.resId;
5570
+ }
5571
+ function buildResOpen(sthis, req, resStreamId) {
5572
+ if (!(req.conn && req.conn.reqId)) {
5573
+ throw new Error("req.conn.reqId is required");
5574
+ }
5575
+ return {
5576
+ ...req,
5577
+ type: "resOpen",
5578
+ conn: {
5579
+ ...req.conn,
5580
+ resId: req.conn.resId || resStreamId || sthis.nextId().str
5581
+ }
5582
+ };
5583
+ }
5584
+ function MsgIsResOpen(msg) {
5585
+ return msg.type === "resOpen";
5586
+ }
5587
+ function MsgIsReqClose(msg) {
5588
+ return msg.type === "reqClose" && MsgIsWithConn(msg);
5589
+ }
5590
+ function MsgIsResClose(msg) {
5591
+ return msg.type === "resClose" && MsgIsWithConn(msg);
5592
+ }
5593
+ function buildResClose(req, conn) {
5594
+ return {
5595
+ ...req,
5596
+ type: "resClose",
5597
+ conn
5598
+ };
5599
+ }
5600
+ function buildReqClose(sthis, auth, conn) {
5601
+ return {
5602
+ tid: sthis.nextId().str,
5603
+ auth,
5604
+ type: "reqClose",
5605
+ version: VERSION,
5606
+ conn
5607
+ };
5608
+ }
5609
+ function buildErrorMsg(msgCtx, base, error, body, stack) {
5610
+ if (!stack && msgCtx.sthis.env.get("FP_STACK")) {
5611
+ stack = error.stack?.split("\n");
5612
+ }
5613
+ const msg = {
5614
+ auth: base.auth || { type: "error" },
5615
+ src: base,
5616
+ type: "error",
5617
+ tid: base.tid || "internal",
5618
+ message: error.message,
5619
+ version: VERSION,
5620
+ body,
5621
+ stack
5622
+ };
5623
+ msgCtx.logger.Any("ErrorMsg", msg);
5624
+ return msg;
5625
+ }
5626
+ function MsgIsTenantLedger(msg) {
5627
+ if (MsgIsWithConnAuth(msg)) {
5628
+ const t = msg.tenant;
5629
+ return !!t && !!t.tenant && !!t.ledger;
5630
+ }
5631
+ return false;
5632
+ }
5633
+ function buildReqSignedUrl(sthis, type, rparam, gwCtx) {
5634
+ return {
5635
+ tid: sthis.nextId().str,
5636
+ type,
5637
+ auth: rparam.auth,
5638
+ methodParams: rparam.methodParam,
5639
+ version: VERSION,
5640
+ ...gwCtx,
5641
+ params: rparam.params
5642
+ };
5643
+ }
5644
+ function resAuth(msg) {
5645
+ return msg.auth ? Promise.resolve(msg.auth) : Promise.reject(new Error("No Auth"));
5646
+ }
5647
+ async function buildRes(methodParams, type, msgCtx, req, ctx) {
5648
+ const psm = {
5649
+ type: "reqSignedUrl",
5650
+ auth: await resAuth(req),
5651
+ version: req.version,
5652
+ methodParams,
5653
+ params: {
5654
+ ...req.params
5655
+ },
5656
+ conn: req.conn,
5657
+ tenant: req.tenant,
5658
+ tid: req.tid
5659
+ };
5660
+ const rSignedUrl = await ctx.calculatePreSignedUrl(msgCtx, psm);
5661
+ if (rSignedUrl.isErr()) {
5662
+ return buildErrorMsg(msgCtx, req, rSignedUrl.Err());
5663
+ }
5664
+ return {
5665
+ ...req,
5666
+ params: psm.params,
5667
+ methodParams,
5668
+ type,
5669
+ signedUrl: rSignedUrl.Ok().toString()
5670
+ };
5671
+ }
5672
+
5673
+ // src/protocols/cloud/msger.ts
5674
+ import { BuildURI as BuildURI3, Result as Result15, runtimeFn as runtimeFn4, URI as URI15 } from "@adviser/cement";
5675
+
5676
+ // src/protocols/cloud/http-connection.ts
5677
+ import { HttpHeader, Result as Result13, exception2Result as exception2Result6 } from "@adviser/cement";
5678
+
5679
+ // src/protocols/cloud/msg-raw-connection-base.ts
5680
+ var MsgRawConnectionBase = class {
5681
+ constructor(sthis, exGestalt) {
5682
+ this.onErrorFns = /* @__PURE__ */ new Map();
5683
+ this.sthis = sthis;
5684
+ this.exchangedGestalt = exGestalt;
5685
+ }
5686
+ onError(fn) {
5687
+ const key = this.sthis.nextId().str;
5688
+ this.onErrorFns.set(key, fn);
5689
+ return () => this.onErrorFns.delete(key);
5690
+ }
5691
+ buildErrorMsg(msgCtx, msg, err) {
5692
+ const rmsg = Array.from(this.onErrorFns.values()).reduce((msg2, fn) => {
5693
+ return fn(msg2, err);
5694
+ }, msg);
5695
+ const emsg = buildErrorMsg(msgCtx, rmsg, err);
5696
+ msgCtx.logger.Error().Err(err).Any("msg", rmsg).Msg("connection error");
5697
+ return emsg;
5698
+ }
5699
+ };
5700
+
5701
+ // src/protocols/cloud/http-connection.ts
5702
+ function toHttpProtocol(uri) {
5703
+ const protocol = (uri.getParam("protocol") ?? uri.protocol).replace(/:$/, "");
5704
+ const toFix = uri.build();
5705
+ switch (protocol) {
5706
+ case "ws":
5707
+ case "http":
5708
+ toFix.protocol("http");
5709
+ break;
5710
+ case "https":
5711
+ case "wss":
5712
+ default:
5713
+ toFix.protocol("https");
5714
+ break;
5715
+ }
5716
+ return toFix.URI();
5717
+ }
5718
+ function ensurePath(uri, fp) {
5719
+ const path = uri.pathname.replace(/\/$/, "").replace(/^\//, "");
5720
+ const buri = uri.build();
5721
+ if (path === "") {
5722
+ buri.appendRelative(fp);
5723
+ }
5724
+ return buri.toString();
5725
+ }
5726
+ var HttpConnection = class extends MsgRawConnectionBase {
5727
+ constructor(sthis, uris, msgP, exGestalt) {
5728
+ super(sthis, exGestalt);
5729
+ this.#onMsg = /* @__PURE__ */ new Map();
5730
+ this.activeBinds = /* @__PURE__ */ new Map();
5731
+ this.logger = ensureLogger(sthis, "HttpConnection");
5732
+ this.baseURIs = uris.map((uri) => ({
5733
+ in: uri,
5734
+ cleaned: toHttpProtocol(uri)
5735
+ }));
5736
+ this.msgP = msgP;
5737
+ }
5738
+ #onMsg;
5739
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5740
+ send(_msg) {
5741
+ throw new Error("Method not implemented.");
5742
+ }
5743
+ async start() {
5744
+ return Result13.Ok(void 0);
5745
+ }
5746
+ async close() {
5747
+ await Promise.all(Array.from(this.activeBinds.values()).map((state) => state.controller?.close()));
5748
+ this.#onMsg.clear();
5749
+ return Result13.Ok(void 0);
5750
+ }
5751
+ toMsg(msg) {
5752
+ this.#onMsg.forEach((fn) => fn(msg));
5753
+ return msg;
5754
+ }
5755
+ onMsg(fn) {
5756
+ const key = this.sthis.nextId().str;
5757
+ this.#onMsg.set(key, fn);
5758
+ return () => this.#onMsg.delete(key);
5759
+ }
5760
+ #poll(state) {
5761
+ this.request(state.bind.msg, state.bind.opts).then((msg) => {
5762
+ try {
5763
+ state.controller?.enqueue(msg);
5764
+ if (MsgIsError(msg)) {
5765
+ state.controller?.close();
5766
+ } else {
5767
+ state.timeout = setTimeout(() => this.#poll(state), state.bind.opts.pollInterval ?? 1e3);
5768
+ }
5769
+ } catch (err) {
5770
+ state.controller?.error(err);
5771
+ state.controller?.close();
5772
+ }
5773
+ }).catch((err) => {
5774
+ state.controller?.error(err);
5775
+ });
5776
+ }
5777
+ bind(req, opts) {
5778
+ const state = {
5779
+ id: this.sthis.nextId().str,
5780
+ bind: {
5781
+ msg: req,
5782
+ opts
5783
+ }
5784
+ };
5785
+ this.activeBinds.set(state.id, state);
5786
+ return new ReadableStream({
5787
+ cancel: () => {
5788
+ clearTimeout(state.timeout);
5789
+ this.activeBinds.delete(state.id);
5790
+ },
5791
+ start: (controller) => {
5792
+ state.controller = controller;
5793
+ this.#poll(state);
5794
+ }
5795
+ });
5796
+ }
5797
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5798
+ async request(req, _opts) {
5799
+ const headers = HttpHeader.from();
5800
+ headers.Set("Content-Type", this.msgP.mime);
5801
+ headers.Set("Accept", this.msgP.mime);
5802
+ const rReqBody = exception2Result6(() => this.msgP.ende.encode(req));
5803
+ if (rReqBody.isErr()) {
5804
+ return this.toMsg(
5805
+ buildErrorMsg(this, req, this.logger.Error().Err(rReqBody.Err()).Any("req", req).Msg("encode error").AsError())
5806
+ );
5807
+ }
5808
+ headers.Set("Content-Length", rReqBody.Ok().byteLength.toString());
5809
+ const url = selectRandom(this.baseURIs);
5810
+ this.logger.Debug().Any(url).Any("body", req).Msg("request");
5811
+ const rRes = await exception2Result6(
5812
+ () => timeout(
5813
+ this.msgP.timeout,
5814
+ fetch(ensurePath(url.cleaned, "fp"), {
5815
+ method: "PUT",
5816
+ headers: headers.AsHeaderInit(),
5817
+ body: rReqBody.Ok()
5818
+ })
5819
+ )
5820
+ );
5821
+ this.logger.Debug().Any(url).Any("body", rRes).Msg("response");
5822
+ if (rRes.isErr()) {
5823
+ return this.toMsg(buildErrorMsg(this, req, this.logger.Error().Err(rRes).Any(url).Msg("fetch error").AsError()));
5824
+ }
5825
+ const res = rRes.Ok();
5826
+ if (!res.ok) {
5827
+ const data2 = new Uint8Array(await res.arrayBuffer());
5828
+ const ret2 = await exception2Result6(async () => this.msgP.ende.decode(data2));
5829
+ if (ret2.isErr() || !MsgIsError(ret2.Ok())) {
5830
+ return this.toMsg(
5831
+ buildErrorMsg(
5832
+ this,
5833
+ req,
5834
+ this.logger.Error().Any(url).Str("status", res.status.toString()).Str("statusText", res.statusText).Msg("HTTP Error").AsError(),
5835
+ await res.text()
5836
+ )
5837
+ );
5838
+ }
5839
+ return this.toMsg(ret2.Ok());
5840
+ }
5841
+ const data = new Uint8Array(await res.arrayBuffer());
5842
+ const ret = await exception2Result6(async () => this.msgP.ende.decode(data));
5843
+ if (ret.isErr()) {
5844
+ return this.toMsg(
5845
+ buildErrorMsg(this, req, this.logger.Error().Err(ret.Err()).Msg("decode error").AsError(), this.sthis.txt.decode(data))
5846
+ );
5847
+ }
5848
+ return this.toMsg(ret.Ok());
5849
+ }
5850
+ // toOnMessage<T extends MsgBase>(msg: WithErrorMsg<T>): Result<WithErrorMsg<T>> {
5851
+ // this.mec.msgFn?.(msg as unknown as MessageEvent<MsgBase>);
5852
+ // return Result.Ok(msg);
5853
+ // }
5854
+ };
5855
+
5856
+ // src/protocols/cloud/ws-connection.ts
5857
+ import { exception2Result as exception2Result7, Future as Future3, Result as Result14 } from "@adviser/cement";
5858
+ var WSConnection = class extends MsgRawConnectionBase {
5859
+ constructor(sthis, ws, msgP, exGestalt) {
5860
+ super(sthis, exGestalt);
5861
+ // readonly baseURI: URI;
5862
+ this.#onMsg = /* @__PURE__ */ new Map();
5863
+ this.#onClose = /* @__PURE__ */ new Map();
5864
+ this.waitForTid = /* @__PURE__ */ new Map();
5865
+ this.opened = false;
5866
+ this.#wsOnMessage = async (event) => {
5867
+ const rMsg = await exception2Result7(() => this.msgP.ende.decode(event.data));
5868
+ if (rMsg.isErr()) {
5869
+ this.logger.Error().Err(rMsg).Any(event.data).Msg("Invalid message");
5870
+ return;
5871
+ }
5872
+ const msg = rMsg.Ok();
5873
+ const waitFor = this.waitForTid.get(msg.tid);
5874
+ Array.from(this.#onMsg.values()).forEach((cb) => {
5875
+ cb(msg);
5876
+ });
5877
+ if (waitFor) {
5878
+ if (MsgIsError(msg)) {
5879
+ this.waitForTid.delete(msg.tid);
5880
+ waitFor.future.resolve(msg);
5881
+ } else if (waitFor.waitFor(msg)) {
5882
+ this.waitForTid.delete(msg.tid);
5883
+ waitFor.future.resolve(msg);
5884
+ } else {
5885
+ this.waitForTid.delete(msg.tid);
5886
+ waitFor.future.resolve(msg);
5887
+ }
5888
+ }
5889
+ };
5890
+ this.activeBinds = /* @__PURE__ */ new Map();
5891
+ this.id = sthis.nextId().str;
5892
+ this.logger = ensureLogger(sthis, "WSConnection");
5893
+ this.msgP = msgP;
5894
+ this.ws = ws;
5895
+ }
5896
+ #onMsg;
5897
+ #onClose;
5898
+ async start() {
5899
+ const onOpenFuture = new Future3();
5900
+ const timer = setTimeout(() => {
5901
+ const err = this.logger.Error().Dur("timeout", this.msgP.timeout).Msg("Timeout").AsError();
5902
+ this.toMsg(buildErrorMsg(this, {}, err));
5903
+ onOpenFuture.resolve(Result14.Err(err));
5904
+ }, this.msgP.timeout);
5905
+ this.ws.onopen = () => {
5906
+ onOpenFuture.resolve(Result14.Ok(void 0));
5907
+ this.opened = true;
5908
+ };
5909
+ this.ws.onerror = (ierr) => {
5910
+ const err = this.logger.Error().Err(ierr).Msg("WS Error").AsError();
5911
+ onOpenFuture.resolve(Result14.Err(err));
5912
+ const res = this.buildErrorMsg(this, {}, err);
5913
+ this.toMsg(res);
5914
+ };
5915
+ this.ws.onmessage = (evt) => {
5916
+ if (!this.opened) {
5917
+ this.toMsg(buildErrorMsg(this, {}, this.logger.Error().Msg("Received message before onOpen").AsError()));
5918
+ }
5919
+ this.#wsOnMessage(evt);
5920
+ };
5921
+ this.ws.onclose = () => {
5922
+ this.opened = false;
5923
+ this.close().catch((ierr) => {
5924
+ const err = this.logger.Error().Err(ierr).Msg("close error").AsError();
5925
+ onOpenFuture.resolve(Result14.Err(err));
5926
+ this.toMsg(buildErrorMsg(this, { tid: "internal" }, err));
5927
+ });
5928
+ };
5929
+ const rOpen = await onOpenFuture.asPromise().finally(() => {
5930
+ clearTimeout(timer);
5931
+ });
5932
+ if (rOpen.isErr()) {
5933
+ return rOpen;
5934
+ }
5935
+ return Result14.Ok(void 0);
5936
+ }
5937
+ #wsOnMessage;
5938
+ async close() {
5939
+ this.#onClose.forEach((fn) => fn());
5940
+ this.#onClose.clear();
5941
+ this.#onMsg.clear();
5942
+ this.ws.close();
5943
+ return Result14.Ok(void 0);
5944
+ }
5945
+ toMsg(msg) {
5946
+ this.#onMsg.forEach((fn) => fn(msg));
5947
+ return msg;
5948
+ }
5949
+ send(msg) {
5950
+ this.ws.send(this.msgP.ende.encode(msg));
5951
+ return Promise.resolve(msg);
5952
+ }
5953
+ onMsg(fn) {
5954
+ const key = this.sthis.nextId().str;
5955
+ this.#onMsg.set(key, fn);
5956
+ return () => this.#onMsg.delete(key);
5957
+ }
5958
+ onClose(fn) {
5959
+ const key = this.sthis.nextId().str;
5960
+ this.#onClose.set(key, fn);
5961
+ return () => this.#onClose.delete(key);
5962
+ }
5963
+ bind(req, opts) {
5964
+ const state = {
5965
+ id: this.sthis.nextId().str,
5966
+ bind: {
5967
+ msg: req,
5968
+ opts
5969
+ }
5970
+ // timeout: undefined,
5971
+ // controller: undefined,
5972
+ };
5973
+ this.activeBinds.set(state.id, state);
5974
+ return new ReadableStream({
5975
+ cancel: () => {
5976
+ this.activeBinds.delete(state.id);
5977
+ },
5978
+ start: (controller) => {
5979
+ this.onMsg((msg) => {
5980
+ if (MsgIsError(msg)) {
5981
+ controller.enqueue(msg);
5982
+ return;
5983
+ }
5984
+ if (!MsgIsTid(msg, req.tid)) {
5985
+ return;
5986
+ }
5987
+ if (opts.waitFor && opts.waitFor(msg)) {
5988
+ controller.enqueue(msg);
5989
+ }
5990
+ });
5991
+ this.send(req);
5992
+ const future = new Future3();
5993
+ this.waitForTid.set(req.tid, { tid: req.tid, future, waitFor: opts.waitFor, timeout: opts.timeout });
5994
+ future.asPromise().then((msg) => {
5995
+ if (MsgIsError(msg)) {
5996
+ controller.enqueue(msg);
5997
+ controller.close();
5998
+ }
5999
+ });
6000
+ }
6001
+ });
6002
+ }
6003
+ async request(req, opts) {
6004
+ if (!this.opened) {
6005
+ return buildErrorMsg(this, req, this.logger.Error().Msg("Connection not open").AsError());
6006
+ }
6007
+ const future = new Future3();
6008
+ this.waitForTid.set(req.tid, { tid: req.tid, future, waitFor: opts.waitFor, timeout: opts.timeout });
6009
+ await this.send(req);
6010
+ return future.asPromise();
6011
+ }
6012
+ // toOnMessage<T extends MsgBase>(msg: WithErrorMsg<T>): Result<WithErrorMsg<T>> {
6013
+ // this.mec.msgFn?.(msg as unknown as MessageEvent<MsgBase>);
6014
+ // return Result.Ok(msg);
6015
+ // }
6016
+ };
6017
+
6018
+ // src/protocols/cloud/msger.ts
6019
+ function selectRandom(arr) {
6020
+ return arr[Math.floor(Math.random() * arr.length)];
6021
+ }
6022
+ function timeout(ms, promise) {
6023
+ return new Promise((resolve, reject) => {
6024
+ const timer = setTimeout(() => {
6025
+ reject(new Error(`TIMEOUT after ${ms}ms`));
6026
+ }, ms);
6027
+ promise.then(resolve).catch(reject).finally(() => clearTimeout(timer));
6028
+ });
6029
+ }
6030
+ function jsonEnDe(sthis) {
6031
+ return {
6032
+ encode: (node) => sthis.txt.encode(JSON.stringify(node)),
6033
+ decode: (data) => JSON.parse(sthis.txt.decode(data))
6034
+ };
6035
+ }
6036
+ function defaultMsgParams(sthis, igs) {
6037
+ return {
6038
+ mime: "application/json",
6039
+ ende: jsonEnDe(sthis),
6040
+ timeout: 3e3,
6041
+ protocolCapabilities: ["reqRes", "stream"],
6042
+ ...igs
6043
+ };
6044
+ }
6045
+ async function applyStart(prC) {
6046
+ const rC = await prC;
6047
+ if (rC.isErr()) {
6048
+ return rC;
6049
+ }
6050
+ const c = rC.Ok();
6051
+ const r = await c.start();
6052
+ if (r.isErr()) {
6053
+ return Result15.Err(r.Err());
6054
+ }
6055
+ return rC;
6056
+ }
6057
+ async function authTypeFromUri(logger, curi) {
6058
+ const uri = URI15.from(curi);
6059
+ const authJWK = uri.getParam("authJWK");
6060
+ if (!authJWK) {
6061
+ return logger.Error().Url(uri).Msg("authJWK is required").ResultError();
6062
+ }
6063
+ return Result15.Ok({
6064
+ type: "fp-cloud-jwk",
6065
+ params: {
6066
+ // claim: fpc.Ok().payload,
6067
+ jwk: authJWK
6068
+ }
6069
+ });
6070
+ }
6071
+ var MsgConnected = class _MsgConnected {
6072
+ static async connect(auth, mrc, conn = {}) {
6073
+ if (Result15.Is(mrc)) {
6074
+ if (mrc.isErr()) {
6075
+ return Result15.Err(mrc.Err());
6076
+ }
6077
+ mrc = mrc.Ok();
6078
+ }
6079
+ const res = await mrc.request(buildReqOpen(mrc.sthis, auth, conn), { waitFor: MsgIsResOpen });
6080
+ if (MsgIsError(res) || !MsgIsResOpen(res)) {
6081
+ return mrc.sthis.logger.Error().Err(res).Msg("unexpected response").ResultError();
6082
+ }
6083
+ return Result15.Ok(new _MsgConnected(mrc, res.conn));
6084
+ }
6085
+ constructor(raw2, conn) {
6086
+ this.sthis = raw2.sthis;
6087
+ this.raw = raw2;
6088
+ this.exchangedGestalt = raw2.exchangedGestalt;
6089
+ this.conn = conn;
6090
+ this.activeBinds = raw2.activeBinds;
6091
+ this.id = this.sthis.nextId().str;
6092
+ }
6093
+ attachAuth(auth) {
6094
+ return new MsgConnectedAuth(this, auth);
6095
+ }
6096
+ };
6097
+ var MsgConnectedAuth = class {
6098
+ constructor(conn, authFactory) {
6099
+ this.id = conn.id;
6100
+ this.raw = conn.raw;
6101
+ this.conn = conn.conn;
6102
+ this.sthis = conn.sthis;
6103
+ this.authFactory = authFactory;
6104
+ this.exchangedGestalt = conn.exchangedGestalt;
6105
+ this.activeBinds = conn.activeBinds;
6106
+ }
6107
+ bind(req, opts) {
6108
+ const stream = this.raw.bind({ ...req, conn: req.conn || this.conn }, opts);
6109
+ const ts = new TransformStream({
6110
+ transform: (chunk, controller) => {
6111
+ if (!MsgIsTid(chunk, req.tid)) {
6112
+ return;
6113
+ }
6114
+ if (MsgIsConnected(chunk, this.conn)) {
6115
+ if (opts.waitFor?.(chunk) || MsgIsError(chunk)) {
6116
+ controller.enqueue(chunk);
6117
+ }
6118
+ }
6119
+ }
6120
+ });
6121
+ stream.pipeThrough(ts);
6122
+ return ts.readable;
6123
+ }
6124
+ authType() {
6125
+ return this.authFactory();
6126
+ }
6127
+ msgConnAuth() {
6128
+ return this.authType().then((r) => {
6129
+ if (r.isErr()) {
6130
+ return Result15.Err(r);
6131
+ }
6132
+ return Result15.Ok({ conn: this.conn, auth: r.Ok() });
6133
+ });
6134
+ }
6135
+ request(req, opts) {
6136
+ return this.raw.request({ ...req, conn: req.conn || this.conn }, opts);
6137
+ }
6138
+ send(msg) {
6139
+ return this.raw.send({ ...msg, conn: msg.conn || this.conn });
6140
+ }
6141
+ start() {
6142
+ return this.raw.start();
6143
+ }
6144
+ async close(t) {
6145
+ await this.request(buildReqClose(this.sthis, t.auth, this.conn), { waitFor: MsgIsResClose });
6146
+ return await this.raw.close(t);
6147
+ }
6148
+ onMsg(msgFn) {
6149
+ return this.raw.onMsg((msg) => {
6150
+ if (MsgIsConnected(msg, this.conn)) {
6151
+ msgFn(msg);
6152
+ }
6153
+ });
6154
+ }
6155
+ };
6156
+ function initialFPUri(curl) {
6157
+ let gestaltUrl = URI15.from(curl);
6158
+ if (["", "/"].includes(gestaltUrl.pathname)) {
6159
+ gestaltUrl = gestaltUrl.build().appendRelative("/fp").URI();
6160
+ }
6161
+ return gestaltUrl;
6162
+ }
6163
+ var Msger = class _Msger {
6164
+ static async openHttp(sthis, urls, msgP, exGestalt) {
6165
+ return Result15.Ok(new HttpConnection(sthis, urls, msgP, exGestalt));
6166
+ }
6167
+ static async openWS(sthis, url, msgP, exGestalt) {
6168
+ let ws;
6169
+ url = url.build().setParam("random", sthis.nextId().str).URI();
6170
+ const wsUrl = ensurePath(url, "ws");
6171
+ if (runtimeFn4().isNodeIsh) {
6172
+ const { WebSocket: WebSocket2 } = await import("ws");
6173
+ ws = new WebSocket2(wsUrl);
6174
+ } else {
6175
+ ws = new WebSocket(wsUrl);
6176
+ }
6177
+ return Result15.Ok(new WSConnection(sthis, ws, msgP, exGestalt));
6178
+ }
6179
+ static async open(sthis, auth, curl, imsgP = {}) {
6180
+ const jsMsgP = defaultMsgParams(sthis, { ...imsgP, mime: "application/json", ende: jsonEnDe(sthis) });
6181
+ const gestaltUrl = initialFPUri(curl);
6182
+ const gs = defaultGestalt(defaultMsgParams(sthis, imsgP), { id: "FP-Universal-Client" });
6183
+ const rHC = await _Msger.openHttp(sthis, [gestaltUrl], jsMsgP, { my: gs, remote: gs });
6184
+ if (rHC.isErr()) {
6185
+ return rHC;
6186
+ }
6187
+ const hc = rHC.Ok();
6188
+ const resGestalt = await hc.request(buildReqGestalt(sthis, auth, gs), {
6189
+ waitFor: MsgIsResGestalt
6190
+ });
6191
+ if (!MsgIsResGestalt(resGestalt)) {
6192
+ return sthis.logger.Error().Any({ resGestalt }).Msg("should be ResGestalt").ResultError();
6193
+ }
6194
+ await hc.close(
6195
+ resGestalt
6196
+ /* as MsgWithConnAuth */
6197
+ );
6198
+ const exGt = { my: gs, remote: resGestalt.gestalt };
6199
+ const msgP = defaultMsgParams(sthis, imsgP);
6200
+ if (exGt.remote.protocolCapabilities.includes("reqRes") && !exGt.remote.protocolCapabilities.includes("stream")) {
6201
+ return applyStart(
6202
+ _Msger.openHttp(
6203
+ sthis,
6204
+ exGt.remote.httpEndpoints.map((i) => BuildURI3.from(curl).resolve(i).URI()),
6205
+ msgP,
6206
+ exGt
6207
+ )
6208
+ );
6209
+ }
6210
+ const wsUrl = BuildURI3.from(gestaltUrl).resolve(selectRandom(exGt.remote.wsEndpoints)).URI();
6211
+ return applyStart(_Msger.openWS(sthis, wsUrl, msgP, exGt));
6212
+ }
6213
+ static connect(sthis, auth, curl, imsgP = {}, conn = {}) {
6214
+ return _Msger.open(sthis, auth, curl, imsgP).then((srv) => MsgConnected.connect(auth, srv, conn));
6215
+ }
6216
+ constructor() {
6217
+ }
6218
+ };
6219
+
6220
+ // src/protocols/cloud/msg-types-data.ts
6221
+ function buildReqGetData(sthis, sup, ctx) {
6222
+ return buildReqSignedUrl(sthis, "reqGetData", sup, ctx);
6223
+ }
6224
+ function MsgIsReqGetData(msg) {
6225
+ return msg.type === "reqGetData";
6226
+ }
6227
+ function MsgIsResGetData(msg) {
6228
+ return msg.type === "resGetData" && MsgIsTenantLedger(msg);
6229
+ }
6230
+ function buildResGetData(msgCtx, req, ctx) {
6231
+ return buildRes(
6232
+ { method: "GET", store: req.methodParams.store },
6233
+ "resGetData",
6234
+ msgCtx,
6235
+ req,
6236
+ ctx
6237
+ );
6238
+ }
6239
+ function MsgIsReqPutData(msg) {
6240
+ return msg.type === "reqPutData";
6241
+ }
6242
+ function buildReqPutData(sthis, sup, ctx) {
6243
+ return buildReqSignedUrl(sthis, "reqPutData", sup, ctx);
6244
+ }
6245
+ function MsgIsResPutData(msg) {
6246
+ return msg.type === "resPutData";
6247
+ }
6248
+ function buildResPutData(msgCtx, req, ctx) {
6249
+ return buildRes(
6250
+ { method: "PUT", store: req.methodParams.store },
6251
+ "resPutData",
6252
+ msgCtx,
6253
+ req,
6254
+ ctx
6255
+ );
6256
+ }
6257
+ function MsgIsReqDelData(msg) {
6258
+ return msg.type === "reqDelData";
6259
+ }
6260
+ function buildReqDelData(sthis, sup, ctx) {
6261
+ return buildReqSignedUrl(sthis, "reqDelData", sup, ctx);
6262
+ }
6263
+ function MsgIsResDelData(msg) {
6264
+ return msg.type === "resDelData";
6265
+ }
6266
+ function buildResDelData(msgCtx, req, ctx) {
6267
+ return buildRes(
6268
+ { method: "DELETE", store: req.methodParams.store },
6269
+ "resDelData",
6270
+ msgCtx,
6271
+ req,
6272
+ ctx
6273
+ );
6274
+ }
6275
+
6276
+ // src/protocols/cloud/msg-types-meta.ts
6277
+ import { VERSION as VERSION2 } from "@adviser/cement";
6278
+ function buildReqPutMeta(sthis, auth, signedUrlParams, meta, gwCtx) {
6279
+ return {
6280
+ auth,
6281
+ tid: sthis.nextId().str,
6282
+ type: "reqPutMeta",
6283
+ ...gwCtx,
6284
+ version: VERSION2,
6285
+ methodParams: {
6286
+ method: "PUT",
6287
+ store: "meta"
6288
+ },
6289
+ params: signedUrlParams,
6290
+ meta
6291
+ };
6292
+ }
6293
+ function MsgIsReqPutMeta(msg) {
6294
+ return msg.type === "reqPutMeta";
6295
+ }
6296
+ function buildResPutMeta(_msgCtx, req, meta, signedUrl) {
6297
+ return {
6298
+ meta,
6299
+ tid: req.tid,
6300
+ conn: req.conn,
6301
+ auth: req.auth,
6302
+ methodParams: req.methodParams,
6303
+ params: req.params,
6304
+ tenant: req.tenant,
6305
+ type: "resPutMeta",
6306
+ signedUrl,
6307
+ version: VERSION2
6308
+ };
6309
+ }
6310
+ function MsgIsResPutMeta(qs) {
6311
+ return qs.type === "resPutMeta";
6312
+ }
6313
+ function MsgIsBindGetMeta(msg) {
6314
+ return msg.type === "bindGetMeta";
6315
+ }
6316
+ function buildBindGetMeta(sthis, auth, params, gwCtx) {
6317
+ return {
6318
+ auth,
6319
+ tid: sthis.nextId().str,
6320
+ ...gwCtx,
6321
+ type: "bindGetMeta",
6322
+ version: VERSION2,
6323
+ params
6324
+ };
6325
+ }
6326
+ function buildEventGetMeta(_msgCtx, req, meta, gwCtx, signedUrl) {
6327
+ return {
6328
+ conn: gwCtx.conn,
6329
+ tenant: req.tenant,
6330
+ auth: req.auth,
6331
+ tid: req.tid,
6332
+ meta,
6333
+ signedUrl,
6334
+ type: "eventGetMeta",
6335
+ params: req.params,
6336
+ methodParams: { method: "GET", store: "meta" },
6337
+ version: VERSION2
6338
+ };
6339
+ }
6340
+ function MsgIsEventGetMeta(qs) {
6341
+ return qs.type === "eventGetMeta";
6342
+ }
6343
+ function buildReqDelMeta(sthis, auth, params, gwCtx, meta) {
6344
+ return {
6345
+ auth,
6346
+ tid: sthis.nextId().str,
6347
+ tenant: gwCtx.tenant,
6348
+ conn: gwCtx.conn,
6349
+ params,
6350
+ meta,
6351
+ type: "reqDelMeta",
6352
+ version: VERSION2
6353
+ // params: signedUrlParams,
6354
+ };
6355
+ }
6356
+ function MsgIsReqDelMeta(msg) {
6357
+ return msg.type === "reqDelMeta";
6358
+ }
6359
+ function buildResDelMeta(req, params, signedUrl) {
6360
+ return {
6361
+ auth: req.auth,
6362
+ methodParams: { method: "DELETE", store: "meta" },
6363
+ params,
6364
+ signedUrl,
6365
+ tid: req.tid,
6366
+ conn: req.conn,
6367
+ tenant: req.tenant,
6368
+ type: "resDelMeta",
6369
+ // key: req.key,
6370
+ version: VERSION2
6371
+ };
6372
+ }
6373
+ function MsgIsResDelMeta(qs) {
6374
+ return qs.type === "resDelMeta";
6375
+ }
6376
+
6377
+ // src/runtime/meta-key-hack.ts
6378
+ import { exception2Result as exception2Result8, Result as Result16 } from "@adviser/cement";
6379
+ function fromV1toV2SerializedMetaKey(v1s, keys = []) {
6380
+ const res = v1s.reduce(
6381
+ (acc, v1) => {
6382
+ const keys2 = [];
6383
+ if (v1.key) {
6384
+ if (typeof v1.key === "string") {
6385
+ acc.keys.add(v1.key);
6386
+ } else {
6387
+ keys2.push(...v1.key);
6388
+ }
6389
+ }
6390
+ if (v1.keys) {
6391
+ keys2.push(...v1.keys);
6392
+ }
6393
+ for (const key of keys2) {
6394
+ acc.keys.add(key);
6395
+ }
6396
+ if (typeof v1.cid === "string" && (!v1.data || typeof v1.data === "string") && (!v1.parents || Array.isArray(v1.parents))) {
6397
+ acc.metas.set(v1.cid, {
6398
+ data: v1.data ?? "",
6399
+ parents: v1.parents ?? [],
6400
+ cid: v1.cid
6401
+ });
6402
+ }
6403
+ return acc;
6404
+ },
6405
+ {
6406
+ metas: /* @__PURE__ */ new Map(),
6407
+ keys: new Set(keys)
6408
+ }
6409
+ );
6410
+ return {
6411
+ metas: Array.from(res.metas.values()),
6412
+ keys: Array.from(res.keys)
6413
+ };
6414
+ }
6415
+ function isV2SerializedMetaKey(or) {
6416
+ const my = or;
6417
+ return my !== null && (!my.keys || Array.isArray(my.keys)) && (!my.metas || Array.isArray(my.metas));
6418
+ }
6419
+ function toV2SerializedMetaKey(or) {
6420
+ if (Array.isArray(or)) {
6421
+ return fromV1toV2SerializedMetaKey(or);
6422
+ }
6423
+ if (isV2SerializedMetaKey(or)) {
6424
+ return fromV1toV2SerializedMetaKey(or.metas ?? [], or.keys ?? []);
6425
+ }
6426
+ throw new Error("not a valid serialized meta key");
6427
+ }
6428
+ async function V2SerializedMetaKeyExtractKey(ctx, v2) {
6429
+ const kb = await ctx.loader.keyBag();
6430
+ if (!kb) {
6431
+ return Promise.resolve(Result16.Err(new Error("missing keybag")));
6432
+ }
6433
+ const dataUrl = await ctx.loader.attachedStores.local().active.car.url();
6434
+ const keyName = dataUrl.getParam(PARAM.STORE_KEY);
6435
+ if (!keyName) {
6436
+ ctx.loader.sthis.logger.Warn().Url(dataUrl).Msg("missing store key");
6437
+ } else {
6438
+ const rKey = await kb.getNamedKey(keyName);
6439
+ if (rKey.isErr()) {
6440
+ ctx.loader.sthis.logger.Warn().Str("keyName", keyName).Msg("did not found a extractable key");
6441
+ } else {
6442
+ for (const keyStr of v2.keys) {
6443
+ const res = await rKey.Ok().upsert(keyStr, false);
6444
+ if (res.isErr()) {
6445
+ ctx.loader.sthis.logger.Warn().Str("keyStr", keyStr).Msg("failed to upsert key");
6446
+ }
6447
+ }
6448
+ }
6449
+ }
6450
+ return Promise.resolve(Result16.Ok(v2.metas));
6451
+ }
6452
+ async function decodeAsToSerializedMeta(ctx, raw2) {
6453
+ const rJsObj = exception2Result8(() => JSON.parse(ctx.loader.sthis.txt.decode(raw2)));
6454
+ if (rJsObj.isErr()) {
6455
+ return Result16.Err(rJsObj);
6456
+ }
6457
+ const v2 = toV2SerializedMetaKey(rJsObj.unwrap());
6458
+ const metas = await V2SerializedMetaKeyExtractKey(ctx, v2);
6459
+ if (metas.isErr()) {
6460
+ return Result16.Err(metas);
6461
+ }
6462
+ return Result16.Ok({
6463
+ metas: metas.Ok(),
6464
+ keys: v2.keys
6465
+ });
6466
+ }
6467
+ function addKeyToDbMetaDecoder(ctx) {
6468
+ const lastDecodedMetas = ctx.lastDecodedMetas ?? [];
6469
+ return {
6470
+ ...ctx,
6471
+ lastDecodedMetas,
6472
+ decoder: {
6473
+ meta: async (sthis, raw2) => {
6474
+ const r = await decodeAsToSerializedMeta(ctx, raw2);
6475
+ if (r.isErr()) {
6476
+ return Promise.resolve(Result16.Err(r));
6477
+ }
6478
+ if (lastDecodedMetas.length > 2) {
6479
+ lastDecodedMetas.shift();
6480
+ }
6481
+ lastDecodedMetas.push(r.Ok());
6482
+ return Promise.resolve(Result16.Ok(r.Ok().metas));
6483
+ }
6484
+ }
6485
+ };
6486
+ }
6487
+ async function wrapEncode(ctx, payload, fn) {
6488
+ const carStore = ctx.loader.attachedStores.local().active.car;
6489
+ const kb = await ctx.loader.keyBag();
6490
+ if (!kb) {
6491
+ return Promise.resolve(Result16.Err(new Error("missing keybag")));
6492
+ }
6493
+ const keyName = carStore.url().getParam(PARAM.STORE_KEY) ?? "";
6494
+ const rKex = await kb.getNamedKey(keyName);
6495
+ if (rKex.isErr()) {
6496
+ return Promise.resolve(Result16.Err(rKex.Err()));
6497
+ }
6498
+ const keyMaterials = await rKex.Ok().asKeysItem().then((i) => Object.values(i.keys).map((i2) => i2.key));
6499
+ return Promise.resolve(Result16.Ok(fn(payload, keyMaterials)));
6500
+ }
6501
+ function encodeAsV1SerializedMetaKey(ctx, payload) {
6502
+ return wrapEncode(ctx, payload, (payload2, keyM) => payload2.map((p) => ({ ...p, key: keyM })));
6503
+ }
6504
+ function encodeAsV2SerializedMetaKey(ctx, payload) {
6505
+ return wrapEncode(
6506
+ ctx,
6507
+ payload,
6508
+ (payload2, keyM) => ({
6509
+ metas: payload2,
6510
+ keys: keyM
6511
+ })
6512
+ );
6513
+ }
6514
+ function addKeyToDbMetaEncoder(ctx, version) {
6515
+ return {
6516
+ ...ctx,
6517
+ encoder: {
6518
+ meta: async (sthis, payload) => {
6519
+ let obj;
6520
+ switch (version) {
6521
+ case "v1":
6522
+ obj = await encodeAsV1SerializedMetaKey(ctx, payload);
6523
+ break;
6524
+ case "v2":
6525
+ obj = await encodeAsV2SerializedMetaKey(ctx, payload);
6526
+ break;
6527
+ default:
6528
+ return Promise.resolve(Result16.Err(`unknown version:[${version}]`));
6529
+ }
6530
+ if (obj.isErr()) {
6531
+ return Promise.resolve(Result16.Err(obj));
6532
+ }
6533
+ try {
6534
+ return Promise.resolve(Result16.Ok(sthis.txt.encode(JSON.stringify(obj.Ok()))));
6535
+ } catch (e) {
6536
+ return Promise.resolve(Result16.Err(e));
6537
+ }
6538
+ }
6539
+ }
6540
+ };
6541
+ }
6542
+ var AddKeyToDbMetaGateway = class {
6543
+ constructor(gw, version) {
6544
+ // only for tests
6545
+ this.lastDecodedMetas = [];
6546
+ this.sdGw = new DefSerdeGateway(gw);
6547
+ this.version = version;
6548
+ }
6549
+ buildUrl(ctx, baseUrl, key) {
6550
+ return this.sdGw.buildUrl(ctx, baseUrl, key);
6551
+ }
6552
+ start(ctx, baseUrl) {
6553
+ return this.sdGw.start(ctx, baseUrl);
6554
+ }
6555
+ close(ctx, baseUrl) {
6556
+ return this.sdGw.close(ctx, baseUrl);
6557
+ }
6558
+ async put(ctx, url, body) {
6559
+ return this.sdGw.put(addKeyToDbMetaEncoder(ctx, this.version), url, body);
6560
+ }
6561
+ async get(ctx, url) {
6562
+ return this.sdGw.get(addKeyToDbMetaDecoder({ ...ctx, lastDecodedMetas: this.lastDecodedMetas }), url);
6563
+ }
6564
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6565
+ delete(ctx, url, loader) {
6566
+ return this.sdGw.delete(ctx, url);
6567
+ }
6568
+ subscribe(ctx, url, callback) {
6569
+ return this.sdGw.subscribe(addKeyToDbMetaDecoder({ ...ctx, lastDecodedMetas: this.lastDecodedMetas }), url, callback);
6570
+ }
6571
+ getPlain(ctx, url, key) {
6572
+ return this.sdGw.getPlain(ctx, url, key);
6573
+ }
6574
+ destroy(ctx, baseUrl) {
6575
+ return this.sdGw.destroy(ctx, baseUrl);
6576
+ }
6577
+ };
6578
+
6579
+ // src/runtime/gateways/cloud/gateway.ts
6580
+ var VERSION3 = "v0.1-fp-cloud";
6581
+ var BaseGateway = class {
6582
+ constructor(sthis, module) {
6583
+ this.sthis = sthis;
6584
+ this.logger = ensureLogger(sthis, module);
6585
+ }
6586
+ async buildReqSignedUrl(type, method, store, uri, conn) {
6587
+ const rParams = uri.getParamsResult({
6588
+ key: param.REQUIRED,
6589
+ store: param.REQUIRED,
6590
+ path: param.OPTIONAL,
6591
+ tenant: param.REQUIRED,
6592
+ name: param.REQUIRED,
6593
+ index: param.OPTIONAL
6594
+ });
6595
+ if (rParams.isErr()) {
6596
+ return buildErrorMsg(this, {}, rParams.Err());
6597
+ }
6598
+ const params = rParams.Ok();
6599
+ if (store !== params.store) {
6600
+ return buildErrorMsg(this, {}, new Error("store mismatch"));
6601
+ }
6602
+ const rAuth = await authTypeFromUri(this.logger, uri);
6603
+ if (rAuth.isErr()) {
6604
+ return buildErrorMsg(this, {}, rAuth.Err());
6605
+ }
6606
+ return {
6607
+ tid: this.sthis.nextId().str,
6608
+ auth: rAuth.Ok(),
6609
+ type,
6610
+ conn: conn.conn.Ok().conn,
6611
+ tenant: {
6612
+ tenant: params.tenant,
6613
+ ledger: params.name
6614
+ },
6615
+ // tenant: conn.tenant,
6616
+ methodParams: {
6617
+ method,
6618
+ store
6619
+ },
6620
+ params: {
6621
+ ...params,
6622
+ key: params.key
6623
+ },
6624
+ version: VERSION3
6625
+ };
6626
+ }
6627
+ async getReqSignedUrl(type, method, store, waitForFn, uri, conn) {
6628
+ const rsu = await this.buildReqSignedUrl(type, method, store, uri, conn);
6629
+ if (MsgIsError(rsu)) {
6630
+ return rsu;
6631
+ }
6632
+ return conn.conn.Ok().request(rsu, { waitFor: waitForFn });
6633
+ }
6634
+ async putObject(uri, uploadUrl, body, conn) {
6635
+ this.logger.Debug().Any("url", { uploadUrl, uri }).Msg("put-fetch-url");
6636
+ const rUpload = await exception2Result9(async () => fetch(uploadUrl, { method: "PUT", body }));
6637
+ if (rUpload.isErr()) {
6638
+ return this.logger.Error().Url(uploadUrl, "uploadUrl").Err(rUpload).Msg("Error in put fetch").ResultError();
6639
+ }
6640
+ if (!rUpload.Ok().ok) {
6641
+ return this.logger.Error().Url(uploadUrl, "uploadUrl").Http(rUpload.Ok()).Msg("Error in put fetch").ResultError();
6642
+ }
6643
+ if (uri.getParam("testMode")) {
6644
+ conn.citem.trackPuts.add(uri.toString());
6645
+ }
6646
+ return Result17.Ok(void 0);
6647
+ }
6648
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6649
+ async getObject(uri, downloadUrl, _conn) {
6650
+ this.logger.Debug().Any("url", { downloadUrl, uri }).Msg("get-fetch-url");
6651
+ const rDownload = await exception2Result9(async () => fetch(downloadUrl.toString(), { method: "GET" }));
6652
+ if (rDownload.isErr()) {
6653
+ return this.logger.Error().Url(downloadUrl, "uploadUrl").Err(rDownload).Msg("Error in get downloadUrl").ResultError();
6654
+ }
6655
+ const download = rDownload.Ok();
6656
+ if (!download.ok) {
6657
+ if (download.status === 404) {
6658
+ return Result17.Err(new NotFoundError("Not found"));
6659
+ }
6660
+ return this.logger.Error().Url(downloadUrl, "uploadUrl").Err(rDownload).Msg("Error in get fetch").ResultError();
6661
+ }
6662
+ return Result17.Ok(to_uint8(await download.arrayBuffer()));
6663
+ }
6664
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6665
+ async delObject(uri, deleteUrl, _conn) {
6666
+ this.logger.Debug().Any("url", { deleteUrl, uri }).Msg("get-fetch-url");
6667
+ const rDelete = await exception2Result9(async () => fetch(deleteUrl.toString(), { method: "DELETE" }));
6668
+ if (rDelete.isErr()) {
6669
+ return this.logger.Error().Url(deleteUrl, "deleteUrl").Err(rDelete).Msg("Error in get deleteURL").ResultError();
6670
+ }
6671
+ const download = rDelete.Ok();
6672
+ if (!download.ok) {
6673
+ if (download.status === 404) {
6674
+ return Result17.Err(new NotFoundError("Not found"));
6675
+ }
6676
+ return this.logger.Error().Url(deleteUrl, "deleteUrl").Err(rDelete).Msg("Error in del fetch").ResultError();
6677
+ }
6678
+ return Result17.Ok(void 0);
6679
+ }
6680
+ };
6681
+ var DataGateway = class extends BaseGateway {
6682
+ constructor(sthis) {
6683
+ super(sthis, "DataGateway");
6684
+ }
6685
+ async get(ctx, uri) {
6686
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6687
+ const rResSignedUrl = await this.getReqSignedUrl("reqGetData", "GET", store, MsgIsResGetData, uri, ctx.conn);
6688
+ if (MsgIsError(rResSignedUrl)) {
6689
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6690
+ }
6691
+ const { signedUrl: downloadUrl } = rResSignedUrl;
6692
+ const r = await fpDeserialize(this.sthis, uri, this.getObject(uri, downloadUrl, ctx.conn));
6693
+ return r;
6694
+ }
6695
+ async put(ctx, uri, data) {
6696
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6697
+ const rResSignedUrl = await this.getReqSignedUrl("reqPutData", "PUT", store, MsgIsResPutData, uri, ctx.conn);
6698
+ if (MsgIsError(rResSignedUrl)) {
6699
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6700
+ }
6701
+ const { signedUrl: uploadUrl } = rResSignedUrl;
6702
+ const rBlob = await fpSerialize(ctx.loader.sthis, data);
6703
+ if (rBlob.isErr()) {
6704
+ return rBlob;
6705
+ }
6706
+ const r = await this.putObject(uri, uploadUrl, rBlob.Ok(), ctx.conn);
6707
+ return r;
6708
+ }
6709
+ async delete(ctx, uri) {
6710
+ const store = coerceFPStoreTypes(uri.getParam("store"));
6711
+ const rResSignedUrl = await this.getReqSignedUrl("reqDelData", "DELETE", store, MsgIsResDelData, uri, ctx.conn);
6712
+ if (MsgIsError(rResSignedUrl)) {
6713
+ return this.logger.Error().Err(rResSignedUrl).Msg("Error in buildResSignedUrl").ResultError();
6714
+ }
6715
+ const { signedUrl: deleteUrl } = rResSignedUrl;
6716
+ return this.delObject(uri, deleteUrl, ctx.conn);
6717
+ }
6718
+ };
6719
+ function getGwCtx(conn, uri) {
6720
+ const rParams = uri.getParamsResult({
6721
+ tid: param.OPTIONAL,
6722
+ tenant: param.REQUIRED,
6723
+ ledger: param.REQUIRED
6724
+ });
6725
+ if (rParams.isErr()) {
6726
+ return Result17.Err(rParams);
6727
+ }
6728
+ const r = rParams.Ok();
6729
+ return Result17.Ok({
6730
+ tid: r.tid,
6731
+ conn,
6732
+ tenant: {
6733
+ tenant: r.tenant,
6734
+ ledger: r.ledger
6735
+ }
6736
+ });
6737
+ }
6738
+ var MetaGateway = class extends BaseGateway {
6739
+ constructor(sthis) {
6740
+ super(sthis, "MetaGateway");
6741
+ }
6742
+ async get(ctx, uri) {
6743
+ const reqSignedUrl = await this.buildReqSignedUrl("bindGetMeta", "GET", "meta", uri, ctx.conn);
6744
+ if (MsgIsError(reqSignedUrl)) {
6745
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6746
+ }
6747
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6748
+ if (rGwCtx.isErr()) {
6749
+ return Result17.Err(rGwCtx);
6750
+ }
6751
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6752
+ if (rAuthType.isErr()) {
6753
+ return Result17.Err(rAuthType);
6754
+ }
6755
+ const res = await ctx.conn.conn.Ok().request(buildBindGetMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rGwCtx.Ok()), {
6756
+ waitFor: MsgIsEventGetMeta
6757
+ });
6758
+ if (MsgIsError(res)) {
6759
+ return this.logger.Error().Err(res).Msg("Error in buildBindGetMeta").ResultError();
6760
+ }
6761
+ const rV2Meta = await V2SerializedMetaKeyExtractKey(ctx, res.meta);
6762
+ const rMeta = await decode2DbMetaEvents(ctx.loader.sthis, rV2Meta);
6763
+ if (rMeta.isErr()) {
6764
+ return Result17.Err(rMeta);
6765
+ }
6766
+ return Result17.Ok({
6767
+ type: "meta",
6768
+ payload: rMeta.Ok()
6769
+ });
6770
+ }
6771
+ async put(ctx, uri, imeta) {
6772
+ const meta = imeta;
6773
+ const reqSignedUrl = await this.buildReqSignedUrl("reqPutMeta", "PUT", "meta", uri, ctx.conn);
6774
+ if (MsgIsError(reqSignedUrl)) {
6775
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6776
+ }
6777
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6778
+ if (rGwCtx.isErr()) {
6779
+ return Result17.Err(rGwCtx);
6780
+ }
6781
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6782
+ if (rAuthType.isErr()) {
6783
+ return Result17.Err(rAuthType);
6784
+ }
6785
+ const serializedMeta = await dbMetaEvent2Serialized(ctx.loader.sthis, meta.payload);
6786
+ const rKeyedMeta = await encodeAsV2SerializedMetaKey(ctx, serializedMeta);
6787
+ if (rKeyedMeta.isErr()) {
6788
+ return rKeyedMeta;
6789
+ }
6790
+ const reqPutMeta = buildReqPutMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rKeyedMeta.Ok(), rGwCtx.Ok());
6791
+ const resMsg = await ctx.conn.conn.Ok().request(reqPutMeta, {
6792
+ waitFor: MsgIsResPutMeta
6793
+ });
6794
+ if (MsgIsError(resMsg)) {
6795
+ return this.logger.Error().Err(resMsg).Msg("Error in buildResSignedUrl").ResultError();
6796
+ }
6797
+ return Result17.Ok(void 0);
6798
+ }
6799
+ async delete(ctx, uri) {
6800
+ const reqSignedUrl = await this.getReqSignedUrl("reqDelMeta", "DELETE", "meta", MsgIsResDelData, uri, ctx.conn);
6801
+ if (MsgIsError(reqSignedUrl)) {
6802
+ return this.logger.Error().Err(reqSignedUrl).Msg("Error in buildReqSignedUrl").ResultError();
6803
+ }
6804
+ const rGwCtx = getGwCtx(ctx.conn.conn.Ok().conn, uri);
6805
+ if (rGwCtx.isErr()) {
6806
+ return Result17.Err(rGwCtx);
6807
+ }
6808
+ const rAuthType = await ctx.conn.conn.Ok().authType();
6809
+ if (rAuthType.isErr()) {
6810
+ return Result17.Err(rAuthType);
6811
+ }
6812
+ const reqDelMeta = buildReqDelMeta(ctx.loader.sthis, rAuthType.Ok(), reqSignedUrl.params, rGwCtx.Ok());
6813
+ const resMsg = await ctx.conn.conn.Ok().request(reqDelMeta, {
6814
+ waitFor: MsgIsResDelData
6815
+ });
6816
+ if (MsgIsError(resMsg)) {
6817
+ return this.logger.Error().Err(resMsg).Msg("Error in buildResSignedUrl").ResultError();
6818
+ }
6819
+ return Result17.Ok(void 0);
6820
+ }
6821
+ };
6822
+ var WALGateway = class extends BaseGateway {
6823
+ constructor(sthis) {
6824
+ super(sthis, "WALGateway");
6825
+ // WAL will not pollute to the cloud
6826
+ this.wals = /* @__PURE__ */ new Map();
6827
+ }
6828
+ getWalKeyFromUri(uri) {
6829
+ const rKey = uri.getParamsResult({
6830
+ key: 0,
6831
+ name: 0
6832
+ });
6833
+ if (rKey.isErr()) {
6834
+ return Result17.Err(rKey.Err());
6835
+ }
6836
+ const { name, key } = rKey.Ok();
6837
+ return Result17.Ok(`${name}:${key}`);
6838
+ }
6839
+ async get(ctx, uri) {
6840
+ const rKey = this.getWalKeyFromUri(uri);
6841
+ if (rKey.isErr()) {
6842
+ return Result17.Err(rKey.Err());
6843
+ }
6844
+ const wal = this.wals.get(rKey.Ok());
6845
+ if (!wal) {
6846
+ return Result17.Err(new NotFoundError("Not found"));
6847
+ }
6848
+ return Result17.Ok(wal);
6849
+ }
6850
+ async put(ctx, uri, body) {
6851
+ const rKey = this.getWalKeyFromUri(uri);
6852
+ if (rKey.isErr()) {
6853
+ return Result17.Err(rKey.Err());
6854
+ }
6855
+ this.wals.set(rKey.Ok(), body);
6856
+ return Result17.Ok(void 0);
6857
+ }
6858
+ async delete(ctx, uri) {
6859
+ const rKey = this.getWalKeyFromUri(uri);
6860
+ if (rKey.isErr()) {
6861
+ return Result17.Err(rKey.Err());
6862
+ }
6863
+ this.wals.delete(rKey.Ok());
6864
+ return Result17.Ok(void 0);
6865
+ }
6866
+ };
6867
+ var storeTypedGateways = new KeyedResolvOnce6();
6868
+ function getStoreTypeGateway(sthis, uri) {
6869
+ const store = uri.getParam("store");
6870
+ switch (store) {
6871
+ case "file":
6872
+ case "car":
6873
+ return storeTypedGateways.get(store).once(() => new DataGateway(sthis));
6874
+ case "meta":
6875
+ return storeTypedGateways.get(store).once(() => new MetaGateway(sthis));
6876
+ case "wal":
6877
+ return storeTypedGateways.get(store).once(() => new WALGateway(sthis));
6878
+ default:
6879
+ throw ensureLogger(sthis, "getStoreTypeGateway").Error().Str("store", store).Msg("Invalid store type").ResultError();
6880
+ }
6881
+ }
6882
+ function connectionURI(uri) {
6883
+ return uri.build().delParam("authJWK").delParam("key").delParam("store").delParam("suffix").delParam("storekey").URI();
6884
+ }
6885
+ var subscriptions = /* @__PURE__ */ new Map();
6886
+ var FireproofCloudGateway = class {
6887
+ #connectionURIs = /* @__PURE__ */ new Map();
6888
+ constructor(sthis) {
6889
+ this.sthis = sthis;
6890
+ this.logger = ensureLogger(sthis, "FireproofCloudGateway", {
6891
+ this: true
6892
+ });
6893
+ }
6894
+ async buildUrl(ctx, baseUrl, key) {
6895
+ return Result17.Ok(baseUrl.build().setParam("key", key).URI());
6896
+ }
6897
+ async start(ctx, uri) {
6898
+ await this.sthis.start();
6899
+ const rName = uri.getParamResult("name");
6900
+ if (rName.isErr()) {
6901
+ return this.logger.Error().Err(rName).Msg("name not found").ResultError();
6902
+ }
6903
+ const ret = uri.build().defParam("version", VERSION3);
6904
+ ret.defParam("protocol", "wss");
6905
+ const retURI = ret.URI();
6906
+ const matchURI = connectionURI(retURI);
6907
+ this.#connectionURIs.set(matchURI.toString(), {
6908
+ uri: matchURI,
6909
+ matchRes: matchURI.match(matchURI),
6910
+ connection: new ResolveOnce8(),
6911
+ trackPuts: /* @__PURE__ */ new Set()
6912
+ });
6913
+ return Result17.Ok(retURI);
6914
+ }
6915
+ async get(ctx, uri) {
6916
+ const conn = await this.getCloudConnectionItem(uri);
6917
+ if (conn.conn.isErr()) {
6918
+ return Result17.Err(conn.conn);
6919
+ }
6920
+ const ret = await getStoreTypeGateway(ctx.loader.sthis, uri).get({ ...ctx, conn }, uri);
6921
+ return ret;
6922
+ }
6923
+ async put(ctx, uri, body) {
6924
+ const conn = await this.getCloudConnectionItem(uri);
6925
+ if (conn.conn.isErr()) {
6926
+ return conn.conn;
6927
+ }
6928
+ const ret = await getStoreTypeGateway(ctx.loader.sthis, uri).put({ ...ctx, conn }, uri, body);
6929
+ if (ret.isOk()) {
6930
+ if (uri.getParam("testMode")) {
6931
+ conn.citem.trackPuts.add(uri.toString());
6932
+ }
6933
+ }
6934
+ return ret;
6935
+ }
6936
+ async delete(ctx, uri) {
6937
+ const conn = await this.getCloudConnectionItem(uri);
6938
+ if (conn.conn.isErr()) {
6939
+ return conn.conn;
6940
+ }
6941
+ conn.citem.trackPuts.delete(uri.toString());
6942
+ return getStoreTypeGateway(ctx.loader.sthis, uri).delete({ ...ctx, conn }, uri);
6943
+ }
6944
+ async close(ctx, uri) {
6945
+ const uriStr = uri.toString();
6946
+ for (const sub of Array.from(subscriptions.values())) {
6947
+ for (const s of sub) {
6948
+ if (s.uri.toString() === uriStr) {
6949
+ s.unsub();
6950
+ }
6951
+ }
6952
+ }
6953
+ const rConn = await this.getCloudConnectionItem(uri);
6954
+ if (rConn.conn.isErr()) {
6955
+ return this.logger.Error().Err(rConn).Msg("Error in getCloudConnection").ResultError();
6956
+ }
6957
+ const conn = rConn.conn.Ok();
6958
+ const rAuth = await conn.msgConnAuth();
6959
+ await conn.close(rAuth.Ok());
6960
+ this.#connectionURIs.delete(rConn.citem.uri.toString());
6961
+ return Result17.Ok(void 0);
6962
+ }
6963
+ // fireproof://localhost:1999/?name=test-public-api&protocol=ws&store=meta
6964
+ async getCloudConnection(uri) {
6965
+ return this.getCloudConnectionItem(uri).then((r) => {
6966
+ return r.conn;
6967
+ });
6968
+ }
6969
+ async getCloudConnectionItem(uri) {
6970
+ const matchURI = connectionURI(uri);
6971
+ let bestMatch;
6972
+ for (const ci of this.#connectionURIs.values()) {
6973
+ const mci = ci.uri.match(matchURI);
6974
+ if (mci.score >= ci.matchRes.score) {
6975
+ bestMatch = ci;
6976
+ break;
6977
+ }
6978
+ }
6979
+ if (!bestMatch) {
6980
+ return {
6981
+ conn: this.logger.Error().Url(matchURI).Any("conns", Object.fromEntries(this.#connectionURIs.entries())).Msg("No connection found").ResultError(),
6982
+ citem: {}
6983
+ };
6984
+ }
6985
+ const conn = await bestMatch.connection.once(async () => {
6986
+ const rParams = uri.getParamsResult({
6987
+ name: param.REQUIRED,
6988
+ protocol: "https",
6989
+ store: param.REQUIRED,
6990
+ storekey: param.OPTIONAL,
6991
+ tenant: param.REQUIRED
6992
+ });
6993
+ if (rParams.isErr()) {
6994
+ return this.logger.Error().Url(uri).Err(rParams).Msg("getCloudConnection:err").ResultError();
6995
+ }
6996
+ const params = rParams.Ok();
6997
+ const rAuth = await authTypeFromUri(this.logger, uri);
6998
+ if (rAuth.isErr()) {
6999
+ return Result17.Err(rAuth);
7000
+ }
7001
+ const qOpen = buildReqOpen(this.sthis, rAuth.Ok(), {});
7002
+ const cUrl = uri.build().protocol(params.protocol).cleanParams().URI();
7003
+ return Msger.connect(this.sthis, rAuth.Ok(), cUrl, qOpen);
7004
+ });
7005
+ if (conn.isErr()) {
7006
+ return { conn: Result17.Err(conn), citem: bestMatch };
7007
+ }
7008
+ return { conn: Result17.Ok(conn.Ok().attachAuth(() => authTypeFromUri(this.logger, uri))), citem: bestMatch };
7009
+ }
7010
+ // private notifySubscribers(data: Uint8Array, callbacks: ((msg: Uint8Array) => void)[] = []): void {
7011
+ // for (const cb of callbacks) {
7012
+ // try {
7013
+ // cb(data);
7014
+ // } catch (error) {
7015
+ // this.logger.Error().Err(error).Msg("Error in subscriber callback execution");
7016
+ // }
7017
+ // }
7018
+ // }
7019
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
7020
+ async subscribe(ctx, url, callback) {
7021
+ return Result17.Err(new Error("Not implemented"));
7022
+ }
7023
+ async destroy(ctx, uri) {
7024
+ const item = await this.getCloudConnectionItem(uri);
7025
+ if (item.conn.isErr()) {
7026
+ return item.conn;
7027
+ }
7028
+ await Promise.all(Array.from(item.citem.trackPuts).map(async (k) => this.delete(ctx, URI17.from(k))));
7029
+ return Result17.Ok(void 0);
7030
+ }
7031
+ async getPlain() {
7032
+ return Result17.Err(new Error("Not implemented"));
7033
+ }
7034
+ };
7035
+ var onceRegisterFireproofCloudStoreProtocol = new KeyedResolvOnce6();
7036
+ function registerFireproofCloudStoreProtocol(protocol = "fpcloud:") {
7037
+ return onceRegisterFireproofCloudStoreProtocol.get(protocol).once(() => {
7038
+ URI17.protocolHasHostpart(protocol);
7039
+ return registerStoreProtocol({
7040
+ protocol,
7041
+ defaultURI() {
7042
+ return URI17.from("fpcloud://fireproof.cloud/");
7043
+ },
7044
+ serdegateway: async (sthis) => {
7045
+ return new FireproofCloudGateway(sthis);
7046
+ }
7047
+ });
7048
+ });
7049
+ }
7050
+ registerFireproofCloudStoreProtocol();
7051
+ function toCloud(url) {
7052
+ const urlObj = URI17.from(url);
7053
+ if (urlObj.protocol !== "fpcloud:") {
7054
+ throw new Error("url must have fireproof protocol");
7055
+ }
7056
+ return {
7057
+ name: urlObj.protocol,
7058
+ prepare() {
7059
+ return Promise.resolve({
7060
+ car: { url: urlObj },
7061
+ file: { url: urlObj },
7062
+ meta: { url: urlObj }
7063
+ });
7064
+ }
7065
+ };
7066
+ }
7067
+
7068
+ // src/protocols/index.ts
7069
+ var protocols_exports = {};
7070
+ __export(protocols_exports, {
7071
+ cloud: () => cloud_exports
7072
+ });
7073
+
7074
+ // src/protocols/cloud/index.ts
7075
+ var cloud_exports = {};
7076
+ __export(cloud_exports, {
7077
+ HttpConnection: () => HttpConnection,
7078
+ MsgConnected: () => MsgConnected,
7079
+ MsgConnectedAuth: () => MsgConnectedAuth,
7080
+ MsgIsBindGetMeta: () => MsgIsBindGetMeta,
7081
+ MsgIsConnected: () => MsgIsConnected,
7082
+ MsgIsError: () => MsgIsError,
7083
+ MsgIsEventGetMeta: () => MsgIsEventGetMeta,
7084
+ MsgIsQSError: () => MsgIsQSError,
7085
+ MsgIsReqChat: () => MsgIsReqChat,
7086
+ MsgIsReqClose: () => MsgIsReqClose,
7087
+ MsgIsReqDelData: () => MsgIsReqDelData,
7088
+ MsgIsReqDelMeta: () => MsgIsReqDelMeta,
7089
+ MsgIsReqDelWAL: () => MsgIsReqDelWAL,
7090
+ MsgIsReqGestalt: () => MsgIsReqGestalt,
7091
+ MsgIsReqGetData: () => MsgIsReqGetData,
7092
+ MsgIsReqGetWAL: () => MsgIsReqGetWAL,
7093
+ MsgIsReqOpen: () => MsgIsReqOpen,
7094
+ MsgIsReqPutData: () => MsgIsReqPutData,
7095
+ MsgIsReqPutMeta: () => MsgIsReqPutMeta,
7096
+ MsgIsReqPutWAL: () => MsgIsReqPutWAL,
7097
+ MsgIsResChat: () => MsgIsResChat,
7098
+ MsgIsResClose: () => MsgIsResClose,
7099
+ MsgIsResDelData: () => MsgIsResDelData,
7100
+ MsgIsResDelMeta: () => MsgIsResDelMeta,
7101
+ MsgIsResDelWAL: () => MsgIsResDelWAL,
7102
+ MsgIsResGestalt: () => MsgIsResGestalt,
7103
+ MsgIsResGetData: () => MsgIsResGetData,
7104
+ MsgIsResGetWAL: () => MsgIsResGetWAL,
7105
+ MsgIsResOpen: () => MsgIsResOpen,
7106
+ MsgIsResPutData: () => MsgIsResPutData,
7107
+ MsgIsResPutMeta: () => MsgIsResPutMeta,
7108
+ MsgIsResPutWAL: () => MsgIsResPutWAL,
7109
+ MsgIsTenantLedger: () => MsgIsTenantLedger,
7110
+ MsgIsTid: () => MsgIsTid,
7111
+ MsgIsWithConn: () => MsgIsWithConn,
7112
+ MsgIsWithConnAuth: () => MsgIsWithConnAuth,
7113
+ MsgRawConnectionBase: () => MsgRawConnectionBase,
7114
+ Msger: () => Msger,
7115
+ VERSION: () => VERSION,
7116
+ WSConnection: () => WSConnection,
7117
+ applyStart: () => applyStart,
7118
+ authTypeFromUri: () => authTypeFromUri,
7119
+ buildBindGetMeta: () => buildBindGetMeta,
7120
+ buildErrorMsg: () => buildErrorMsg,
7121
+ buildEventGetMeta: () => buildEventGetMeta,
7122
+ buildReqChat: () => buildReqChat,
7123
+ buildReqClose: () => buildReqClose,
7124
+ buildReqDelData: () => buildReqDelData,
7125
+ buildReqDelMeta: () => buildReqDelMeta,
7126
+ buildReqDelWAL: () => buildReqDelWAL,
7127
+ buildReqGestalt: () => buildReqGestalt,
7128
+ buildReqGetData: () => buildReqGetData,
7129
+ buildReqGetWAL: () => buildReqGetWAL,
7130
+ buildReqOpen: () => buildReqOpen,
7131
+ buildReqPutData: () => buildReqPutData,
7132
+ buildReqPutMeta: () => buildReqPutMeta,
7133
+ buildReqPutWAL: () => buildReqPutWAL,
7134
+ buildReqSignedUrl: () => buildReqSignedUrl,
7135
+ buildRes: () => buildRes,
7136
+ buildResChat: () => buildResChat,
7137
+ buildResClose: () => buildResClose,
7138
+ buildResDelData: () => buildResDelData,
7139
+ buildResDelMeta: () => buildResDelMeta,
7140
+ buildResDelWAL: () => buildResDelWAL,
7141
+ buildResGestalt: () => buildResGestalt,
7142
+ buildResGetData: () => buildResGetData,
7143
+ buildResGetWAL: () => buildResGetWAL,
7144
+ buildResOpen: () => buildResOpen,
7145
+ buildResPutData: () => buildResPutData,
7146
+ buildResPutMeta: () => buildResPutMeta,
7147
+ buildResPutWAL: () => buildResPutWAL,
7148
+ coerceFPStoreTypes: () => coerceFPStoreTypes,
7149
+ defaultGestalt: () => defaultGestalt,
7150
+ defaultMsgParams: () => defaultMsgParams,
7151
+ ensurePath: () => ensurePath,
7152
+ isAuthTypeFPCloud: () => isAuthTypeFPCloud,
7153
+ isAuthTypeFPCloudJWK: () => isAuthTypeFPCloudJWK,
7154
+ isProtocolCapabilities: () => isProtocolCapabilities,
7155
+ jsonEnDe: () => jsonEnDe,
7156
+ keyTenantLedger: () => keyTenantLedger,
7157
+ qsidEqual: () => qsidEqual,
7158
+ qsidKey: () => qsidKey,
7159
+ resAuth: () => resAuth,
7160
+ selectRandom: () => selectRandom,
7161
+ timeout: () => timeout
7162
+ });
7163
+
7164
+ // src/protocols/cloud/msg-types-wal.ts
7165
+ function MsgIsReqGetWAL(msg) {
7166
+ return msg.type === "reqGetWAL";
7167
+ }
7168
+ function buildReqGetWAL(sthis, sup, ctx) {
7169
+ return buildReqSignedUrl(sthis, "reqGetWAL", sup, ctx);
7170
+ }
7171
+ function MsgIsResGetWAL(msg) {
7172
+ return msg.type === "resGetWAL";
7173
+ }
7174
+ function buildResGetWAL(msgCtx, req, ctx) {
7175
+ return buildRes(
7176
+ { method: "GET", store: "wal" },
7177
+ "resGetWAL",
7178
+ msgCtx,
7179
+ req,
7180
+ ctx
7181
+ );
7182
+ }
7183
+ function MsgIsReqPutWAL(msg) {
7184
+ return msg.type === "reqPutWAL";
7185
+ }
7186
+ function buildReqPutWAL(sthis, sup, ctx) {
7187
+ return buildReqSignedUrl(sthis, "reqPutWAL", sup, ctx);
7188
+ }
7189
+ function MsgIsResPutWAL(msg) {
7190
+ return msg.type === "resPutWAL";
7191
+ }
7192
+ function buildResPutWAL(msgCtx, req, ctx) {
7193
+ return buildRes(
7194
+ { method: "PUT", store: "wal" },
7195
+ "resPutWAL",
7196
+ msgCtx,
7197
+ req,
7198
+ ctx
7199
+ );
7200
+ }
7201
+ function MsgIsReqDelWAL(msg) {
7202
+ return msg.type === "reqDelWAL";
7203
+ }
7204
+ function buildReqDelWAL(sthis, sup, ctx) {
7205
+ return buildReqSignedUrl(sthis, "reqDelWAL", sup, ctx);
7206
+ }
7207
+ function MsgIsResDelWAL(msg) {
7208
+ return msg.type === "resDelWAL" && MsgIsTenantLedger(msg);
7209
+ }
7210
+ function buildResDelWAL(msgCtx, req, ctx) {
7211
+ return buildRes(
7212
+ { method: "DELETE", store: "wal" },
7213
+ "resDelWAL",
7214
+ msgCtx,
7215
+ req,
7216
+ ctx
7217
+ );
7218
+ }
7219
+
5263
7220
  // src/version.ts
5264
7221
  var PACKAGE_VERSION = Object.keys({
5265
- "0.20.0-dev-preview-55": "xxxx"
7222
+ "0.20.0-dev-preview-58": "xxxx"
5266
7223
  })[0];
5267
7224
  export {
5268
7225
  CRDTImpl,
@@ -5299,8 +7256,11 @@ export {
5299
7256
  keyConfigOpts,
5300
7257
  makeName,
5301
7258
  onSuperThis,
7259
+ protocols_exports as protocols,
7260
+ protocols_exports as ps,
5302
7261
  runtime_exports as rt,
5303
7262
  runtime_exports as runtime,
7263
+ setPresetEnv,
5304
7264
  storeType2DataMetaWal,
5305
7265
  throwFalsy,
5306
7266
  toSortedArray,