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

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