@fkn/lib 0.9.48 → 0.9.49

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.
Files changed (49) hide show
  1. package/{storage-C6F9SnDM.js → account-storage-C31d68BN.js} +2 -2
  2. package/{storage-DmRIhg1P.cjs → account-storage-C6hcXjG0.cjs} +1 -1
  3. package/{storage-B_mXNAdB.d.ts → account-storage-DHl6bXdb.d.ts} +2 -2
  4. package/{api-Cpi-qz1j.d.ts → api-wnOQJEK6.d.ts} +34 -42
  5. package/api.d.ts +2 -2
  6. package/cloud/dns.d.ts +1 -1
  7. package/cloud/fetch.d.ts +1 -1
  8. package/cloud/fs/promises.d.ts +1 -1
  9. package/cloud/fs.cjs +1 -1
  10. package/cloud/fs.d.ts +3 -3
  11. package/cloud/fs.js +12 -12
  12. package/cloud/net.d.ts +1 -1
  13. package/{cloud-DK3DtdsU.d.ts → cloud-CWHjH89l.d.ts} +3 -3
  14. package/cloud.d.ts +4 -4
  15. package/{contract-XlEPwc7b.d.ts → contract-DGuGXxKd.d.ts} +119 -82
  16. package/contract.cjs +1 -1
  17. package/contract.d.ts +2 -2
  18. package/contract.js +69 -3
  19. package/dgram.d.ts +2 -2
  20. package/dns.d.ts +1 -1
  21. package/fs/promises.cjs +1 -1
  22. package/fs/promises.d.ts +1 -1
  23. package/fs/promises.js +1 -1
  24. package/{fs-lKZe5xIo.d.ts → fs-BZv2djbS.d.ts} +2 -2
  25. package/{fs-BY0Csn2V.js → fs-ClnOPmRF.js} +39 -39
  26. package/fs-zERmcLRS.cjs +1 -0
  27. package/fs.cjs +1 -1
  28. package/fs.d.ts +3 -3
  29. package/fs.js +2 -2
  30. package/http.d.ts +1 -1
  31. package/{index-D9x6A-Gx.d.ts → index-DawD_N1P.d.ts} +2 -2
  32. package/index.cjs +1 -1
  33. package/index.d.ts +5 -6
  34. package/index.js +39 -40
  35. package/{messages-d7pvCXPn.d.ts → messages-AdPfdoLV.d.ts} +1 -1
  36. package/messages.d.ts +1 -1
  37. package/{net-C2Yz0job.d.ts → net-C2sulnNU.d.ts} +2 -2
  38. package/net.d.ts +1 -1
  39. package/package.json +5 -5
  40. package/packages.d.ts +1 -1
  41. package/{proxy-BZ-YFeXe.d.ts → proxy-MVuD49E2.d.ts} +2 -2
  42. package/rooms.d.ts +1 -1
  43. package/storage.cjs +1 -0
  44. package/storage.d.ts +69 -0
  45. package/storage.js +137 -0
  46. package/fs-DnF1cQuE.cjs +0 -1
  47. package/links.cjs +0 -1
  48. package/links.d.ts +0 -65
  49. package/links.js +0 -187
package/index.js CHANGED
@@ -3,28 +3,27 @@ import { B as t, C as n, D as r, E as i, F as a, G as o, H as s, I as c, J as ee
3
3
  import { a as pe, i as me, n as he, o as ge, t as _e } from "./extension-hOZN6A1U.js";
4
4
  import { c as H, d as ve, f as ye, o as U, u as W } from "./api-ySazPAwN.js";
5
5
  import { n as be, r as xe } from "./busy-DsMWrSzc.js";
6
- import { LINK_EXPIRES_MS as Se } from "./contract.js";
7
- import { a as Ce, i as G, n as we } from "./cloud-B4_qsdaE.js";
8
- import { t as Te } from "./dns.js";
9
- import { t as Ee } from "./net.js";
10
- import { t as De } from "./dgram.js";
11
- import { t as Oe } from "./http.js";
12
- import { t as ke } from "./desktop.js";
13
- import { t as Ae } from "./account.js";
14
- import { u as je } from "./fs-BY0Csn2V.js";
15
- import { t as Me } from "./opfs.js";
16
- import { t as Ne } from "./packages.js";
17
- import { t as Pe } from "./rooms.js";
18
- import { t as Fe } from "./links.js";
19
- import { t as Ie } from "./connect-button-DtsN3X1J.js";
20
- import { relay as Le } from "osra";
6
+ import { a as Se, i as G, n as Ce } from "./cloud-B4_qsdaE.js";
7
+ import { t as we } from "./dns.js";
8
+ import { t as Te } from "./net.js";
9
+ import { t as Ee } from "./dgram.js";
10
+ import { t as De } from "./http.js";
11
+ import { t as Oe } from "./desktop.js";
12
+ import { t as ke } from "./account.js";
13
+ import { u as Ae } from "./fs-ClnOPmRF.js";
14
+ import { t as je } from "./opfs.js";
15
+ import { t as Me } from "./packages.js";
16
+ import { t as Ne } from "./rooms.js";
17
+ import { t as Pe } from "./storage.js";
18
+ import { t as Fe } from "./connect-button-DtsN3X1J.js";
19
+ import { relay as Ie } from "osra";
21
20
  //#region src/frame.ts
22
- var Re = 1e4, ze = 150, Be = () => new Promise((e) => {
21
+ var Le = 1e4, Re = 150, ze = () => new Promise((e) => {
23
22
  if (g()) return e(!0);
24
- let t, n = setTimeout(() => r(g()), Re), r = (r) => {
23
+ let t, n = setTimeout(() => r(g()), Le), r = (r) => {
25
24
  clearTimeout(t), clearTimeout(n), a.disconnect(), document.removeEventListener("readystatechange", o), e(r);
26
25
  }, i = () => {
27
- clearTimeout(t), t = setTimeout(() => r(g()), ze);
26
+ clearTimeout(t), t = setTimeout(() => r(g()), Re);
28
27
  }, a = new MutationObserver(() => {
29
28
  g() && r(!0);
30
29
  }), o = () => {
@@ -34,57 +33,57 @@ var Re = 1e4, ze = 150, Be = () => new Promise((e) => {
34
33
  attributes: !0,
35
34
  attributeFilter: ["data-fkn-extension"]
36
35
  }), document.addEventListener("readystatechange", o), document.readyState === "complete" && i();
37
- }), Ve = (async (e) => {
36
+ }), Be = (async (e) => {
38
37
  let { kind: t, cookies: n } = D(e);
39
38
  if (t === "window") {
40
39
  let t = e;
41
40
  return n === "native" ? d(t) : G(t);
42
41
  }
43
42
  let r = e;
44
- return n === "native" ? He(r) : G(r);
45
- }), He = async (e) => (Ce(e), await Be(), d(e)), Ue = "https://fkn.app", We = async (e, t) => {
43
+ return n === "native" ? Ve(r) : G(r);
44
+ }), Ve = async (e) => (Se(e), await ze(), d(e)), He = "https://fkn.app", Ue = async (e, t) => {
46
45
  if (typeof window > "u") throw Error("FKN @fkn/lib: relayWorker must be called from the main thread");
47
46
  let n = await ye;
48
47
  if (!n) throw Error("FKN @fkn/lib: relayWorker found no FKN transport in this realm");
49
48
  ve(), xe("relayed worker", t?.unregisterSignal);
50
49
  let r = n.emit instanceof MessagePort ? {} : {
51
- originA: t?.originA ?? Ue,
50
+ originA: t?.originA ?? He,
52
51
  originB: t?.originB ?? "*"
53
52
  };
54
- Le(n, e, {
53
+ Ie(n, e, {
55
54
  key: "fkn-api",
56
55
  ...r,
57
56
  unregisterSignal: t?.unregisterSignal
58
57
  });
59
- }, Ge = async () => typeof window > "u" ? !1 : (await U).connect.prompt(location.origin).catch(() => !1), Ke = async () => typeof window > "u" ? null : (await U).relay.prompt().catch(() => null), K = /* @__PURE__ */ new Set(), qe = (e) => (K.add(e), () => {
58
+ }, We = async () => typeof window > "u" ? !1 : (await U).connect.prompt(location.origin).catch(() => !1), Ge = async () => typeof window > "u" ? null : (await U).relay.prompt().catch(() => null), K = /* @__PURE__ */ new Set(), Ke = (e) => (K.add(e), () => {
60
59
  K.delete(e);
61
- }), q = () => {
60
+ }), qe = () => {
62
61
  if (K.size === 0) return !1;
63
62
  for (let e of [...K]) try {
64
63
  e();
65
64
  } catch {}
66
65
  return !0;
67
- }, Je = (e, t) => {
66
+ }, q = (e, t) => {
68
67
  if (typeof e?.onUpdateTaken == "function") return Promise.resolve(e.onUpdateTaken(t));
69
- }, Ye = /* @__PURE__ */ e({
70
- applyUpdate: () => nt,
71
- busyReasons: () => tt,
72
- onUpdate: () => Qe,
73
- onUpdateTaken: () => $e,
74
- updateReady: () => Xe
75
- }), Xe = async () => typeof window > "u" ? !1 : U.then((e) => e.shell?.updateReady()).then((e) => e === !0).catch(() => !1), J = /* @__PURE__ */ new Set(), Y = !1, Ze = () => {
68
+ }, Je = /* @__PURE__ */ e({
69
+ applyUpdate: () => tt,
70
+ busyReasons: () => et,
71
+ onUpdate: () => Ze,
72
+ onUpdateTaken: () => Qe,
73
+ updateReady: () => Ye
74
+ }), Ye = async () => typeof window > "u" ? !1 : U.then((e) => e.shell?.updateReady()).then((e) => e === !0).catch(() => !1), J = /* @__PURE__ */ new Set(), Y = !1, Xe = () => {
76
75
  Y = !0;
77
76
  for (let e of [...J]) try {
78
77
  e();
79
78
  } catch {}
80
79
  }, X = 0, Z = () => {
81
80
  let e = H();
82
- e && J.size !== 0 && X !== e.epoch && (X = e.epoch, Y = !1, Promise.resolve(e.remote.shell?.onUpdate(Ze)).catch(() => {
81
+ e && J.size !== 0 && X !== e.epoch && (X = e.epoch, Y = !1, Promise.resolve(e.remote.shell?.onUpdate(Xe)).catch(() => {
83
82
  X === e.epoch && (X = 0);
84
83
  }));
85
84
  };
86
85
  typeof window < "u" && W(Z);
87
- var Qe = async (e) => {
86
+ var Ze = async (e) => {
88
87
  if (typeof window > "u") return () => {};
89
88
  if (J.add(e), Y) try {
90
89
  e();
@@ -92,8 +91,8 @@ var Qe = async (e) => {
92
91
  return Z(), () => {
93
92
  J.delete(e);
94
93
  };
95
- }, $e = (e) => typeof window > "u" ? () => {} : qe(e), Q = 0, $ = !1, et = () => {
96
- if (!q() && !$) {
94
+ }, Qe = (e) => typeof window > "u" ? () => {} : Ke(e), Q = 0, $ = !1, $e = () => {
95
+ if (!qe() && !$) {
97
96
  $ = !0;
98
97
  try {
99
98
  location.reload();
@@ -104,7 +103,7 @@ typeof window < "u" && W(() => {
104
103
  let e = H();
105
104
  if (!e || Q === e.epoch) return;
106
105
  Q = e.epoch;
107
- let t = Je(e.remote.shell, et);
106
+ let t = q(e.remote.shell, $e);
108
107
  if (!t) {
109
108
  Q = 0;
110
109
  return;
@@ -113,6 +112,6 @@ typeof window < "u" && W(() => {
113
112
  Q === e.epoch && (Q = 0);
114
113
  });
115
114
  });
116
- var tt = () => be(), nt = async () => typeof window > "u" ? !1 : U.then((e) => e.shell?.applyUpdate()).then((e) => e === !0).catch(() => !1);
115
+ var et = () => be(), tt = async () => typeof window > "u" ? !1 : U.then((e) => e.shell?.applyUpdate()).then((e) => e === !0).catch(() => !1);
117
116
  //#endregion
118
- export { y as ATTACH_FRAME_EVENT_KEY, pe as BACKGROUND_STOPPED, R as CATEGORIES, b as EXTENSION_ABI, f as ExtensionOperationUnsupportedError, O as ExtensionOutdatedError, fe as FORGEABLE_HEADERS, v as FrameWindowBlockedError, u as FrameWindowRefusedError, Se as LINK_EXPIRES_MS, S as LOCATOR_DENIED, ie as LOCATOR_ERROR, c as LOCATOR_INVALID, i as LOCATOR_UNSUPPORTED, P as PERMISSION_DENIED, N as REQUIRED_EXTENSION_ABI, ce as TimeoutError, Ae as account, z as assertAttachableFrameUrl, s as assertFetchableUrl, de as assertForgeableHeaders, se as assertLockdownApplicable, l as assertOneCookieIdentity, Ve as attachFrame, L as attachFramePermission, I as box, we as cloud, Ge as connect, Ie as connectButtonUrl, t as cookies, B as createFrame, h as createVideoElementHandle, ke as desktop, De as dgram, Te as dns, _e as extension, he as fetch, ue as fetchCredentialedPermission, o as fetchLocalPermission, te as fetchPermission, je as fs, p as gotoPermission, C as handleRevivableModules, ae as hasForgedCookie, Oe as http, ge as isBackgroundStopped, A as isBlockedFetchUrl, n as isBlockedFrameUrl, g as isExtensionExposed, ee as isLocalNetworkUrl, a as isLocatorDenied, x as isLocatorInvalid, r as isLocatorUnsupported, T as isPermissionDenied, re as isTerminalError, _ as isType, Fe as links, ne as modifyRequestHeadersPermission, Ee as net, Me as opfs, Ne as packages, j as permissions, me as promptInstall, Ke as promptRelay, le as readCookiePermission, F as readExtensionHandshake, We as relayWorker, oe as removeRequestHeaderRule, k as revive, Pe as rooms, E as setMissingExtensionHandler, V as setRequestHeaderRule, Ye as shell, m as supportsOperation, w as type, M as waitForExtensionExposure };
117
+ export { y as ATTACH_FRAME_EVENT_KEY, pe as BACKGROUND_STOPPED, R as CATEGORIES, b as EXTENSION_ABI, f as ExtensionOperationUnsupportedError, O as ExtensionOutdatedError, fe as FORGEABLE_HEADERS, v as FrameWindowBlockedError, u as FrameWindowRefusedError, S as LOCATOR_DENIED, ie as LOCATOR_ERROR, c as LOCATOR_INVALID, i as LOCATOR_UNSUPPORTED, P as PERMISSION_DENIED, N as REQUIRED_EXTENSION_ABI, ce as TimeoutError, ke as account, z as assertAttachableFrameUrl, s as assertFetchableUrl, de as assertForgeableHeaders, se as assertLockdownApplicable, l as assertOneCookieIdentity, Be as attachFrame, L as attachFramePermission, I as box, Ce as cloud, We as connect, Fe as connectButtonUrl, t as cookies, B as createFrame, h as createVideoElementHandle, Oe as desktop, Ee as dgram, we as dns, _e as extension, he as fetch, ue as fetchCredentialedPermission, o as fetchLocalPermission, te as fetchPermission, Ae as fs, p as gotoPermission, C as handleRevivableModules, ae as hasForgedCookie, De as http, ge as isBackgroundStopped, A as isBlockedFetchUrl, n as isBlockedFrameUrl, g as isExtensionExposed, ee as isLocalNetworkUrl, a as isLocatorDenied, x as isLocatorInvalid, r as isLocatorUnsupported, T as isPermissionDenied, re as isTerminalError, _ as isType, ne as modifyRequestHeadersPermission, Te as net, je as opfs, Me as packages, j as permissions, me as promptInstall, Ge as promptRelay, le as readCookiePermission, F as readExtensionHandshake, Ue as relayWorker, oe as removeRequestHeaderRule, k as revive, Ne as rooms, E as setMissingExtensionHandler, V as setRequestHeaderRule, Je as shell, Pe as storage, m as supportsOperation, w as type, M as waitForExtensionExposure };
@@ -6,7 +6,7 @@ declare const E2E_INTEGRITY_MESSAGE = "fkn:e2e-integrity: stored data failed its
6
6
  declare const E2E_RETIRED_FORMAT_MESSAGE = "fkn:e2e-retired-format: stored data is in a format this version no longer opens";
7
7
  /**
8
8
  * The error code for "there is no object at this path", so a caller tests absence instead of parsing
9
- * a message. osra drops custom codes at the SharedWorker boundary, so storage.ts's rethrow re-mints
9
+ * a message. osra drops custom codes at the SharedWorker boundary, so account-storage.ts's rethrow re-mints
10
10
  * it from the message on the app side.
11
11
  */
12
12
  declare const STORAGE_NOT_FOUND = "FKN_STORAGE_NOT_FOUND";
package/messages.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as E2E_LOCKED_MESSAGE, c as STORAGE_ACCOUNT_CHANGED, d as STORAGE_UNREACHABLE, i as E2E_INTEGRITY_MESSAGE, l as STORAGE_ACCOUNT_PIN_UNSUPPORTED, n as ACCOUNT_PIN_INVALID_MESSAGE, o as E2E_RETIRED_FORMAT_MESSAGE, r as ACCOUNT_PIN_UNSUPPORTED_MESSAGE, s as E2E_STALE_EPOCH_MESSAGE, t as ACCOUNT_CHANGED_MESSAGE, u as STORAGE_NOT_FOUND } from "./messages-d7pvCXPn.js";
1
+ import { a as E2E_LOCKED_MESSAGE, c as STORAGE_ACCOUNT_CHANGED, d as STORAGE_UNREACHABLE, i as E2E_INTEGRITY_MESSAGE, l as STORAGE_ACCOUNT_PIN_UNSUPPORTED, n as ACCOUNT_PIN_INVALID_MESSAGE, o as E2E_RETIRED_FORMAT_MESSAGE, r as ACCOUNT_PIN_UNSUPPORTED_MESSAGE, s as E2E_STALE_EPOCH_MESSAGE, t as ACCOUNT_CHANGED_MESSAGE, u as STORAGE_NOT_FOUND } from "./messages-AdPfdoLV.js";
2
2
  export { ACCOUNT_CHANGED_MESSAGE, ACCOUNT_PIN_INVALID_MESSAGE, ACCOUNT_PIN_UNSUPPORTED_MESSAGE, E2E_INTEGRITY_MESSAGE, E2E_LOCKED_MESSAGE, E2E_RETIRED_FORMAT_MESSAGE, E2E_STALE_EPOCH_MESSAGE, STORAGE_ACCOUNT_CHANGED, STORAGE_ACCOUNT_PIN_UNSUPPORTED, STORAGE_NOT_FOUND, STORAGE_UNREACHABLE };
@@ -1,6 +1,6 @@
1
- import { Mt as TcpSocketListenerResult, Pt as TcpSocketResult, tt as Resolvers } from "./contract-XlEPwc7b.js";
1
+ import { K as Resolvers, Mt as TcpSocketListenerResult, Pt as TcpSocketResult } from "./contract-DGuGXxKd.js";
2
2
  import { o as TcpSocketOption } from "./wire-Fk5pJaoy.js";
3
- import "./api-Cpi-qz1j.js";
3
+ import "./api-wnOQJEK6.js";
4
4
  import { AddressInfo, ListenOptions, Server, ServerOpts, Socket, SocketConnectOpts, SocketConstructorOpts } from "net";
5
5
  import { DuplexOptions, Stream } from "stream";
6
6
  import { EventEmitter } from "events";
package/net.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as createConnection, c as isIP, i as connect, l as isIPv4, n as Socket, o as createServer, r as _default, t as Server, u as isIPv6 } from "./net-C2Yz0job.js";
1
+ import { a as createConnection, c as isIP, i as connect, l as isIPv4, n as Socket, o as createServer, r as _default, t as Server, u as isIPv6 } from "./net-C2sulnNU.js";
2
2
  export { Server, Socket, _default, _default as default, connect, createConnection, createServer, isIP, isIPv4, isIPv6 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fkn/lib",
3
- "version": "0.9.48",
3
+ "version": "0.9.49",
4
4
  "main": "index.js",
5
5
  "types": "index.d.ts",
6
6
  "type": "module",
@@ -115,10 +115,10 @@
115
115
  "import": "./rooms.js",
116
116
  "require": "./rooms.cjs"
117
117
  },
118
- "./links": {
119
- "types": "./links.d.ts",
120
- "import": "./links.js",
121
- "require": "./links.cjs"
118
+ "./storage": {
119
+ "types": "./storage.d.ts",
120
+ "import": "./storage.js",
121
+ "require": "./storage.cjs"
122
122
  },
123
123
  "./react": {
124
124
  "types": "./react.d.ts",
package/packages.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { At as SurfaceRect, E as InstalledPackage, G as PackagesErrorCode, J as Placement, T as InstallOptions, U as PackageQuery, W as PackageResult, et as Radii, m as ConnectOptions, q as PickOptions } from "./contract-XlEPwc7b.js";
1
+ import { At as SurfaceRect, E as InstalledPackage, F as PackageResult, G as Radii, I as PackagesErrorCode, P as PackageQuery, R as PickOptions, T as InstallOptions, m as ConnectOptions, z as Placement } from "./contract-DGuGXxKd.js";
2
2
  import { Remote } from "osra";
3
3
  declare namespace packages_d_exports {
4
4
  export { AppConnectOptions, Connect, ConnectOptions, ConnectPayload, IncomingConnection, IncomingConnectionInfo, InstallOptions, InstalledPackage, MountOptions, MountedPackage, PackageConnection, PackageQuery, PackageResult, PackageView, PackagesError, PackagesErrorCode, PickOptions, Placement, Radii, RawPackageConnection, ShowOptions, SurfaceRect, attach, connect, hide, install, isVisible, list, mount, onConnect, onVisibilityChange, pick, search, show, uninstall };
@@ -1,5 +1,5 @@
1
- import { tt as Resolvers } from "./contract-XlEPwc7b.js";
2
- import "./api-Cpi-qz1j.js";
1
+ import { K as Resolvers } from "./contract-DGuGXxKd.js";
2
+ import "./api-wnOQJEK6.js";
3
3
  //#region src/proxy.d.ts
4
4
  type ProxyFetch = Resolvers['cloud']['fetch'];
5
5
  type FetchParameters = Parameters<ProxyFetch>;
package/rooms.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { at as RoomDefaults, dt as RoomMember, ft as RoomMessage, gt as RoomsErrorCode, ht as RoomPermissions, it as RoomCreateOptions, lt as RoomJoinOptions, mt as RoomPermission, nt as RoomBacklog, ot as RoomEnd, pt as RoomOpenOptions, rt as RoomClaimOptions, st as RoomEvent, ut as RoomMailbox } from "./contract-XlEPwc7b.js";
1
+ import { J as RoomClaimOptions, Q as RoomEvent, X as RoomDefaults, Y as RoomCreateOptions, Z as RoomEnd, at as RoomPermission, et as RoomJoinOptions, it as RoomOpenOptions, nt as RoomMember, ot as RoomPermissions, q as RoomBacklog, rt as RoomMessage, st as RoomsErrorCode, tt as RoomMailbox } from "./contract-DGuGXxKd.js";
2
2
  declare namespace rooms_d_exports {
3
3
  export { RoomClaimOptions as ClaimOptions, RoomCreateOptions as CreateOptions, RoomJoinOptions as JoinOptions, RoomOpenOptions as OpenOptions, Room, RoomBacklog, RoomDefaults, RoomEnd, RoomEvent, RoomMailbox, RoomMember, RoomMessage, RoomPermission, RoomPermissions, RoomsError, RoomsErrorCode, available, create, join, open };
4
4
  }
package/storage.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./rolldown-runtime-BIInC43l.cjs"),t=require("./api-DMnVye0K.cjs"),n=require("./contract.cjs"),r=require("./account-generation-9VhfEDoW.cjs"),i=require("./account-storage-C6hcXjG0.cjs");var a=e.t({available:()=>v,delete:()=>C,get:()=>x,list:()=>S,put:()=>y}),o=new Map(Object.values(n.STORAGE_REFUSALS).map(({code:e,message:t})=>[t,e])),s=new Set(o.values()),c=(e,t)=>Object.assign(Error(t),{code:e}),l=e=>c(n.STORAGE_REFUSALS[e].code,n.STORAGE_REFUSALS[e].message),u=e=>e instanceof Error&&s.has(e.code),d=e=>{if(u(e))return e;let t=e instanceof Error?e.message:``,n=o.get(t);return n?c(n,t):l(`unavailable`)},f=async()=>{if(!t.l)return;let e=(await t.s(`storage`).catch(()=>void 0))?.storage;return typeof e?.put==`function`?e:void 0},p=()=>{throw l(`unavailable`)},m=e=>typeof e==`object`&&!!e&&typeof e.error==`string`&&typeof e.message==`string`,h=(e,t,n)=>{throw e.error===`aborted`?t?.reason??new DOMException(`The operation was aborted.`,`AbortError`):(e.error===`account-changed`&&n&&r.r(n.generation),s.has(e.error)?c(e.error,e.message):l(`unavailable`))},g=async e=>{try{return await i.m(e)}catch(e){throw i.l(e)?l(`accountChanged`):e instanceof Error&&/not connected|not signed in/i.test(e.message)?l(`needsAccount`):l(`unavailable`)}},_=(e,t)=>(e.catch(()=>{}),t?Promise.race([e,new Promise((e,n)=>t.addEventListener(`abort`,()=>n(t.reason),{once:!0}))]):e),v=async()=>{let e=await f();return e?Promise.resolve(e.available()).catch(()=>!1):!1},y=async(e,t={})=>{let n=i.s(),{signal:r,onProgress:a,key:o}=t;r?.throwIfAborted();let s=typeof Blob<`u`&&e instanceof Blob,c=typeof ReadableStream<`u`&&e instanceof ReadableStream;if(!s&&!c)throw l(`notAFile`);let u=s?e.size:t.size;if(typeof u!=`number`||!Number.isSafeInteger(u)||u<0||s&&t.size!==void 0&&t.size!==u)throw l(`badSize`);let d=await f();if(!d)throw l(`unavailable`);let v=await g(n);r?.throwIfAborted();let y=await _(Promise.resolve(d.put(e,{size:u,...o===void 0?{}:{key:o},accountPin:v,...r?{signal:r}:{},...typeof a==`function`?{onProgress:e=>{try{a(e)}catch{}}}:{}})).catch(p),r);return m(y)?h(y,r,n):y},b=(e,t,n)=>{let r=(t,n)=>{if(t===void 0)return n;let r=Math.trunc(Number.isFinite(t)?t:t>0?e:-e);return r<0?Math.max(e+r,0):Math.min(r,e)},i=r(t,0);return{from:i,to:Math.max(i,r(n,e))}},x=async(e,n,r={})=>{if(typeof e!=`string`)throw l(`badUrl`);if(typeof n!=`string`)throw l(`badKey`);let{signal:i}=r;i?.throwIfAborted();let a=async()=>{let r=await f();if(!r)throw l(`unavailable`);let a=t.c()?.epoch,o=await _(Promise.resolve(r.get(e,n,i?{signal:i}:void 0)).catch(p),i);return m(o)?h(o,i):{handle:o,epoch:a}},o=await a(),s=async()=>{let e=t.c()?.epoch;return o.epoch!==void 0&&e!==void 0&&e!==o.epoch&&(o=await a()),o.handle},c=(e,t)=>{let n;return new ReadableStream({pull:async r=>{try{if(!n){let r=await s(),i=await Promise.resolve(r.read(e,t)).catch(p);if(m(i))return h(i);n=i.getReader()}let{value:i,done:a}=await n.read();a?r.close():r.enqueue(i)}catch(e){throw d(e)}},cancel:e=>n?.cancel(e)},{highWaterMark:0})},u=(e,t)=>({size:t-e,stream:()=>c(e,t),arrayBuffer:async()=>{let n=new Uint8Array(t-e),r=c(e,t).getReader(),i=0;for(;;){let{value:e,done:t}=await r.read();if(t)break;n.set(e,i),i+=e.length}return n.buffer},slice:(n,r)=>{let i=b(t-e,n,r);return u(e+i.from,e+i.to)}});return u(0,o.handle.size)},S=async(e={})=>{let t=i.s(),n=await f();if(!n)throw l(`unavailable`);let r=await g(t),{limit:a,cursor:o}=e,s=await Promise.resolve(n.list({accountPin:r,...a===void 0?{}:{limit:a},...o===void 0?{}:{cursor:o}})).catch(p);return m(s)?h(s,void 0,t):s},C=async e=>{let t=i.s();if(typeof e!=`string`)throw l(`badUrl`);let n=await f();if(!n)throw l(`unavailable`);let r=await g(t),a=await Promise.resolve(n.delete(e,{accountPin:r})).catch(p);m(a)&&h(a,void 0,t)};exports.available=v,exports.delete=C,exports.get=x,exports.list=S,exports.put=y,Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
package/storage.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { Ct as StorageProgress, Ot as StoredObject, kt as StoredPage, wt as StoragePutOptions, xt as StorageErrorCode } from "./contract-DGuGXxKd.js";
2
+ declare namespace storage_d_exports {
3
+ export { StorageError, StorageErrorCode, StorageProgress, StoragePutOptions, StoredBlob, StoredObject, StoredPage, available, remove as delete, get, list, put };
4
+ }
5
+ /** Thrown by every member of this namespace except on an aborted signal. Match on `code`, never on the message. */
6
+ export type StorageError = Error & {
7
+ code: StorageErrorCode;
8
+ };
9
+ /**
10
+ * The bytes `get` opened, shaped like a `Blob`: `size`, `stream`, `arrayBuffer` and `slice`. Every read
11
+ * is by range and each 1 MiB record is checked before it is handed over, so a `slice` near the end of
12
+ * a large object fetches only that end.
13
+ */
14
+ export type StoredBlob = {
15
+ /** the plaintext bytes of this blob, a slice's own length */
16
+ size: number;
17
+ /** errors with `integrity` on the first record that does not open under the key */
18
+ stream: () => ReadableStream<Uint8Array>;
19
+ arrayBuffer: () => Promise<ArrayBuffer>;
20
+ /** `Blob.slice`'s arguments, negative ones counted from the end, and the same shape back */
21
+ slice: (start?: number, end?: number) => StoredBlob;
22
+ };
23
+ /** Whether put, list and delete can run here now. `get` needs no account and does not depend on this. Answers rather than rejecting. */
24
+ export declare const available: () => Promise<boolean>;
25
+ /**
26
+ * Seals the data in the broker and uploads it, then answers its url and the key that opens it: the
27
+ * app's own `key` unchanged, or the one the broker minted. Resolves once the object is `ready`. Needs
28
+ * a signed-in account, and counts the sealed size (28 bytes more per 1 MiB) against the account's
29
+ * storage from the moment it starts until the object is deleted or the upload is aborted. The account
30
+ * the call belongs to is the one this page is on when it is made, as for every storage call.
31
+ *
32
+ * `data` is a `Blob` (a `File` included) or a `ReadableStream<Uint8Array>` with its `size`. An upload
33
+ * survives the network dropping a part, not a reload: a reload starts the file again, and the upload
34
+ * left behind stops counting within the hour.
35
+ *
36
+ * Refused `invalid` for a stream without its size or one that delivers another, a file past the
37
+ * service's part ceiling, or a `key` that is not 32 bytes base64url; `denied` with no account; `quota`;
38
+ * `too-many` past the account's stored objects or this hour's uploads; `account-changed`.
39
+ */
40
+ export declare const put: (data: Blob | ReadableStream<Uint8Array>, options?: StoragePutOptions) => Promise<StoredObject & {
41
+ key: string;
42
+ }>;
43
+ /**
44
+ * Opens an object any app stored, with no account: the broker reads its size from the first ranged
45
+ * answer and fetches the sealed bytes by range. Refused `invalid` for a url that names no stored object
46
+ * or a key that is not 32 bytes base64url, `not-found` for an object that was never made, was deleted
47
+ * or is still uploading (one answer for all of them). A wrong key shows on the first read, as
48
+ * `integrity`. A broker replaced while the object is held is asked to open it again on the next read.
49
+ */
50
+ export declare const get: (url: string, key: string, options?: {
51
+ signal?: AbortSignal;
52
+ }) => Promise<StoredBlob>;
53
+ /**
54
+ * This app's objects, newest first, uploads in progress included: no key, which the service never
55
+ * holds. `limit` is 1 to 1,000 (1,000 by default), and `cursor` is the one a previous page answered;
56
+ * `invalid` otherwise.
57
+ */
58
+ export declare const list: (options?: {
59
+ limit?: number;
60
+ cursor?: string;
61
+ }) => Promise<StoredPage>;
62
+ /**
63
+ * Deletes an object by its url: every later `get` of it answers `not-found`, and an upload in progress
64
+ * is aborted and stops counting. Only the app that stored it (the same app once it is verified)
65
+ * deletes it, `denied` otherwise. An object already gone resolves.
66
+ */
67
+ declare const remove: (url: string) => Promise<void>;
68
+ //#endregion
69
+ export { type StorageErrorCode, type StorageProgress, type StoragePutOptions, type StoredObject, type StoredPage, remove as delete, storage_d_exports as t };
package/storage.js ADDED
@@ -0,0 +1,137 @@
1
+ import { t as e } from "./rolldown-runtime-Dy4uBu1J.js";
2
+ import { c as t, l as n, s as r } from "./api-ySazPAwN.js";
3
+ import { STORAGE_REFUSALS as i } from "./contract.js";
4
+ import { r as a } from "./account-generation-hUekEHGW.js";
5
+ import { l as o, m as s, s as c } from "./account-storage-C31d68BN.js";
6
+ //#region src/storage.ts
7
+ var l = /* @__PURE__ */ e({
8
+ available: () => S,
9
+ delete: () => D,
10
+ get: () => T,
11
+ list: () => E,
12
+ put: () => C
13
+ }), u = new Map(Object.values(i).map(({ code: e, message: t }) => [t, e])), d = new Set(u.values()), f = (e, t) => Object.assign(Error(t), { code: e }), p = (e) => f(i[e].code, i[e].message), m = (e) => e instanceof Error && d.has(e.code), h = (e) => {
14
+ if (m(e)) return e;
15
+ let t = e instanceof Error ? e.message : "", n = u.get(t);
16
+ return n ? f(n, t) : p("unavailable");
17
+ }, g = async () => {
18
+ if (!n) return;
19
+ let e = (await r("storage").catch(() => void 0))?.storage;
20
+ return typeof e?.put == "function" ? e : void 0;
21
+ }, _ = () => {
22
+ throw p("unavailable");
23
+ }, v = (e) => typeof e == "object" && !!e && typeof e.error == "string" && typeof e.message == "string", y = (e, t, n) => {
24
+ throw e.error === "aborted" ? t?.reason ?? new DOMException("The operation was aborted.", "AbortError") : (e.error === "account-changed" && n && a(n.generation), d.has(e.error) ? f(e.error, e.message) : p("unavailable"));
25
+ }, b = async (e) => {
26
+ try {
27
+ return await s(e);
28
+ } catch (e) {
29
+ throw o(e) ? p("accountChanged") : e instanceof Error && /not connected|not signed in/i.test(e.message) ? p("needsAccount") : p("unavailable");
30
+ }
31
+ }, x = (e, t) => (e.catch(() => {}), t ? Promise.race([e, new Promise((e, n) => t.addEventListener("abort", () => n(t.reason), { once: !0 }))]) : e), S = async () => {
32
+ let e = await g();
33
+ return e ? Promise.resolve(e.available()).catch(() => !1) : !1;
34
+ }, C = async (e, t = {}) => {
35
+ let n = c(), { signal: r, onProgress: i, key: a } = t;
36
+ r?.throwIfAborted();
37
+ let o = typeof Blob < "u" && e instanceof Blob, s = typeof ReadableStream < "u" && e instanceof ReadableStream;
38
+ if (!o && !s) throw p("notAFile");
39
+ let l = o ? e.size : t.size;
40
+ if (typeof l != "number" || !Number.isSafeInteger(l) || l < 0 || o && t.size !== void 0 && t.size !== l) throw p("badSize");
41
+ let u = await g();
42
+ if (!u) throw p("unavailable");
43
+ let d = await b(n);
44
+ r?.throwIfAborted();
45
+ let f = await x(Promise.resolve(u.put(e, {
46
+ size: l,
47
+ ...a === void 0 ? {} : { key: a },
48
+ accountPin: d,
49
+ ...r ? { signal: r } : {},
50
+ ...typeof i == "function" ? { onProgress: (e) => {
51
+ try {
52
+ i(e);
53
+ } catch {}
54
+ } } : {}
55
+ })).catch(_), r);
56
+ return v(f) ? y(f, r, n) : f;
57
+ }, w = (e, t, n) => {
58
+ let r = (t, n) => {
59
+ if (t === void 0) return n;
60
+ let r = Math.trunc(Number.isFinite(t) ? t : t > 0 ? e : -e);
61
+ return r < 0 ? Math.max(e + r, 0) : Math.min(r, e);
62
+ }, i = r(t, 0);
63
+ return {
64
+ from: i,
65
+ to: Math.max(i, r(n, e))
66
+ };
67
+ }, T = async (e, n, r = {}) => {
68
+ if (typeof e != "string") throw p("badUrl");
69
+ if (typeof n != "string") throw p("badKey");
70
+ let { signal: i } = r;
71
+ i?.throwIfAborted();
72
+ let a = async () => {
73
+ let r = await g();
74
+ if (!r) throw p("unavailable");
75
+ let a = t()?.epoch, o = await x(Promise.resolve(r.get(e, n, i ? { signal: i } : void 0)).catch(_), i);
76
+ return v(o) ? y(o, i) : {
77
+ handle: o,
78
+ epoch: a
79
+ };
80
+ }, o = await a(), s = async () => {
81
+ let e = t()?.epoch;
82
+ return o.epoch !== void 0 && e !== void 0 && e !== o.epoch && (o = await a()), o.handle;
83
+ }, c = (e, t) => {
84
+ let n;
85
+ return new ReadableStream({
86
+ pull: async (r) => {
87
+ try {
88
+ if (!n) {
89
+ let r = await s(), i = await Promise.resolve(r.read(e, t)).catch(_);
90
+ if (v(i)) return y(i);
91
+ n = i.getReader();
92
+ }
93
+ let { value: i, done: a } = await n.read();
94
+ a ? r.close() : r.enqueue(i);
95
+ } catch (e) {
96
+ throw h(e);
97
+ }
98
+ },
99
+ cancel: (e) => n?.cancel(e)
100
+ }, { highWaterMark: 0 });
101
+ }, l = (e, t) => ({
102
+ size: t - e,
103
+ stream: () => c(e, t),
104
+ arrayBuffer: async () => {
105
+ let n = new Uint8Array(t - e), r = c(e, t).getReader(), i = 0;
106
+ for (;;) {
107
+ let { value: e, done: t } = await r.read();
108
+ if (t) break;
109
+ n.set(e, i), i += e.length;
110
+ }
111
+ return n.buffer;
112
+ },
113
+ slice: (n, r) => {
114
+ let i = w(t - e, n, r);
115
+ return l(e + i.from, e + i.to);
116
+ }
117
+ });
118
+ return l(0, o.handle.size);
119
+ }, E = async (e = {}) => {
120
+ let t = c(), n = await g();
121
+ if (!n) throw p("unavailable");
122
+ let r = await b(t), { limit: i, cursor: a } = e, o = await Promise.resolve(n.list({
123
+ accountPin: r,
124
+ ...i === void 0 ? {} : { limit: i },
125
+ ...a === void 0 ? {} : { cursor: a }
126
+ })).catch(_);
127
+ return v(o) ? y(o, void 0, t) : o;
128
+ }, D = async (e) => {
129
+ let t = c();
130
+ if (typeof e != "string") throw p("badUrl");
131
+ let n = await g();
132
+ if (!n) throw p("unavailable");
133
+ let r = await b(t), i = await Promise.resolve(n.delete(e, { accountPin: r })).catch(_);
134
+ v(i) && y(i, void 0, t);
135
+ };
136
+ //#endregion
137
+ export { S as available, D as delete, T as get, E as list, C as put, l as t };
package/fs-DnF1cQuE.cjs DELETED
@@ -1 +0,0 @@
1
- const e=require("./rolldown-runtime-BIInC43l.cjs"),t=require("./api-DMnVye0K.cjs"),n=require("./busy-BXbVH595.cjs"),r=require("./node-fs-vsWuoMGa.cjs"),i=require("./messages.cjs"),a=require("./storage-DmRIhg1P.cjs"),o=require("./account.cjs"),s=require("./opfs-CXMESVLc.cjs");var c=e.t({adopt:()=>L,adoptable:()=>z,available:()=>ee,captureAccount:()=>l,list:()=>ye,onConflict:()=>Ce,pending:()=>fe,pendingDeletes:()=>pe,pull:()=>N,readFile:()=>be,readFileSealed:()=>M,remove:()=>Se,replicating:()=>me,writeFile:()=>xe}),l=a.o,u,d=async()=>await(u??=s.t().catch(()=>!1))?!0:(u=void 0,!1),f=()=>a.a().catch(()=>`unknown`),p=async()=>await f()===`connected`,ee=async()=>await d()||await p(),te=`fkn:fs:pending`,ne=`fkn:fs:pending-delete`,re=`fkn:fs:adopt-declined`,m=!0,ie=new Map,ae=null,oe=(e,t)=>{if(e===null)return!1;if(`generation`in e&&`generation`in t)return e.generation===t.generation;let n=e=>`pin`in e?e.pin:a.d(e),r=n(e);return r!==void 0&&r===n(t)},h=(e,t)=>oe(ae,t)?ie.get(e)??null:null,g=e=>e===`write`?te:ne,_=e=>{try{let t=localStorage.getItem(g(e));if(!t)return{};let n=JSON.parse(t);if(Array.isArray(n))return Object.fromEntries(n.filter(e=>typeof e==`string`).map(e=>[e,{base:null,pin:null}]));if(!n||typeof n!=`object`)return{};let r={};for(let[e,t]of Object.entries(n))if(t===null||typeof t==`string`)r[e]={base:t,pin:null};else if(typeof t==`object`){let{base:n,pin:i}=t;r[e]={base:typeof n==`string`?n:null,pin:typeof i==`string`&&i?i:null}}return r}catch{return{}}},v=(e,t)=>{try{Object.keys(t).length?localStorage.setItem(g(e),JSON.stringify(t)):localStorage.removeItem(g(e))}catch{}},se=()=>{try{let e=JSON.parse(localStorage.getItem(re)??`{}`);return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch{return{}}},y=new Map,ce=e=>`pin`in e?e.pin:a.d(e)??null,le=(e,t,n,r)=>{let i=_(e),a=i[t],o=ce(r);a&&o!==null&&a.pin===o||(i[t]={base:a?a.base:n,pin:o},v(e,i),o===null&&`generation`in r?y.set(`${e}:${t}`,r):y.delete(`${e}:${t}`))},ue=(e,t)=>{y.delete(`${e}:${t}`);let n=_(e);t in n&&(delete n[t],v(e,n),E()||(O=D))},b=(e,t,n)=>le(`write`,e,t,n),x=e=>ue(`write`,e),de=(e,t)=>le(`delete`,e,h(e,t),t),S=e=>ue(`delete`,e),fe=()=>Object.keys(_(`write`)),pe=()=>Object.keys(_(`delete`)),me=()=>m,C=new Map,he=e=>C.get(e)===a.o().generation,ge=(e,t,n)=>n.pin===null&&!y.has(`${e}:${t}`),w=null,T=!1;n.i(`storage replication`,()=>w!==null||B!==null);var E=()=>[`write`,`delete`].some(e=>Object.entries(_(e)).some(([t,n])=>n.pin===null?!ge(e,t,n):!he(n.pin))),D=6e4,_e=6e5,O=D,k=null,A=()=>{!k&&typeof window<`u`&&E()&&(k=setTimeout(()=>{k=null,j()},O),O=Math.min(O*2,_e))},j=()=>{if(w){T=!0;return}E()&&(w=ke(!1,a.o()).then(e=>{if(!E()){O=D;return}e.failed.length&&A()}).catch(()=>{A()}).finally(()=>{w=null,ve()}))},ve=()=>{T&&(T=!1,j())},ye=async e=>{let t=e?.pin??a.o();U();let n=await f(),r=n===`connected`,[i,o]=await Promise.all([d().then(e=>e?s.n():[]).catch(()=>[]),r?a.f({pin:t}).then(e=>({ok:!0,entries:e}),e=>({ok:!1,entries:[],changed:a.c(e)?e:void 0})):Promise.resolve({ok:n===`disconnected`,entries:[]})]);if(n!==`unknown`&&(m=o.ok),o.ok&&n!==`unknown`&&(ie=new Map(o.entries.map(e=>[e.path,e.updatedAt])),ae=t),o.changed)throw o.changed;let c=new Map,l=e=>{let t=Date.parse(e.updatedAt??``);return Number.isFinite(t)?t:0},u=e=>{let t=c.get(e.path);(!t||l(e)>=l(t))&&c.set(e.path,e)};for(let e of i)u(e);for(let e of o.entries)u(e);return o.ok&&r&&(Ie(i,o.entries).catch(()=>{}),E()?j():H({local:i,remote:o.entries,from:t}).catch(()=>{})),[...c.values()]},be=async(e,t)=>{let n=t?.pin??a.o();if(await d())try{return await s.i(e)}catch(e){if(e?.name!==`NotFoundError`)throw e}let r=await a.h(e,{pin:n});return await d()&&s.o(e,r).catch(()=>{}),r},M=async(e,t)=>{let n=t?.pin??a.o();if(await d())try{let t=await s.i(e);return{data:new Uint8Array(await t.arrayBuffer()),sealedAt:null}}catch(e){if(e?.name!==`NotFoundError`)throw e}return a.g(e,{pin:n})},xe=async(e,t,n)=>{let r=n?.pin??a.o(),i=n?.contentType,o=i?{contentType:i}:void 0,c=t instanceof Blob?t:new Blob([t],o?{type:o.contentType}:void 0);if(await d()){await s.o(e,c,o),U();let t=h(e,r),n=await f();if(n===`disconnected`)return;if(n===`unknown`||!m){b(e,t,r),A();return}a.b(e,c,{...o,pin:r}).then(()=>x(e)).catch(n=>{b(e,t,r),a.c(n)||A(),console.warn(`fs: cloud replicate failed, queued for adopt()`,n)});return}let l=await f();if(l===`connected`)return a.b(e,c,{...o,pin:r});throw Error(l===`unknown`?`fs: cloud unreachable`:`fs: no storage backend available`)},Se=async(e,t)=>{let n=t?.pin??a.o();U();let r=[];await d()&&r.push(s.a(e).catch(()=>{}));let i=await f();if(i===`connected`?r.push(a._(e,{pin:n}).then(()=>S(e)).catch(t=>{de(e,n),a.c(t)||A(),console.warn(`fs: cloud delete failed, queued for retry`,t)})):i===`unknown`&&r.length&&h(e,n)!==null&&(de(e,n),A()),!r.length)throw Error(i===`unknown`?`fs: cloud unreachable`:`fs: no storage backend available`);x(e),await Promise.all(r)},N=async e=>{let t=a.o(),n=await a.h(e,{pin:t});return await d()&&await s.o(e,n),n},P=null,Ce=e=>(P=e,()=>{P===e&&(P=null)}),we=async e=>{let n=await(await t.o).cloud.fs.promptConflict({path:e.path,local:e.local,cloud:e.cloud}).catch(()=>null);return n===`local`?e.readLocal():n===`cloud`?e.readCloud():null},Te=async e=>{if(P)try{return await P(e)}catch{return null}return we(e)},F=class extends Error{},I=e=>e instanceof Error?e.message:String(e),Ee=()=>{let e=new Map,t=t=>{let n=e.get(t);return n||e.set(t,n={writes:new Map,deletes:new Map}),n};for(let[e,n]of Object.entries(_(`write`)))t(n.pin).writes.set(e,n.base);for(let[e,n]of Object.entries(_(`delete`)))t(n.pin).deletes.set(e,n.base);return e},De=async()=>{for(let[e,t]of[...y]){let n=e.startsWith(`write:`)?`write`:`delete`,r=e.slice(n.length+1),i;try{i=await a.p(t)}catch(t){a.c(t)&&y.delete(e);continue}if(y.get(e)!==t)continue;y.delete(e);let o=_(n),s=o[r];s&&s.pin===null&&(o[r]={base:s.base,pin:i},v(n,o))}},Oe=async(e,t,n,r,i,o)=>{let c=new Map(t.map(e=>[e.path,e])),l=e=>{if(a.c(e))throw new F};for(let[t,o]of e.deletes){let e=c.get(t);if(!e){S(t);continue}if(r.some(e=>e.path===t)){S(t);continue}if(e.updatedAt!==o){S(t);continue}try{await a._(t,n),S(t),i.deleted.push(t)}catch(e){l(e),i.failed.push({path:t,error:I(e)})}}for(let t of r){let r=c.get(t.path),u=e.writes.has(t.path);if(!u){if(!o(t))continue;if(r){i.kept.push(t.path);continue}}let d=e.writes.get(t.path)??null;if(u&&r&&r.updatedAt!==d){let e=null,o=null,c=await Te({path:t.path,local:{size:t.size,updatedAt:t.updatedAt},cloud:{size:r.size,updatedAt:r.updatedAt},readLocal:()=>e??=s.i(t.path),readCloud:()=>o??=a.h(t.path,n)});if(c==null){i.unresolved.push(t.path);continue}try{let r=e!==null&&c===await e,l=o!==null&&c===await o;l||await a.b(t.path,c,t.contentType?{contentType:t.contentType,...n}:n),r||await s.o(t.path,c),x(t.path),i.resolved.push({path:t.path,choice:r?`local`:l?`cloud`:`merged`})}catch(e){if(l(e),e?.code===`FKN_E2E_LOCKED`)throw e;i.failed.push({path:t.path,error:I(e)})}continue}try{let e=await s.i(t.path);await a.b(t.path,e,t.contentType?{contentType:t.contentType,...n}:n),x(t.path),i.uploaded.push(t.path)}catch(e){if(u||b(t.path,r?.updatedAt??null,n.pin),l(e),e?.code===`FKN_E2E_LOCKED`)throw e;i.failed.push({path:t.path,error:I(e)})}}},ke=async(e,t)=>{let n={uploaded:[],kept:[],resolved:[],unresolved:[],deleted:[],failed:[]},r=await f();if(r===`unknown`)throw Error(`fs: cloud unreachable`);if(r!==`connected`)throw Error(`fs: this needs a signed-in account`);let i=await d(),o=i?await s.n():[];if(i)for(let e of Object.keys(_(`write`)))o.some(t=>t.path===e)||x(e);await De();for(let[e,r]of Ee()){if(e===null||he(e))continue;let i={pin:{pin:e}},s;try{s=await a.f(i)}catch(n){if(a.c(n)){C.set(e,t.generation);continue}if(a.l(n)){Ae(e);continue}throw n}try{await Oe(r,s,i,o,n,()=>!1)}catch(n){if(!(n instanceof F))throw n;C.set(e,t.generation)}}if(e){let e={pin:t},r=await a.f(e),i=_(`write`),s=Ee().get(null)??{writes:new Map,deletes:new Map},c=new Set([...n.uploaded,...n.resolved.map(({path:e})=>e),...n.unresolved,...n.failed.map(({path:e})=>e)]),l=e=>!(e.path in i)&&!c.has(e.path);try{await Oe(s,r,e,o,n,l)}catch(e){throw e instanceof F?new a.t:e}}return n},Ae=e=>{for(let t of[`write`,`delete`]){let n=_(t),r=!1;for(let t of Object.values(n))t.pin===e&&(t.pin=null,r=!0);r&&v(t,n)}},je=async e=>{for(;w;)await w;let t=ke(!0,e);w=t.then(()=>{},()=>{});try{return await t}finally{w=null,ve()}},L=()=>je(a.o()),R=(e,t)=>{let n=new Set(t.map(e=>e.path)),r=_(`write`);return e.filter(e=>{let t=r[e.path];return t?ge(`write`,e.path,t):!n.has(e.path)})},z=async()=>{let e=a.o();if(!await p()||!await d())return{paths:[],bytes:0};let[t,n]=await Promise.all([s.n(),a.f({pin:e})]),r=R(t,n);return{paths:r.map(e=>e.path),bytes:r.reduce((e,t)=>e+t.size,0)}},Me=()=>new Set(Object.keys(se())),Ne=e=>{let t=se();for(let n of e)t[n]=null;try{localStorage.setItem(re,JSON.stringify(t))}catch{}},B=null,V=!1,H=e=>{if(B)return V=!0,B;let n=e?.from??a.o();return B=(async()=>{if(!await p())return;let r=e??(await d()?{local:await s.n(),remote:await a.f({pin:n})}:null);if(!r)return;let i=Me(),o=R(r.local,r.remote).filter(e=>!i.has(e.path));if(!o.length)return;let c=await t.o,l=o.reduce((e,t)=>e+t.size,0);if(!await c.cloud.fs.promptAdopt({files:o.length,bytes:l}).catch(()=>!1)){Ne(o.map(e=>e.path));return}`generation`in n&&await je(n)})().catch(()=>{}).finally(()=>{B=null,V&&(V=!1,H())}),B},Pe=null,Fe=!1,Ie=async(e,n)=>{let r=R(e,n),i=await t.o,a=async()=>{await L().catch(()=>{});let e=await z().catch(()=>({paths:[],bytes:0}));await i.cloud.fs.setAdoptSource({files:e.paths.length,bytes:e.bytes},a).catch(()=>{})},o={files:r.length,bytes:r.reduce((e,t)=>e+t.size,0)};Pe=()=>{i.cloud.fs.setAdoptSource(o,a).catch(()=>{})},Fe||(Fe=!0,t.u((e,t)=>{t>1&&Pe?.()})),await i.cloud.fs.setAdoptSource(o,a)},Le=!1,U=()=>{Le||typeof window>`u`||(Le=!0,window.addEventListener(`online`,()=>{j()}),o.onChange(()=>{H().catch(()=>{}),j()}).catch(()=>{}))},Re=e.t({STORAGE_ACCOUNT_CHANGED:()=>i.STORAGE_ACCOUNT_CHANGED,STORAGE_ACCOUNT_PIN_UNSUPPORTED:()=>i.STORAGE_ACCOUNT_PIN_UNSUPPORTED,StorageAccountChangedError:()=>a.t,StorageAccountPinUnsupportedError:()=>a.n,adopt:()=>q,adoptable:()=>J,appendFile:()=>tt,appendFileSync:()=>Ue,available:()=>Be,default:()=>$,exists:()=>ct,existsSync:()=>We,flush:()=>W,isAccountChanged:()=>a.c,lstatSync:()=>Ke,mkdir:()=>it,mkdirSync:()=>Je,mount:()=>ut,onConflict:()=>Q,pending:()=>Y,pendingDeletes:()=>X,promises:()=>lt,pull:()=>G,readFile:()=>$e,readFileSealed:()=>K,readFileSync:()=>Ve,readdir:()=>rt,readdirSync:()=>qe,remount:()=>dt,rename:()=>st,renameSync:()=>Qe,replicating:()=>Z,rm:()=>at,rmSync:()=>Ye,rmdirSync:()=>Xe,stat:()=>nt,statSync:()=>Ge,unlink:()=>ot,unlinkSync:()=>Ze,writeFile:()=>et,writeFileSync:()=>He}),ze=r.t(c,{memfs:!0}),{available:Be,readFileSync:Ve,writeFileSync:He,appendFileSync:Ue,existsSync:We,statSync:Ge,lstatSync:Ke,readdirSync:qe,mkdirSync:Je,rmSync:Ye,rmdirSync:Xe,unlinkSync:Ze,renameSync:Qe,readFile:$e,writeFile:et,appendFile:tt,stat:nt,readdir:rt,mkdir:it,rm:at,unlink:ot,rename:st,exists:ct,promises:lt,mount:ut,flush:W,remount:dt}=ze,G=N,K=M,q=L,J=z,Y=fe,X=pe,Z=me,Q=Ce,$={...ze,pull:G,readFileSealed:K,adopt:q,adoptable:J,pending:Y,pendingDeletes:X,replicating:Z,onConflict:Q};Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return Ye}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return rt}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return Qe}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return st}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return Ze}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return et}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return nt}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return Ge}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return ot}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return dt}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return $e}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return it}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return Xe}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return at}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return ut}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return ct}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return Je}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return tt}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return We}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return lt}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return G}});
package/links.cjs DELETED
@@ -1 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./rolldown-runtime-BIInC43l.cjs"),t=require("./api-DMnVye0K.cjs"),n=require("./contract.cjs"),r=require("./account-generation-9VhfEDoW.cjs"),i=require("./storage-DmRIhg1P.cjs");var a=e.t({LINK_EXPIRES_MS:()=>n.LINK_EXPIRES_MS,available:()=>_,create:()=>v,list:()=>x,open:()=>b,revoke:()=>S}),o={notALink:`links: the link is not one fkn.app made`,badExpiry:`links: the expiry is not one a link can carry`,notAFile:`links: the file is not a Blob or a ReadableStream`,badSize:`links: a stream needs the size it will deliver, a whole number of bytes`,badName:`links: the name or type is not one a link can carry`,tooLarge:`links: the file is too large for a link`,shortStream:`links: the stream did not deliver the size it declared`,badKey:`links: the key is not 32 bytes base64url`,keyTaken:`links: the key already names a link`,gone:`links: the link is no longer available`,integrity:`links: the file does not match its link`,needsAccount:`links: making a link needs an account`,notCreator:`links: only the app that made the link can revoke it`,quota:`links: storage quota exceeded`,tooMany:`links: too many links`,tooManyThisHour:`links: too many links made this hour, try again later`,rateLimited:`links: this link is opened too often, try again later`,accountChanged:`links: the signed-in account changed`,unavailable:`links: links are unavailable`},s=new Map([[o.notALink,`invalid`],[o.badExpiry,`invalid`],[o.notAFile,`invalid`],[o.badSize,`invalid`],[o.badName,`invalid`],[o.tooLarge,`invalid`],[o.shortStream,`invalid`],[o.badKey,`invalid`],[o.keyTaken,`invalid`],[o.gone,`not-found`],[o.integrity,`integrity`],[o.needsAccount,`denied`],[o.notCreator,`denied`],[o.quota,`quota`],[o.tooMany,`too-many`],[o.tooManyThisHour,`too-many`],[o.rateLimited,`rate-limited`],[o.accountChanged,`account-changed`],[o.unavailable,`unavailable`]]),c=new Set(s.values()),l=(e,t)=>Object.assign(Error(t),{code:e}),u=e=>e instanceof Error&&c.has(e.code),d=e=>{if(u(e))return e;let t=e instanceof Error?e.message:``,n=s.get(t);return n?l(n,t):l(`unavailable`,o.unavailable)},f=async()=>{if(!t.l)return;let e=(await t.s(`a link`).catch(()=>void 0))?.links;return typeof e?.create==`function`?e:void 0},p=()=>{throw l(`unavailable`,o.unavailable)},m=e=>typeof e==`object`&&!!e&&typeof e.error==`string`&&typeof e.message==`string`,h=(e,t,n)=>{throw e.error===`aborted`?t?.reason??new DOMException(`The operation was aborted.`,`AbortError`):(e.error===`account-changed`&&n&&r.r(n.generation),c.has(e.error)?l(e.error,e.message):l(`unavailable`,o.unavailable))},g=async e=>{try{return await i.p(e)}catch(e){throw i.c(e)?l(`account-changed`,o.accountChanged):e instanceof Error&&/not connected|not signed in/i.test(e.message)?l(`denied`,o.needsAccount):l(`unavailable`,o.unavailable)}},_=async()=>{let e=await f();return e?Promise.resolve(e.available()).catch(()=>!1):!1},v=async(e,t={})=>{let r=i.o(),a=Date.now(),{signal:s,onProgress:c,key:u}=t;s?.throwIfAborted();let d=typeof Blob<`u`&&e instanceof Blob,_=typeof ReadableStream<`u`&&e instanceof ReadableStream;if(!d&&!_)throw l(`invalid`,o.notAFile);let v=d?e.size:t.size;if(typeof v!=`number`||!Number.isSafeInteger(v)||v<0||d&&t.size!==void 0&&t.size!==v)throw l(`invalid`,o.badSize);let y=t.name??(typeof File<`u`&&e instanceof File?e.name:``),b=t.type??(d?e.type:``);if(typeof y!=`string`||typeof b!=`string`)throw l(`invalid`,o.badName);let x=typeof File<`u`&&e instanceof File?e.lastModified:a,S=t.expires,C;if(S!=null&&(typeof S!=`number`||!Number.isFinite(S)||(C=Math.round(S-a),C<n.LINK_EXPIRES_MS.min||C>n.LINK_EXPIRES_MS.max)))throw l(`invalid`,o.badExpiry);if(c!==void 0&&typeof c!=`function`)throw l(`invalid`,o.notAFile);let w=await f();if(!w)throw l(`unavailable`,o.unavailable);let T=await g(r);s?.throwIfAborted();let E=Promise.resolve(w.create(e,{name:y,type:b,lastModified:x,size:v,...C===void 0?{}:{expiresIn:C},...u===void 0?{}:{key:u},accountPin:T,...s?{signal:s}:{},...c?{onProgress:e=>{try{c(e)}catch{}}}:{}})).catch(p);E.catch(()=>{});let D=s?await Promise.race([E,new Promise((e,t)=>s.addEventListener(`abort`,()=>t(s.reason),{once:!0}))]):await E;return m(D)?h(D,s,r):D},y=(e,t,n)=>{let r=(t,n)=>{if(t===void 0)return n;let r=Math.trunc(Number.isFinite(t)?t:t>0?e:-e);return r<0?Math.max(e+r,0):Math.min(r,e)},i=r(t,0);return{from:i,to:Math.max(i,r(n,e))}},b=async(e,n={})=>{if(typeof e!=`string`)throw l(`invalid`,o.notALink);let{signal:r}=n;r?.throwIfAborted();let i=async()=>{let n=await f();if(!n)throw l(`unavailable`,o.unavailable);let i=t.c()?.epoch,a=await Promise.resolve(n.open(e,r?{signal:r}:void 0)).catch(p);return m(a)?h(a,r):{handle:a,epoch:i}},a=await i(),s=async()=>{let e=t.c()?.epoch;return a.epoch!==void 0&&e!==void 0&&e!==a.epoch&&(a=await i()),a.handle},{name:c,type:u,size:g,lastModified:_}=a.handle,v=(e,t)=>{let n;return new ReadableStream({pull:async r=>{try{if(!n){let r=await s(),i=await Promise.resolve(r.read(e,t)).catch(p);if(m(i))return h(i);n=i.getReader()}let{value:i,done:a}=await n.read();a?r.close():r.enqueue(i)}catch(e){throw d(e)}},cancel:e=>n?.cancel(e)},{highWaterMark:0})},b=(e,t)=>({name:c,type:u,size:t-e,lastModified:_,stream:()=>v(e,t),arrayBuffer:async()=>{let n=new Uint8Array(t-e),r=v(e,t).getReader(),i=0;for(;;){let{value:e,done:t}=await r.read();if(t)break;n.set(e,i),i+=e.length}return n.buffer},slice:(n,r)=>{let i=y(t-e,n,r);return b(e+i.from,e+i.to)}});return b(0,g)},x=async()=>{let e=i.o(),t=await f();if(!t)throw l(`unavailable`,o.unavailable);let n=await g(e),r=await Promise.resolve(t.list({accountPin:n})).catch(p);return m(r)?h(r,void 0,e):r.links},S=async e=>{let t=i.o();if(typeof e!=`string`||!e)throw l(`invalid`,o.notALink);let n=await f();if(!n)throw l(`unavailable`,o.unavailable);let r=await g(t),a=await Promise.resolve(n.revoke(e,{accountPin:r})).catch(p);m(a)&&h(a,void 0,t)};exports.LINK_EXPIRES_MS=n.LINK_EXPIRES_MS,exports.available=_,exports.create=v,exports.list=x,exports.open=b,exports.revoke=S,Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
package/links.d.ts DELETED
@@ -1,65 +0,0 @@
1
- import { A as Link, F as LinksErrorCode, L as ListedLink, P as LinkProgress, j as LinkCreateOptions, k as LINK_EXPIRES_MS } from "./contract-XlEPwc7b.js";
2
- declare namespace links_d_exports {
3
- export { LINK_EXPIRES_MS, Link, LinkCreateOptions, LinkProgress, LinkedFile, LinksError, LinksErrorCode, ListedLink, available, create, list, open, revoke };
4
- }
5
- /** Thrown by every member of this namespace except on an aborted signal. Match on `code`, never on the message. */
6
- export type LinksError = Error & {
7
- code: LinksErrorCode;
8
- };
9
- /**
10
- * The file an opened link names, shaped like a `File`: the same four fields, `stream`, `arrayBuffer`
11
- * and `slice`. Every read is by range and each 1 MiB record is checked before it is handed over, so a
12
- * `slice` near the end of a large file fetches only that end.
13
- */
14
- export type LinkedFile = {
15
- name: string;
16
- type: string;
17
- size: number;
18
- lastModified: number;
19
- /** errors with `integrity` on the first record that is not what the link sealed */
20
- stream: () => ReadableStream<Uint8Array>;
21
- arrayBuffer: () => Promise<ArrayBuffer>;
22
- /** `Blob.slice`'s arguments, negative ones counted from the end, and the same shape back */
23
- slice: (start?: number, end?: number) => LinkedFile;
24
- };
25
- /** Whether a link can be made here now. Opening needs no account and does not depend on this. Answers rather than rejecting. */
26
- export declare const available: () => Promise<boolean>;
27
- /**
28
- * Seals a file in the broker and uploads it, then answers its link. Needs a signed-in account, and
29
- * counts the sealed size (28 bytes more per 1 MiB) against the account's storage from the moment it
30
- * starts until the link is revoked, expires or the upload is aborted. The account the call belongs to
31
- * is the one this page is on when it is made, as for every storage call.
32
- *
33
- * `data` is a `Blob` (a `File` included) or a `ReadableStream<Uint8Array>` with its `size`. An upload
34
- * survives the network dropping a part, not a reload: a reload starts the file again, and the upload
35
- * left behind stops counting within the hour, or at once from `revoke` or the account's settings.
36
- *
37
- * Refused `invalid` for an expiry outside `LINK_EXPIRES_MS`, a stream without its size or one that
38
- * delivers another, a file past the service's part ceiling, a `key` that is not 32 bytes base64url or
39
- * one that already names a link; `denied` with no account; `quota`; `too-many` past the account's live
40
- * links or this hour's creations; `account-changed`.
41
- */
42
- export declare const create: (data: Blob | ReadableStream<Uint8Array>, options?: LinkCreateOptions) => Promise<Link>;
43
- /**
44
- * Opens a link made by any app, with no account: the broker reads the key from the link and fetches
45
- * the sealed file by range. Refused `invalid` for a link fkn.app did not make, `not-found` for one
46
- * that is missing, revoked, expired, still uploading or turned off (one answer for all of them),
47
- * `integrity` when the file does not match its link, `rate-limited` past the link's daily opens.
48
- *
49
- * Opening counts once per viewer per link per day; reading the same opened file again, by `slice` or
50
- * a second `stream()`, counts nothing more. A broker replaced while the file is held is asked to open
51
- * it again on the next read.
52
- */
53
- export declare const open: (url: string, options?: {
54
- signal?: AbortSignal;
55
- }) => Promise<LinkedFile>;
56
- /** This app's links, newest first, uploads in progress included, as the service holds them: no name and no url. */
57
- export declare const list: () => Promise<ListedLink[]>;
58
- /**
59
- * Revokes a link by its url or its id: every copy of the link stops opening, and an upload in
60
- * progress is aborted and stops counting. Only the app that made the link (the same app once it is
61
- * verified) revokes it, `denied` otherwise. A link already gone resolves.
62
- */
63
- export declare const revoke: (target: string) => Promise<void>;
64
- //#endregion
65
- export { LINK_EXPIRES_MS, type Link, type LinkCreateOptions, type LinkProgress, type LinksErrorCode, type ListedLink, links_d_exports as t };