@asaidimu/hestia 1.16.0 → 1.16.2
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/README.md +12 -0
- package/index.cjs +4 -4
- package/index.d.cts +21 -7
- package/index.d.mts +19 -7
- package/index.mjs +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -55,6 +55,18 @@ pager.subscribe((page) => console.log("Page:", page.page.number))
|
|
|
55
55
|
await pager.resize(25, 1)
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
+
### Graceful shutdown
|
|
59
|
+
|
|
60
|
+
In Node, call `close()` before the process exits. It stops the auto-heartbeat
|
|
61
|
+
timer, closes the cross-tab auth channel, aborts open streams and flushes/closes
|
|
62
|
+
the persistence adapter. It is safe to call more than once.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const api = new HestiaClient({ baseUrl: "http://localhost:8070" })
|
|
66
|
+
// ... work ...
|
|
67
|
+
await api.close()
|
|
68
|
+
```
|
|
69
|
+
|
|
58
70
|
## API
|
|
59
71
|
|
|
60
72
|
### `HestiaClient`
|
package/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@asaidimu/network-client"),t=require("@asaidimu/utils-error"),n=require("@asaidimu/utils-sync"),r=require("@asaidimu/utils-store"),i=require("@asaidimu/query");async function a(e){try{return(await e.clone().json())?.error??null}catch{return null}}function o(e,n){if(n)return new t.SystemError({code:n.code??`UNKNOWN`,message:n.message??`Unknown error`,issues:n.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new t.SystemError({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new t.SystemError({code:`UNKNOWN`,message:r??`Unknown error`})}function s(e){return t.Errors.notFound(e)}function c(e){return t.Errors.permissionDenied(e)}function l(e){return t.Errors.internalError(e)}const u={"system:apikeys:key:create":{method:`POST`,route:`/system/apikeys/key/create`,arguments:[]},"system:apikeys:key:delete":{method:`DELETE`,route:`/system/apikeys/key/delete/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:get":{method:`GET`,route:`/system/apikeys/key/get/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:list":{method:`GET`,route:`/system/apikeys/key/list`,arguments:[]},"system:apikeys:key:rotate":{method:`POST`,route:`/system/apikeys/key/rotate/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:update":{method:`PATCH`,route:`/system/apikeys/key/update/{key_id}`,arguments:[`key_id`]},"system:audit:log:export":{method:`PATCH`,route:`/system/audit/log/export`,arguments:[]},"system:audit:log:stream":{method:`GET`,route:`/system/audit/log/stream`,arguments:[]},"system:auth:bootstrap:password:set":{method:`PATCH`,route:`/system/auth/bootstrap/password/set`,arguments:[]},"system:auth:password:confirm":{method:`PATCH`,route:`/system/auth/password/confirm`,arguments:[]},"system:auth:password:reset":{method:`POST`,route:`/system/auth/password/reset`,arguments:[]},"system:auth:session:create":{method:`POST`,route:`/system/auth/session/create`,arguments:[]},"system:auth:session:delete":{method:`DELETE`,route:`/system/auth/session/delete`,arguments:[]},"system:auth:session:get":{method:`GET`,route:`/system/auth/session/get`,arguments:[]},"system:auth:token:elevate":{method:`POST`,route:`/system/auth/token/elevate`,arguments:[]},"system:blobs:blob:abort":{method:`POST`,route:`/system/blobs/blob/abort/{ns}`,arguments:[`ns`]},"system:blobs:blob:begin":{method:`POST`,route:`/system/blobs/blob/begin/{ns}`,arguments:[`ns`]},"system:blobs:blob:chunk":{method:`POST`,route:`/system/blobs/blob/chunk/{ns}`,arguments:[`ns`]},"system:blobs:blob:complete":{method:`POST`,route:`/system/blobs/blob/complete/{ns}`,arguments:[`ns`]},"system:blobs:blob:delete":{method:`DELETE`,route:`/system/blobs/blob/delete/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:download":{method:`GET`,route:`/system/blobs/blob/download/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:head":{method:`POST`,route:`/system/blobs/blob/head/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:list":{method:`POST`,route:`/system/blobs/blob/list/{ns}`,arguments:[`ns`]},"system:blobs:blob:progress":{method:`POST`,route:`/system/blobs/blob/progress/{ns}`,arguments:[`ns`]},"system:blobs:blob:rename":{method:`PATCH`,route:`/system/blobs/blob/rename/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:update":{method:`PATCH`,route:`/system/blobs/blob/update/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:upload":{method:`POST`,route:`/system/blobs/blob/upload/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:namespace:compact":{method:`POST`,route:`/system/blobs/namespace/compact/{ns}`,arguments:[`ns`]},"system:blobs:namespace:create":{method:`POST`,route:`/system/blobs/namespace/create/{ns}`,arguments:[`ns`]},"system:blobs:namespace:delete":{method:`DELETE`,route:`/system/blobs/namespace/delete/{ns}`,arguments:[`ns`]},"system:blobs:namespace:list":{method:`POST`,route:`/system/blobs/namespace/list`,arguments:[]},"system:blobs:namespace:stats":{method:`POST`,route:`/system/blobs/namespace/stats/{ns}`,arguments:[`ns`]},"system:blobs:namespace:verify":{method:`POST`,route:`/system/blobs/namespace/verify/{ns}`,arguments:[`ns`]},"system:collections:audit_log:query":{method:`POST`,route:`/system/collections/audit_log/query`,arguments:[]},"system:collections:collection:create":{method:`POST`,route:`/system/collections/collection/create`,arguments:[]},"system:collections:collection:delete":{method:`DELETE`,route:`/system/collections/collection/delete/{name}`,arguments:[`name`]},"system:collections:collection:get":{method:`GET`,route:`/system/collections/collection/get/{name}`,arguments:[`name`]},"system:collections:collection:list":{method:`GET`,route:`/system/collections/collection/list`,arguments:[]},"system:collections:document:create":{method:`POST`,route:`/system/collections/document/create/{name}`,arguments:[`name`]},"system:collections:document:delete":{method:`DELETE`,route:`/system/collections/document/delete/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:get":{method:`GET`,route:`/system/collections/document/get/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:query":{method:`POST`,route:`/system/collections/document/query/{name}`,arguments:[`name`]},"system:collections:document:update":{method:`PATCH`,route:`/system/collections/document/update/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:update_many":{method:`PATCH`,route:`/system/collections/document/update_many/{name}`,arguments:[`name`]},"system:collections:operation_policy:query":{method:`POST`,route:`/system/collections/operation_policy/query`,arguments:[]},"system:collections:user:query":{method:`POST`,route:`/system/collections/user/query`,arguments:[]},"system:collections:view:create":{method:`POST`,route:`/system/collections/view/create/{name}`,arguments:[`name`]},"system:collections:view:refresh":{method:`PATCH`,route:`/system/collections/view/refresh/{name}`,arguments:[`name`]},"system:core:capability:list":{method:`GET`,route:`/system/core/capability/list`,arguments:[]},"system:core:capability:set":{method:`PATCH`,route:`/system/core/capability/set/{name}`,arguments:[`name`]},"system:core:docs:list":{method:`GET`,route:`/system/core/docs/list`,arguments:[]},"system:core:health:check":{method:`GET`,route:`/system/core/health/check`,arguments:[]},"system:core:heartbeat":{method:`GET`,route:`/system/core/heartbeat`,arguments:[]},"system:core:reset":{method:`DELETE`,route:`/system/core/reset`,arguments:[]},"system:logs:list":{method:`POST`,route:`/system/logs/list`,arguments:[]},"system:logs:stream":{method:`GET`,route:`/system/logs/stream`,arguments:[]},"system:notifications:notification:create":{method:`POST`,route:`/system/notifications/notification/create`,arguments:[]},"system:notifications:notification:list":{method:`GET`,route:`/system/notifications/notification/list`,arguments:[]},"system:notifications:notification:read":{method:`PATCH`,route:`/system/notifications/notification/read/{notification_id}`,arguments:[`notification_id`]},"system:notifications:notification:stream":{method:`GET`,route:`/system/notifications/notification/stream`,arguments:[]},"system:notifications:read:all":{method:`PATCH`,route:`/system/notifications/read/all`,arguments:[]},"system:notifications:unread:count":{method:`GET`,route:`/system/notifications/unread/count`,arguments:[]},"system:policies:binding:get":{method:`GET`,route:`/system/policies/binding/get/{name}`,arguments:[`name`]},"system:policies:binding:list":{method:`GET`,route:`/system/policies/binding/list`,arguments:[]},"system:policies:policy:create":{method:`POST`,route:`/system/policies/policy/create/{name}`,arguments:[`name`]},"system:policies:policy:list":{method:`GET`,route:`/system/policies/policy/list`,arguments:[]},"system:policies:policy:update":{method:`PATCH`,route:`/system/policies/policy/update/{name}`,arguments:[`name`]},"system:policies:reload":{method:`GET`,route:`/system/policies/reload`,arguments:[]},"system:policies:rule:create":{method:`POST`,route:`/system/policies/rule/create/{name}`,arguments:[`name`]},"system:policies:rule:delete":{method:`DELETE`,route:`/system/policies/rule/delete/{name}`,arguments:[`name`]},"system:policies:rule:get":{method:`GET`,route:`/system/policies/rule/get/{name}`,arguments:[`name`]},"system:policies:rule:list":{method:`GET`,route:`/system/policies/rule/list`,arguments:[]},"system:policies:rule:update":{method:`PATCH`,route:`/system/policies/rule/update/{name}`,arguments:[`name`]},"system:policies:rule:validate":{method:`POST`,route:`/system/policies/rule/validate`,arguments:[]},"system:scheduler:job:list":{method:`GET`,route:`/system/scheduler/job/list`,arguments:[]},"system:schedules:schedule:all":{method:`GET`,route:`/system/schedules/schedule/all`,arguments:[]},"system:schedules:schedule:create":{method:`POST`,route:`/system/schedules/schedule/create`,arguments:[]},"system:schedules:schedule:delete":{method:`DELETE`,route:`/system/schedules/schedule/delete/{id}`,arguments:[`id`]},"system:schedules:schedule:get":{method:`GET`,route:`/system/schedules/schedule/get/{id}`,arguments:[`id`]},"system:schedules:schedule:list":{method:`GET`,route:`/system/schedules/schedule/list`,arguments:[]},"system:schedules:schedule:update":{method:`PATCH`,route:`/system/schedules/schedule/update/{id}`,arguments:[`id`]},"system:settings:delete":{method:`DELETE`,route:`/system/settings/delete/{key}`,arguments:[`key`]},"system:settings:get":{method:`GET`,route:`/system/settings/get/{key}`,arguments:[`key`]},"system:settings:list":{method:`GET`,route:`/system/settings/list`,arguments:[]},"system:settings:set":{method:`POST`,route:`/system/settings/set/{key}`,arguments:[`key`]},"system:updates:changelog:get":{method:`GET`,route:`/system/updates/changelog/get`,arguments:[]},"system:updates:check:create":{method:`POST`,route:`/system/updates/check/create`,arguments:[]},"system:updates:check:get":{method:`GET`,route:`/system/updates/check/get`,arguments:[]},"system:updates:stage:create":{method:`POST`,route:`/system/updates/stage/create`,arguments:[]},"system:updates:status:get":{method:`GET`,route:`/system/updates/status/get`,arguments:[]},"system:updates:update:apply":{method:`POST`,route:`/system/updates/update/apply`,arguments:[]},"system:updates:update:discard":{method:`DELETE`,route:`/system/updates/update/discard`,arguments:[]},"system:users:password:change":{method:`PATCH`,route:`/system/users/password/change/{user_id}`,arguments:[`user_id`]},"system:users:user:create":{method:`POST`,route:`/system/users/user/create`,arguments:[]},"system:users:user:delete":{method:`DELETE`,route:`/system/users/user/delete/{user_id}`,arguments:[`user_id`]},"system:users:user:get":{method:`GET`,route:`/system/users/user/get/{user_id}`,arguments:[`user_id`]},"system:users:user:update":{method:`PATCH`,route:`/system/users/user/update/{user_id}`,arguments:[`user_id`]},"system:workflows:definition:compile":{method:`POST`,route:`/system/workflows/definition/compile`,arguments:[]},"system:workflows:definition:create":{method:`POST`,route:`/system/workflows/definition/create`,arguments:[]},"system:workflows:definition:delete":{method:`DELETE`,route:`/system/workflows/definition/delete/{id}`,arguments:[`id`]},"system:workflows:definition:get":{method:`GET`,route:`/system/workflows/definition/get/{id}`,arguments:[`id`]},"system:workflows:definition:list":{method:`GET`,route:`/system/workflows/definition/list`,arguments:[]},"system:workflows:definition:update":{method:`PATCH`,route:`/system/workflows/definition/update/{id}`,arguments:[`id`]},"system:workflows:registry:get":{method:`GET`,route:`/system/workflows/registry/get/{kind}`,arguments:[`kind`]},"system:workflows:registry:handles":{method:`GET`,route:`/system/workflows/registry/handles`,arguments:[]},"system:workflows:registry:list":{method:`GET`,route:`/system/workflows/registry/list`,arguments:[]},"system:workflows:run:events":{method:`GET`,route:`/system/workflows/run/events/{run_id}`,arguments:[`run_id`]},"system:workflows:run:get":{method:`GET`,route:`/system/workflows/run/get/{run_id}`,arguments:[`run_id`]},"system:workflows:run:list":{method:`GET`,route:`/system/workflows/run/list`,arguments:[]},"system:workflows:run:outcome":{method:`GET`,route:`/system/workflows/run/outcome/{run_id}`,arguments:[`run_id`]},"system:workflows:run:store":{method:`GET`,route:`/system/workflows/run/store/{run_id}`,arguments:[`run_id`]},"system:workflows:run:stream":{method:`GET`,route:`/system/workflows/run/stream/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:abort":{method:`DELETE`,route:`/system/workflows/runtime/abort/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:events":{method:`POST`,route:`/system/workflows/runtime/events`,arguments:[]},"system:workflows:runtime:has":{method:`GET`,route:`/system/workflows/runtime/has/{id}`,arguments:[`id`]},"system:workflows:runtime:invoke":{method:`POST`,route:`/system/workflows/runtime/invoke`,arguments:[]},"system:workflows:runtime:list":{method:`GET`,route:`/system/workflows/runtime/list`,arguments:[]},"system:workflows:runtime:resume":{method:`POST`,route:`/system/workflows/runtime/resume`,arguments:[]},"system:workflows:runtime:run":{method:`POST`,route:`/system/workflows/runtime/run`,arguments:[]}};var d=class{data;status;constructor(e,t){this.data=e,this.status=t}},f=class{baseUrl;apiPrefix;onAuthStateChanged;defaultHeaders;raw;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.onAuthStateChanged=r,this.defaultHeaders=i,this.raw=(0,e.createNetworkClient)({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`,...this.defaultHeaders?{defaultHeaders:this.defaultHeaders}:{}})}substituteArgs(e,t){return e.replace(/\{(\w+)(\*)?\}/g,(e,n,r)=>t[n]?r?t[n].split(`/`).map(encodeURIComponent).join(`/`):encodeURIComponent(t[n]):`{${n}}`)}async dispatch(e,n){let r=u[e];if(!r)throw new t.SystemError({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});let i=this.substituteArgs(r.route,n?.arguments??{}),a=r.method,o={},s=n?.notifyAuthStateChange??!0;if(n?.headers&&(o.headers=n.headers),n?.responseType&&(o.responseType=n.responseType),n?.bodyType&&(o.bodyType=n.bodyType),n?.signal&&(o.signal=n.signal),n?.modifiers){let e=Object.entries(n.modifiers).flatMap(([e,t])=>(Array.isArray(t)?t:[t]).map(t=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join(`&`);if(e){let t=i.includes(`?`)?`&`:`?`;return this.request(a,`${i}${t}${e}`,n?.payload,o,s)}}return this.request(a,i,n?.payload,o,s)}routeUrl(e,n){let r=u[e];if(!r)throw new t.SystemError({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});return`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(this.substituteArgs(r.route,n??{}))}`}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(){}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,t,n,r,i=!1){let s=this.canonicalPath(t),c={};r?.headers&&(c.headers={...r.headers}),r?.responseType&&(c.responseType=r.responseType),r?.bodyType&&(c.bodyType=r.bodyType),r?.signal&&(c.signal=r.signal),c.headers||={};let l;if(e===`GET`)l=await this.raw.get(s,c);else{let t=r?.bodyType?{type:r.bodyType}:void 0;l=await this.raw[e.toLowerCase()](s,n,c,t)}if(l.success||l.status===204)return new d(l.data,l.status);l.status===401&&i&&this.onAuthStateChanged?.();let u=l.raw?await a(l.raw):null;throw o(l,u)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,t,n){let r={Accept:`text/event-stream`,...this.defaultHeaders??{},...n?.headers??{}},i=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,a;try{a=await fetch(i,{method:`GET`,headers:r,credentials:n?.credentials??`same-origin`,signal:n?.signal})}catch(e){if(e instanceof Error&&e.name===`AbortError`){t.onClose?.();return}t.onError?.(e instanceof Error?e:Error(String(e)));return}if(!a.ok||!a.body){t.onError?.(Error(`Stream request failed with status ${a.status}`));return}t.onOpen?.();let o=a.body.getReader(),s=new TextDecoder,c=``;try{for(;;){let{done:e,value:n}=await o.read();if(e)break;c+=s.decode(n,{stream:!0});let r=c.indexOf(`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@asaidimu/network-client"),t=require("@asaidimu/utils-error"),n=require("@asaidimu/utils-sync"),r=require("@asaidimu/utils-store"),i=require("@asaidimu/query");async function a(e){try{return(await e.clone().json())?.error??null}catch{return null}}function o(e,n){if(n)return new t.SystemError({code:n.code??`UNKNOWN`,message:n.message??`Unknown error`,issues:n.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new t.SystemError({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new t.SystemError({code:`UNKNOWN`,message:r??`Unknown error`})}function s(e){return t.Errors.notFound(e)}function c(e){return t.Errors.permissionDenied(e)}function l(e){return t.Errors.internalError(e)}const u={"system:apikeys:key:create":{method:`POST`,route:`/system/apikeys/key/create`,arguments:[]},"system:apikeys:key:delete":{method:`DELETE`,route:`/system/apikeys/key/delete/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:get":{method:`GET`,route:`/system/apikeys/key/get/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:list":{method:`GET`,route:`/system/apikeys/key/list`,arguments:[]},"system:apikeys:key:rotate":{method:`POST`,route:`/system/apikeys/key/rotate/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:update":{method:`PATCH`,route:`/system/apikeys/key/update/{key_id}`,arguments:[`key_id`]},"system:audit:log:export":{method:`PATCH`,route:`/system/audit/log/export`,arguments:[]},"system:audit:log:stream":{method:`GET`,route:`/system/audit/log/stream`,arguments:[]},"system:auth:bootstrap:password:set":{method:`PATCH`,route:`/system/auth/bootstrap/password/set`,arguments:[]},"system:auth:password:confirm":{method:`PATCH`,route:`/system/auth/password/confirm`,arguments:[]},"system:auth:password:reset":{method:`POST`,route:`/system/auth/password/reset`,arguments:[]},"system:auth:session:create":{method:`POST`,route:`/system/auth/session/create`,arguments:[]},"system:auth:session:delete":{method:`DELETE`,route:`/system/auth/session/delete`,arguments:[]},"system:auth:session:get":{method:`GET`,route:`/system/auth/session/get`,arguments:[]},"system:auth:token:elevate":{method:`POST`,route:`/system/auth/token/elevate`,arguments:[]},"system:blobs:blob:abort":{method:`POST`,route:`/system/blobs/blob/abort/{ns}`,arguments:[`ns`]},"system:blobs:blob:begin":{method:`POST`,route:`/system/blobs/blob/begin/{ns}`,arguments:[`ns`]},"system:blobs:blob:chunk":{method:`POST`,route:`/system/blobs/blob/chunk/{ns}`,arguments:[`ns`]},"system:blobs:blob:complete":{method:`POST`,route:`/system/blobs/blob/complete/{ns}`,arguments:[`ns`]},"system:blobs:blob:delete":{method:`DELETE`,route:`/system/blobs/blob/delete/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:download":{method:`GET`,route:`/system/blobs/blob/download/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:head":{method:`POST`,route:`/system/blobs/blob/head/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:list":{method:`POST`,route:`/system/blobs/blob/list/{ns}`,arguments:[`ns`]},"system:blobs:blob:progress":{method:`POST`,route:`/system/blobs/blob/progress/{ns}`,arguments:[`ns`]},"system:blobs:blob:rename":{method:`PATCH`,route:`/system/blobs/blob/rename/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:update":{method:`PATCH`,route:`/system/blobs/blob/update/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:upload":{method:`POST`,route:`/system/blobs/blob/upload/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:namespace:compact":{method:`POST`,route:`/system/blobs/namespace/compact/{ns}`,arguments:[`ns`]},"system:blobs:namespace:create":{method:`POST`,route:`/system/blobs/namespace/create/{ns}`,arguments:[`ns`]},"system:blobs:namespace:delete":{method:`DELETE`,route:`/system/blobs/namespace/delete/{ns}`,arguments:[`ns`]},"system:blobs:namespace:list":{method:`POST`,route:`/system/blobs/namespace/list`,arguments:[]},"system:blobs:namespace:stats":{method:`POST`,route:`/system/blobs/namespace/stats/{ns}`,arguments:[`ns`]},"system:blobs:namespace:verify":{method:`POST`,route:`/system/blobs/namespace/verify/{ns}`,arguments:[`ns`]},"system:collections:audit_log:query":{method:`POST`,route:`/system/collections/audit_log/query`,arguments:[]},"system:collections:collection:create":{method:`POST`,route:`/system/collections/collection/create`,arguments:[]},"system:collections:collection:delete":{method:`DELETE`,route:`/system/collections/collection/delete/{name}`,arguments:[`name`]},"system:collections:collection:get":{method:`GET`,route:`/system/collections/collection/get/{name}`,arguments:[`name`]},"system:collections:collection:list":{method:`GET`,route:`/system/collections/collection/list`,arguments:[]},"system:collections:document:create":{method:`POST`,route:`/system/collections/document/create/{name}`,arguments:[`name`]},"system:collections:document:delete":{method:`DELETE`,route:`/system/collections/document/delete/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:get":{method:`GET`,route:`/system/collections/document/get/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:query":{method:`POST`,route:`/system/collections/document/query/{name}`,arguments:[`name`]},"system:collections:document:update":{method:`PATCH`,route:`/system/collections/document/update/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:update_many":{method:`PATCH`,route:`/system/collections/document/update_many/{name}`,arguments:[`name`]},"system:collections:operation_policy:query":{method:`POST`,route:`/system/collections/operation_policy/query`,arguments:[]},"system:collections:user:query":{method:`POST`,route:`/system/collections/user/query`,arguments:[]},"system:collections:view:create":{method:`POST`,route:`/system/collections/view/create/{name}`,arguments:[`name`]},"system:collections:view:refresh":{method:`PATCH`,route:`/system/collections/view/refresh/{name}`,arguments:[`name`]},"system:core:capability:list":{method:`GET`,route:`/system/core/capability/list`,arguments:[]},"system:core:capability:set":{method:`PATCH`,route:`/system/core/capability/set/{name}`,arguments:[`name`]},"system:core:docs:list":{method:`GET`,route:`/system/core/docs/list`,arguments:[]},"system:core:health:check":{method:`GET`,route:`/system/core/health/check`,arguments:[]},"system:core:heartbeat":{method:`GET`,route:`/system/core/heartbeat`,arguments:[]},"system:core:reset":{method:`DELETE`,route:`/system/core/reset`,arguments:[]},"system:logs:list":{method:`POST`,route:`/system/logs/list`,arguments:[]},"system:logs:stream":{method:`GET`,route:`/system/logs/stream`,arguments:[]},"system:notifications:notification:create":{method:`POST`,route:`/system/notifications/notification/create`,arguments:[]},"system:notifications:notification:list":{method:`GET`,route:`/system/notifications/notification/list`,arguments:[]},"system:notifications:notification:read":{method:`PATCH`,route:`/system/notifications/notification/read/{notification_id}`,arguments:[`notification_id`]},"system:notifications:notification:stream":{method:`GET`,route:`/system/notifications/notification/stream`,arguments:[]},"system:notifications:read:all":{method:`PATCH`,route:`/system/notifications/read/all`,arguments:[]},"system:notifications:unread:count":{method:`GET`,route:`/system/notifications/unread/count`,arguments:[]},"system:policies:binding:get":{method:`GET`,route:`/system/policies/binding/get/{name}`,arguments:[`name`]},"system:policies:binding:list":{method:`GET`,route:`/system/policies/binding/list`,arguments:[]},"system:policies:policy:create":{method:`POST`,route:`/system/policies/policy/create/{name}`,arguments:[`name`]},"system:policies:policy:list":{method:`GET`,route:`/system/policies/policy/list`,arguments:[]},"system:policies:policy:update":{method:`PATCH`,route:`/system/policies/policy/update/{name}`,arguments:[`name`]},"system:policies:reload":{method:`GET`,route:`/system/policies/reload`,arguments:[]},"system:policies:rule:create":{method:`POST`,route:`/system/policies/rule/create/{name}`,arguments:[`name`]},"system:policies:rule:delete":{method:`DELETE`,route:`/system/policies/rule/delete/{name}`,arguments:[`name`]},"system:policies:rule:get":{method:`GET`,route:`/system/policies/rule/get/{name}`,arguments:[`name`]},"system:policies:rule:list":{method:`GET`,route:`/system/policies/rule/list`,arguments:[]},"system:policies:rule:update":{method:`PATCH`,route:`/system/policies/rule/update/{name}`,arguments:[`name`]},"system:policies:rule:validate":{method:`POST`,route:`/system/policies/rule/validate`,arguments:[]},"system:scheduler:job:list":{method:`GET`,route:`/system/scheduler/job/list`,arguments:[]},"system:schedules:schedule:all":{method:`GET`,route:`/system/schedules/schedule/all`,arguments:[]},"system:schedules:schedule:create":{method:`POST`,route:`/system/schedules/schedule/create`,arguments:[]},"system:schedules:schedule:delete":{method:`DELETE`,route:`/system/schedules/schedule/delete/{id}`,arguments:[`id`]},"system:schedules:schedule:get":{method:`GET`,route:`/system/schedules/schedule/get/{id}`,arguments:[`id`]},"system:schedules:schedule:list":{method:`GET`,route:`/system/schedules/schedule/list`,arguments:[]},"system:schedules:schedule:update":{method:`PATCH`,route:`/system/schedules/schedule/update/{id}`,arguments:[`id`]},"system:settings:delete":{method:`DELETE`,route:`/system/settings/delete/{key}`,arguments:[`key`]},"system:settings:get":{method:`GET`,route:`/system/settings/get/{key}`,arguments:[`key`]},"system:settings:list":{method:`GET`,route:`/system/settings/list`,arguments:[]},"system:settings:set":{method:`POST`,route:`/system/settings/set/{key}`,arguments:[`key`]},"system:updates:changelog:get":{method:`GET`,route:`/system/updates/changelog/get`,arguments:[]},"system:updates:check:create":{method:`POST`,route:`/system/updates/check/create`,arguments:[]},"system:updates:check:get":{method:`GET`,route:`/system/updates/check/get`,arguments:[]},"system:updates:stage:create":{method:`POST`,route:`/system/updates/stage/create`,arguments:[]},"system:updates:status:get":{method:`GET`,route:`/system/updates/status/get`,arguments:[]},"system:updates:update:apply":{method:`POST`,route:`/system/updates/update/apply`,arguments:[]},"system:updates:update:discard":{method:`DELETE`,route:`/system/updates/update/discard`,arguments:[]},"system:users:password:change":{method:`PATCH`,route:`/system/users/password/change/{user_id}`,arguments:[`user_id`]},"system:users:user:create":{method:`POST`,route:`/system/users/user/create`,arguments:[]},"system:users:user:delete":{method:`DELETE`,route:`/system/users/user/delete/{user_id}`,arguments:[`user_id`]},"system:users:user:get":{method:`GET`,route:`/system/users/user/get/{user_id}`,arguments:[`user_id`]},"system:users:user:update":{method:`PATCH`,route:`/system/users/user/update/{user_id}`,arguments:[`user_id`]},"system:workflows:definition:compile":{method:`POST`,route:`/system/workflows/definition/compile`,arguments:[]},"system:workflows:definition:create":{method:`POST`,route:`/system/workflows/definition/create`,arguments:[]},"system:workflows:definition:delete":{method:`DELETE`,route:`/system/workflows/definition/delete/{id}`,arguments:[`id`]},"system:workflows:definition:get":{method:`GET`,route:`/system/workflows/definition/get/{id}`,arguments:[`id`]},"system:workflows:definition:list":{method:`GET`,route:`/system/workflows/definition/list`,arguments:[]},"system:workflows:definition:update":{method:`PATCH`,route:`/system/workflows/definition/update/{id}`,arguments:[`id`]},"system:workflows:registry:get":{method:`GET`,route:`/system/workflows/registry/get/{kind}`,arguments:[`kind`]},"system:workflows:registry:handles":{method:`GET`,route:`/system/workflows/registry/handles`,arguments:[]},"system:workflows:registry:list":{method:`GET`,route:`/system/workflows/registry/list`,arguments:[]},"system:workflows:run:events":{method:`GET`,route:`/system/workflows/run/events/{run_id}`,arguments:[`run_id`]},"system:workflows:run:get":{method:`GET`,route:`/system/workflows/run/get/{run_id}`,arguments:[`run_id`]},"system:workflows:run:list":{method:`GET`,route:`/system/workflows/run/list`,arguments:[]},"system:workflows:run:outcome":{method:`GET`,route:`/system/workflows/run/outcome/{run_id}`,arguments:[`run_id`]},"system:workflows:run:store":{method:`GET`,route:`/system/workflows/run/store/{run_id}`,arguments:[`run_id`]},"system:workflows:run:stream":{method:`GET`,route:`/system/workflows/run/stream/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:abort":{method:`DELETE`,route:`/system/workflows/runtime/abort/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:events":{method:`POST`,route:`/system/workflows/runtime/events`,arguments:[]},"system:workflows:runtime:has":{method:`GET`,route:`/system/workflows/runtime/has/{id}`,arguments:[`id`]},"system:workflows:runtime:invoke":{method:`POST`,route:`/system/workflows/runtime/invoke`,arguments:[]},"system:workflows:runtime:list":{method:`GET`,route:`/system/workflows/runtime/list`,arguments:[]},"system:workflows:runtime:resume":{method:`POST`,route:`/system/workflows/runtime/resume`,arguments:[]},"system:workflows:runtime:run":{method:`POST`,route:`/system/workflows/runtime/run`,arguments:[]}};var d=class{data;status;constructor(e,t){this.data=e,this.status=t}},f=class{baseUrl;apiPrefix;onAuthStateChanged;defaultHeaders;raw;streams=new Set;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.onAuthStateChanged=r,this.defaultHeaders=i,this.raw=(0,e.createNetworkClient)({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`,...this.defaultHeaders?{defaultHeaders:this.defaultHeaders}:{}})}substituteArgs(e,t){return e.replace(/\{(\w+)(\*)?\}/g,(e,n,r)=>t[n]?r?t[n].split(`/`).map(encodeURIComponent).join(`/`):encodeURIComponent(t[n]):`{${n}}`)}async dispatch(e,n){let r=u[e];if(!r)throw new t.SystemError({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});let i=this.substituteArgs(r.route,n?.arguments??{}),a=r.method,o={},s=n?.notifyAuthStateChange??!0;if(n?.headers&&(o.headers=n.headers),n?.responseType&&(o.responseType=n.responseType),n?.bodyType&&(o.bodyType=n.bodyType),n?.signal&&(o.signal=n.signal),n?.modifiers){let e=Object.entries(n.modifiers).flatMap(([e,t])=>(Array.isArray(t)?t:[t]).map(t=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join(`&`);if(e){let t=i.includes(`?`)?`&`:`?`;return this.request(a,`${i}${t}${e}`,n?.payload,o,s)}}return this.request(a,i,n?.payload,o,s)}routeUrl(e,n){let r=u[e];if(!r)throw new t.SystemError({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});return`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(this.substituteArgs(r.route,n??{}))}`}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(){}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,t,n,r,i=!1){let s=this.canonicalPath(t),c={};r?.headers&&(c.headers={...r.headers}),r?.responseType&&(c.responseType=r.responseType),r?.bodyType&&(c.bodyType=r.bodyType),r?.signal&&(c.signal=r.signal),c.headers||={};let l;if(e===`GET`)l=await this.raw.get(s,c);else{let t=r?.bodyType?{type:r.bodyType}:void 0;l=await this.raw[e.toLowerCase()](s,n,c,t)}if(l.success||l.status===204)return new d(l.data,l.status);l.status===401&&i&&this.onAuthStateChanged?.();let u=l.raw?await a(l.raw):null;throw o(l,u)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,t,n){let r=new AbortController,i=n?.signal?AbortSignal.any([r.signal,n.signal]):r.signal;this.streams.add(r);try{let r={Accept:`text/event-stream`,...this.defaultHeaders??{},...n?.headers??{}},a=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,o;try{o=await fetch(a,{method:`GET`,headers:r,credentials:n?.credentials??`same-origin`,signal:i})}catch(e){if(e instanceof Error&&e.name===`AbortError`){t.onClose?.();return}t.onError?.(e instanceof Error?e:Error(String(e)));return}if(!o.ok||!o.body){t.onError?.(Error(`Stream request failed with status ${o.status}`));return}t.onOpen?.();let s=o.body.getReader(),c=new TextDecoder,l=``;try{for(;;){let{done:e,value:n}=await s.read();if(e)break;l+=c.decode(n,{stream:!0});let r=l.indexOf(`
|
|
2
2
|
|
|
3
|
-
`);for(;r!==-1;){let e=
|
|
3
|
+
`);for(;r!==-1;){let e=l.slice(0,r);l=l.slice(r+2);let n=e.split(`
|
|
4
4
|
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());n.length>0&&t.onMessage(n.join(`
|
|
5
|
-
`)),r=
|
|
5
|
+
`)),r=l.indexOf(`
|
|
6
6
|
|
|
7
|
-
`)}}}catch(e){e instanceof Error&&e.name===`AbortError`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}}};const p=f;function m(){let e=[],t=`active`,n=null,r=()=>{if(!n)return;let e=n;n=null,e()},i=n=>{t===`active`&&(e.push(n),r())},a=()=>{t===`active`&&(t=`completed`),r()},o=()=>{t===`active`&&(t=`cancelled`),r()};async function*s(){for(;t===`active`;){if(e.length>0){yield e.shift();continue}await new Promise(r=>{n=r,(e.length>0||t!==`active`)&&(n=null,r())})}for(;e.length>0;)yield e.shift()}return{stream:()=>s(),push:i,end:a,cancel:o,status:()=>t}}function h(){try{let e=window.go;if(!e)return null;for(let t of Object.values(e))for(let e of Object.values(t))if(e?.Dispatch)return e;return null}catch{return null}}function g(){throw new t.SystemError({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var _=class{baseUrl=``;apiPrefix=``;init=new n.Once({throws:!0});config;http;onUnauthorized;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new f(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new f(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new f(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return h()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw g();return this.http.routeUrl(e,t)}async ready(e=1e4){await this.init.do(async()=>{let n=Date.now();for(;!this.resolveService();){if(Date.now()-n>e)throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`Timed out after ${e}ms waiting for Wails bindings on window.go. Are you running inside a Wails desktop window?`});await new Promise(e=>setTimeout(e,50))}},e)}async dispatch(e,r){if(await this.ready(),this.http&&(r?.bodyType===`blob`||r?.bodyType===`stream`))return this.http.dispatch(e,r);let i=r?.notifyAuthStateChange??!0,a=r?.payload??null,o={...r?.modifiers??{}};r?.headers?.[`Content-Type`]&&(o.content_type=r.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:r?.arguments??{},modifiers:o,payload:a})}catch(n){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,n?.message??n),n instanceof t.SystemError?n:new t.SystemError({code:`DISPATCH_ERROR`,message:n?.message??String(n)})}if(c.status>=400){let r=c.data?.error,a=r?.code??`UNKNOWN`,o=r?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&i&&(this.init=new n.Once({throws:!0}),this.onUnauthorized?.()),new t.SystemError({code:a,message:o})}return new d(c.data,c.status)}throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Dispatch binding found on window.go. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}.`})}async check(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw g();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.delete(e,t,n)}async openStream(e,n,r){let i=this.resolveService();try{if(!i?.Stream)throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Stream binding found. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}`});let r=await i.Stream(e),a=`hestia:stream:${e}`;window.runtime?.EventsOn(a,e=>{n.onMessage(typeof e==`string`?e:JSON.stringify(e))}),n.onOpen?.(),r&&n.onMessage(r),n.onClose?.()}catch(e){n.onError?.(e instanceof Error?e:Error(String(e))),n.onClose?.()}}};const v=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),y={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function b(e,t,i,a){let o=i.page??1,s=i.size??20,c=i.sort,l=i.filter,u=new n.Debouncer({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:r.DELETE_SYMBOL,page:{number:1,size:20,count:0,total:0,pages:1}}});let f=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},p=async e=>(await t.set({[d]:{loading:!0,error:r.DELETE_SYMBOL}}),await new Promise(n=>{n(u.do(async()=>{v(()=>{v(async()=>{try{let n=await a(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...y,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??y,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await p({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await p()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await p()},filter:async e=>{l=e,o=1,await p()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),p(e)])},subscribe:e=>m.subscribe(e),invalidate:async()=>{await t.set({[d]:r.DELETE_SYMBOL}),h()},id:()=>d}}const ee=new Set([`id`,`metadata`]);function x(e){return new Proxy(e,{get(e,t,n){if(ee.has(t)&&!(t in e))return t===`id`?()=>e._id_:()=>e._metadata_;let r=Reflect.get(e,t,n);return typeof r==`function`?r.bind(e):r}})}function S(e){return{...e,data:e.data.map(x)}}const te=new Set([`_id_`,`_metadata_`]);function C(e){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return[...e];let t={};for(let[n,r]of Object.entries(e))te.has(n)||(t[n]=r);return t}var w=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=b(t,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.collectionName},payload:e??{}}),n=t.data?.data??[];return S({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.collectionName,doc_id:e}})).data?.data;return t?x(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=await this.client.dispatch(`system:collections:document:create`,{arguments:{name:this.collectionName},payload:C(e.data)});return t.data?x(t.data.data):void 0}async update(e){let t=!!e.id,n=!!e.filter;if(t===n)throw Error(`update requires exactly one of id or filter`);let r=C(e.data);if(n){let t=await this.client.dispatch(`system:collections:document:update_many`,{arguments:{name:this.collectionName},payload:{set:r,filter:e.filter}});return t.data?x(t.data.data):void 0}let i=await this.client.dispatch(`system:collections:document:update`,{arguments:{name:this.collectionName,doc_id:e.id},payload:r});return i.data?x(i.data.data):void 0}async delete(e){await this.client.dispatch(`system:collections:document:delete`,{arguments:{name:this.collectionName,doc_id:e}})}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},T=class e{client;viewName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.viewName=t,this.defaultLimit=n,this.pager=b(t,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}static async create(t,n){return await t.dispatch(`system:collections:view:create`,{arguments:{name:n.name},payload:{query:n.query,materialized:n.materialized??!1}}),new e(t,n.name)}name(){return this.viewName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.viewName},payload:e??{}}),n=t.data?.data??[];return S({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.viewName,doc_id:e}})).data?.data;return t?x(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async refresh(){let e=(await this.client.dispatch(`system:collections:view:refresh`,{arguments:{name:this.viewName}})).data?.data;return e?x(e):void 0}async create(e){throw Error(`Create not supported for views: views are read-only`)}async update(e){throw Error(`Update not supported for views: views are read-only`)}async delete(e){throw Error(`Delete not supported for views: views are read-only`)}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for views`)}async subscribe(e,t){throw Error(`Subscription not implemented for views`)}async notify(e){throw Error(`Notify not implemented for views`)}stream(e,t){throw Error(`Stream not supported for views`)}page(e){return this.pager}},E=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.dispatch(`system:core:health:check`)).data.data}async session(){try{let e=await this.client.dispatch(`system:auth:session:get`,{notifyAuthStateChange:!1});return await this.provider.setIdentity(e.data.data.user),e.data.data}catch(e){if(ne(e))return await this.provider.clear(),null;throw e}}async login(e,t){let n=await this.client.dispatch(`system:auth:session:create`,{payload:{email:e,password:t}});return await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{payload:{email:e,password:t,name:n}})).data.data}async logout(){try{await this.client.dispatch(`system:auth:session:delete`)}catch(e){if(!re(e))throw e}finally{await this.provider.clear()}}async requestPasswordReset(e){await this.client.dispatch(`system:auth:password:reset`,{payload:{email:e}})}async confirmPasswordReset(e,t){await this.client.dispatch(`system:auth:password:confirm`,{payload:{password:t,token:e}})}async bootstrap(e,t,n){await this.client.dispatch(`system:auth:bootstrap:password:set`,{payload:{password:t,email:n},headers:{"X-API-Key":e}})}};function ne(e){return e?.httpStatus===401||e?.code===`UNAUTHORIZED`||e?.code===`UNAUTHENTICATED`||e?.code===`AUTH_REQUIRED`||e?.code===`AUTH-002-UNAUTH`}function re(e){return e?.code===`NO_ACTIVE_SESSION`||ne(e)||e?.message?.includes(`no active session`)}var D=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=b(`users`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections:user:query`,{payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.dispatch(`system:users:user:get`,{arguments:{user_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){if(e.filter)throw Error(`filter-based update not supported for users`);if(!e.id)throw Error(`user id is required for update`);return(await this.client.dispatch(`system:users:user:update`,{arguments:{user_id:e.id},payload:C(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:users:user:delete`,{arguments:{user_id:e}})}async create({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:C(e)})).data.data}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.dispatch(`system:users:password:change`,{arguments:{user_id:e},payload:{current:t,new:n}})}},O=class{client;pager;constructor(e){this.client=e,this.pager=b(`_api_key_`,new r.ReactiveDataStore({}),{},e=>this.find(e))}async find(e){let t=await this.client.dispatch(`system:apikeys:key:list`),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.dispatch(`system:apikeys:key:get`,{arguments:{key_id:e}})).data?.data}catch(e){if(e?.code===`DOCUMENT_NOT_FOUND`||e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.dispatch(`system:apikeys:key:create`,{payload:C(e.data)})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for API keys`);if(!e.id)throw Error(`key id is required for update`);return(await this.client.dispatch(`system:apikeys:key:update`,{arguments:{key_id:e.id},payload:C(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:apikeys:key:delete`,{arguments:{key_id:e}})}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.dispatch(`system:apikeys:key:rotate`,{arguments:{key_id:e}})).data.data}};function k(e){let t=e;return{...e,_id_:t._id_??e.name,_metadata_:t._metadata_??{checksum:``,created:``,updated:``,version:1}}}var A=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>k(e)),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:binding:get`,{arguments:{name:e}});return t.data?.data?k(t.data.data):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},j=class{client;pager;constructor(e){this.client=e,this.pager=b(`policies`,new r.ReactiveDataStore({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.dispatch(`system:collections:operation_policy:query`,{payload:e}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for policies`);let t=e.id;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}},M=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.dispatch(`system:policies:rule:list`)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:rule:get`,{arguments:{name:e}});if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.dispatch(`system:policies:rule:create`,{arguments:{name:t},payload:C(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){if(e.filter)throw Error(`filter-based update not supported for policy rules`);let t=e.id;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.dispatch(`system:policies:rule:update`,{arguments:{name:t},payload:C(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.dispatch(`system:policies:rule:delete`,{arguments:{name:e}})}async validate(e){return(await this.client.dispatch(`system:policies:rule:validate`,{payload:e})).data?.data??{valid:!1}}async reload(){return(await this.client.dispatch(`system:policies:reload`)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},N=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=b(`_audit_log_`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/audit_log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=m(),r=new AbortController,i=!1,a=()=>{i||(i=!0,n.status()===`active`&&this.client.openStream(`/system/audit/log/stream`,{onMessage(e){try{let t=JSON.parse(e);t?.data&&n.push(t.data)}catch{}},onError:()=>n.end(),onClose:()=>n.end()},{signal:r.signal}).catch(()=>n.end()))},o=async function*(){a(),yield*n.stream()};return{stream:()=>o(),cancel:()=>{r.abort(),n.cancel()},status:n.status}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}},P=class{client;baseUrl;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n}async query(e){return(await this.client.post(`/system/logs/list`,e??{})).data?.data??{entries:[],total:0,has_more:!1}}stream(e){let t=m(),n=new AbortController,r=new URLSearchParams;e?.level&&r.set(`level`,e.level);let i=r.toString(),a=`/system/logs/stream${i?`?`+i:``}`,o=!1,s=()=>{o||(o=!0,t.status()===`active`&&this.client.openStream(a,{onMessage(e){try{let n=JSON.parse(e);n?.data&&t.push(n.data)}catch{}},onError:()=>t.end(),onClose:()=>t.end()},{signal:n.signal}).catch(()=>t.end()))},c=async function*(){s(),yield*t.stream()};return{stream:()=>c(),cancel:()=>{n.abort(),t.cancel()},status:t.status}}getStreamUrl(e){let t=new URLSearchParams;e?.level&&t.set(`level`,e.level);let n=t.toString();return`${this.baseUrl}${this.apiPrefix}/system/logs/stream${n?`?`+n:``}`}};const F=.3;function I(e){return new Promise(t=>setTimeout(t,e))}async function L(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function R(e,t,n){return e.slice(t,n)}function z(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function B(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function ie(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var V=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-F)+e*F}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},ae=class{backing;state={jobs:{}};instanceId=z();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},H=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;startedAt=Date.now();blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??z(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new V(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=B(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await I(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await R(this.file,t,i).arrayBuffer();this.blockHashes[r]=await L(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await I(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await L(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=ie(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=R(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await I(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},U=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;ns;constructor(e,t,n={}){this.transport=e,this.ns=t,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new H(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new H(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function W(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function oe(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var G=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=b(`blobs_${t}`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.dispatch(`system:blobs:blob:list`,{arguments:{ns:this.ns},payload:r})).data?.data?.blobs??[];return{data:i.map(W),loading:!1,page:oe(i),error:void 0}}async read(e){try{let t=await this.client.dispatch(`system:blobs:blob:head`,{arguments:{ns:this.ns,key:e}});return t.data?.data?W(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){if(e.filter)throw Error(`filter-based update not supported for blobs`);let t=e.id;if(!t)throw Error(`id is required for blob update`);return W((await this.client.dispatch(`system:blobs:blob:update`,{arguments:{ns:this.ns,key:t},payload:{custom:C(e.data)}})).data.data)}async delete(e){await this.client.dispatch(`system:blobs:blob:delete`,{arguments:{ns:this.ns,key:e}})}async rename(e,t){await this.client.dispatch(`system:blobs:blob:rename`,{arguments:{ns:this.ns,key:e},payload:{new_key:t}})}async stats(){return(await this.client.dispatch(`system:blobs:namespace:stats`,{arguments:{ns:this.ns}})).data.data}async verify(){await this.client.dispatch(`system:blobs:namespace:verify`,{arguments:{ns:this.ns}})}async compact(){return(await this.client.dispatch(`system:blobs:namespace:compact`,{arguments:{ns:this.ns}})).data.data}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new H(this,e,n,t,this.persistence)}queue(e){return this._queue||=new U(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),W((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return W((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.dispatch(`system:blobs:blob:download`,{arguments:{ns:this.ns,key:e},responseType:`blob`})).data;return{data:t,contentType:t.type}}},K=class{client;uploadPersistence;apiPrefix;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n,this.apiPrefix=t}async namespaces(){return(await this.client.dispatch(`system:blobs:namespace:list`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.dispatch(`system:blobs:namespace:create`,{arguments:{ns:e.ns},payload:{display_name:e.display_name,custom:e.custom}})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return this.client.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new G(this.client,e,this.uploadPersistence)}},q=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:collections:collection:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});return t.data?t.data.data:void 0}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){let t=e.data.schema??e.data;return(await this.client.dispatch(`system:collections:collection:create`,{payload:t})).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.dispatch(`system:collections:collection:delete`,{arguments:{name:e}})}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new w(this.client,e)}view(e){return new T(this.client,e)}},J=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:notifications:notification:create`,{payload:C(e)})).data.data}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}stream(e,t){let n=new AbortController,r=AbortSignal.any([n.signal,...t?.signal?[t.signal]:[]]);return this.client.openStream(`/system/notifications/notification/stream`,{onMessage(t){try{let n=JSON.parse(t),r=n.data??n;e.onMessage(r)}catch(t){e.onError?.(t instanceof Error?t:Error(String(t)))}},onError:e.onError,onOpen:e.onOpen,onClose:e.onClose},{...t,signal:r}).catch(t=>{e.onError?.(t instanceof Error?t:Error(String(t)))}),n}async dispatchAction(e){if(!e.message)throw Error(`action has no message to dispatch`);await this.client.dispatch(e.message,{arguments:e.arguments??{}})}},Y=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:C(e)})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async all(){return(await this.client.dispatch(`system:schedules:schedule:all`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:C(t)})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},X=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},Z=class{client;constructor(e){this.client=e}async status(){return(await this.client.dispatch(`system:updates:status:get`)).data.data}async changelog(){return(await this.client.dispatch(`system:updates:changelog:get`)).data.data}async checkAvailability(){return(await this.client.dispatch(`system:updates:check:get`)).data.data}async stage(){return(await this.client.dispatch(`system:updates:stage:create`)).data.data}async check(){return(await this.client.dispatch(`system:updates:check:create`)).data.data}async apply(){return(await this.client.dispatch(`system:updates:update:apply`)).data.data}};let Q=null;function se(){return Q}var ce=class{client;constructor(e){this.client=e}async compile(e,t){return(await this.client.dispatch(`system:workflows:definition:compile`,{payload:{nodes:e,edges:t}})).data?.data}async create(e){return(await this.client.dispatch(`system:workflows:definition:create`,{payload:e})).data?.data?.id??``}async delete(e){await this.client.dispatch(`system:workflows:definition:delete`,{arguments:{id:e}})}async update(e,t){await this.client.dispatch(`system:workflows:definition:update`,{arguments:{id:e},payload:t})}async list(){return(await this.client.dispatch(`system:workflows:definition:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:workflows:definition:get`,{arguments:{id:e}})).data?.data??null}async run(e){return(await this.client.dispatch(`system:workflows:runtime:run`,{payload:e})).data?.data?.run_id??``}async emitEvent(e){await this.client.dispatch(`system:workflows:runtime:events`,{payload:e})}async abort(e){await this.client.dispatch(`system:workflows:runtime:abort`,{arguments:{run_id:e}})}async listRuns(){return(await this.client.dispatch(`system:workflows:run:list`)).data?.data??[]}async getRun(e){return(await this.client.dispatch(`system:workflows:run:get`,{arguments:{run_id:e}})).data?.data??null}async getOutcome(e){return(await this.client.dispatch(`system:workflows:run:outcome`,{arguments:{run_id:e}})).data?.data??null}async getEvents(e){return(await this.client.dispatch(`system:workflows:run:events`,{arguments:{run_id:e}})).data?.data?.events??[]}async getStore(e){return(await this.client.dispatch(`system:workflows:run:store`,{arguments:{run_id:e}})).data?.data?.state??null}async getRegistry(){return(await this.client.dispatch(`system:workflows:registry:list`)).data?.data?.nodes??[]}async getNodeDefinition(e){return(await this.client.dispatch(`system:workflows:registry:get`,{arguments:{kind:e}})).data?.data??null}async fetchHandles(){if(Q)return Q;try{let e=(await this.client.dispatch(`system:workflows:registry:handles`)).data?.data?.code;return e?(Q=Function(`return (${e})`)(),Q):(Q={},Q)}catch{return Q={},Q}}async hasWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:has`,{arguments:{id:e}})).data?.data?.has??!1}async listWorkflows(){return(await this.client.dispatch(`system:workflows:runtime:list`)).data?.data?.workflow_ids??[]}async invokeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:invoke`,{payload:e})).data?.data}async resumeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:resume`,{payload:e})).data?.data}streamRun(e,t,n){let r=new AbortController,i=AbortSignal.any([r.signal,...n?.signal?[n.signal]:[]]);return this.client.openStream(`/system/workflows/run/stream/${encodeURIComponent(e)}`,{onMessage:e=>{try{let n=JSON.parse(e),r=n.data??n;t.onEvent(r)}catch{}},onError:t.onError,onOpen:t.onOpen,onClose:t.onDone},{...n,signal:i}).catch(e=>{t.onError?.(e instanceof Error?e:Error(String(e)))}),r}},$=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:core:docs:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},le=class{store;client;auth;users;keys;policies;rules;auditLogs;appLogs;collections;blobs;core;notifications;schedules;settings;updates;workflows;operations;tokenProvider;apiKeyMode;autoHeartbeat;authChannel;applyingRemoteAuth=!1;constructor(e){this.store=new r.ReactiveDataStore({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},n=e.apiPrefix??`/api`,i=e.apiKey?{"X-Api-Key":e.apiKey}:void 0,a=()=>{t.clear()};this.tokenProvider=t,this.apiKeyMode=!!e.apiKey,this.autoHeartbeat=e.autoHeartbeat!==!1,e.transport instanceof _?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(a),this.client=e.transport):this.client=e.transport??new f(e.baseUrl,n,a,i),this.auth=new E(this.client,t),this.users=new D(this.client),this.keys=new O(this.client),this.policies=new j(this.client),this.rules=new M(this.client),this.auditLogs=new N(this.client,e.baseUrl,n),this.appLogs=new P(this.client,e.baseUrl,n),this.collections=new q(this.client),this.blobs=new K(this.client,n,e.uploadPersistence),this.core=new $(this.client),this.notifications=new J(this.client),this.schedules=new Y(this.client),this.settings=new X(this.client),this.updates=new Z(this.client),this.workflows=new ce(this.client),this.operations=new A(this.client),this.store.watch(`identity`,e=>{e.identity?this.autoHeartbeat&&this.startHeartbeat():this.stopHeartbeat(),this.applyingRemoteAuth||this.authChannel?.postMessage(`changed`)}),this.setupAuthChannel(e.baseUrl)}setupAuthChannel(e){if(typeof BroadcastChannel>`u`)return;let t=`hestia:auth:${e.replace(/\/+$/,``)}`;try{this.authChannel=new BroadcastChannel(t),this.authChannel.unref?.()}catch{return}this.authChannel.addEventListener(`message`,()=>{this.applyRemoteAuthChange()})}async applyRemoteAuthChange(){if(!this.applyingRemoteAuth){this.applyingRemoteAuth=!0;try{await this.auth.session()}catch{}finally{this.applyingRemoteAuth=!1}}}onAuthStateChange(e){return this.store.watch(`identity`,t=>{e(t.identity??null)})}async authenticated(){if(this.apiKeyMode)return!0;if(this.tokenProvider.identity()===null)return await this.auth.session()!==null;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){if(this.heartbeatTimer!==void 0&&e===void 0)return;this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}view(e){return this.collections.view(e)}ready(){return this.client.ready()}};function ue(e){let t=`${e.collectionName}_array_pager_state_`,n=new r.ReactiveDataStore({}),a=[...e.initialData??[]],o=`collection`,s,c=e.page??1,l=e.size??20,u=[],d,f,{match:p}=(0,i.createMatcher)(e.customFunctions??{}),{sort:m}=(0,i.createSorter)(),h=n.select(e=>e[t]),g={data:[],loading:!0,error:void 0,page:{number:1,size:l,count:0,total:0,pages:1}},_=()=>({filters:d,sort:u,pagination:{type:`offset`,offset:(c-1)*l,limit:l}}),v=async(r=!0)=>{if(e.fetch){if(f=void 0,r){let e=h.get()??g;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=_(),n=await e.fetch(t);o=n.scope,s=n.total,a=n.replace?[...n.data]:[...a,...n.data]}catch(e){f=e}}let i=y(e.fetch?r:!1);await n.set({[t]:i})},y=e=>{let t=[...a];if(o===`collection`){d&&(t=t.filter(e=>p(e,d))),u.length>0&&(t=m(t,u));let n=t.length,r=Math.ceil(n/l)||1;c>r&&(c=r),c<1&&(c=1);let i=(c-1)*l,a=t.slice(i,i+l);return{data:a,loading:e,error:f,page:{number:c,size:l,count:a.length,total:n,pages:r}}}let n=s??t.length,r=Math.ceil(n/l)||1;return{data:t,loading:e,error:f,page:{number:c,size:l,count:t.length,total:n,pages:r}}};return v(!0),{id:()=>t,page:()=>h.get()??g,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);c=e,await v(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);l=e,c=t,await v(!0)},sort:async e=>{u=Array.isArray(e)?e:[e],c=1,await v(!0)},filter:async e=>{d=e,c=1,await v(!0)},refresh:async e=>{let r=h.get()??g;await n.set({[t]:{...r,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),v(!1)]);let a=h.get()??g;await n.set({[t]:{...a,loading:!1}})},subscribe:e=>h.subscribe(t=>{e(t)}),invalidate:async()=>{await n.set({[t]:r.DELETE_SYMBOL}),a=[]}}}exports.AimdController=V,exports.BlobNamespace=G,exports.HestiaAppLogs=P,exports.HestiaAuditLogs=N,exports.HestiaAuth=E,exports.HestiaBlobClient=K,exports.HestiaClient=le,exports.HestiaCollection=w,exports.HestiaCollections=q,exports.HestiaCore=$,exports.HestiaDataView=T,exports.HestiaKeyStore=O,exports.HestiaNetworkClient=p,exports.HestiaNotificationStore=J,exports.HestiaOperations=A,exports.HestiaPolicies=j,exports.HestiaResponse=d,exports.HestiaRules=M,exports.HestiaScheduleStore=Y,exports.HestiaSettingStore=X,exports.HestiaUpdates=Z,exports.HestiaUsers=D,exports.HestiaWorkflowStore=ce,exports.HttpTransport=f,exports.ResumableUpload=H,exports.UploadJobStore=ae,exports.UploadQueue=U,exports.WailsTransport=_,exports.createArrayPager=ue,exports.createAsyncStream=m,exports.createPagedController=b,exports.getCachedHandles=se,exports.getMissingRanges=B,exports.internalError=l,exports.notFound=s,exports.parseErrorBody=a,exports.permissionDenied=c,exports.proxiedDocument=x,exports.proxiedPage=S,exports.toSystemError=o;
|
|
7
|
+
`)}}}catch(e){e instanceof Error&&e.name===`AbortError`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}}finally{this.streams.delete(r)}}close(){for(let e of this.streams)e.abort()}};const p=f;function m(){let e=[],t=`active`,n=null,r=()=>{if(!n)return;let e=n;n=null,e()},i=n=>{t===`active`&&(e.push(n),r())},a=()=>{t===`active`&&(t=`completed`),r()},o=()=>{t===`active`&&(t=`cancelled`),r()};async function*s(){for(;t===`active`;){if(e.length>0){yield e.shift();continue}await new Promise(r=>{n=r,(e.length>0||t!==`active`)&&(n=null,r())})}for(;e.length>0;)yield e.shift()}return{stream:()=>s(),push:i,end:a,cancel:o,status:()=>t}}function h(){try{let e=window.go;if(!e)return null;for(let t of Object.values(e))for(let e of Object.values(t))if(e?.Dispatch)return e;return null}catch{return null}}function g(){throw new t.SystemError({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var _=class{baseUrl=``;apiPrefix=``;init=new n.Once({throws:!0});config;http;onUnauthorized;streamEvents=new Set;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new f(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new f(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new f(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return h()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw g();return this.http.routeUrl(e,t)}async ready(e=1e4){await this.init.do(async()=>{let n=Date.now();for(;!this.resolveService();){if(Date.now()-n>e)throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`Timed out after ${e}ms waiting for Wails bindings on window.go. Are you running inside a Wails desktop window?`});await new Promise(e=>setTimeout(e,50))}},e)}async dispatch(e,r){if(await this.ready(),this.http&&(r?.bodyType===`blob`||r?.bodyType===`stream`))return this.http.dispatch(e,r);let i=r?.notifyAuthStateChange??!0,a=r?.payload??null,o={...r?.modifiers??{}};r?.headers?.[`Content-Type`]&&(o.content_type=r.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:r?.arguments??{},modifiers:o,payload:a})}catch(n){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,n?.message??n),n instanceof t.SystemError?n:new t.SystemError({code:`DISPATCH_ERROR`,message:n?.message??String(n)})}if(c.status>=400){let r=c.data?.error,a=r?.code??`UNKNOWN`,o=r?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&i&&(this.init=new n.Once({throws:!0}),this.onUnauthorized?.()),new t.SystemError({code:a,message:o})}return new d(c.data,c.status)}throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Dispatch binding found on window.go. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}.`})}async check(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw g();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw g();return this.http.delete(e,t,n)}async openStream(e,n,r){let i=this.resolveService();try{if(!i?.Stream)throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Stream binding found. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}`});let r=await i.Stream(e),a=`hestia:stream:${e}`;window.runtime?.EventsOn(a,e=>{n.onMessage(typeof e==`string`?e:JSON.stringify(e))}),this.streamEvents.add(a),n.onOpen?.(),r&&n.onMessage(r),n.onClose?.()}catch(e){n.onError?.(e instanceof Error?e:Error(String(e))),n.onClose?.()}}close(){for(let e of this.streamEvents)window.runtime?.EventsOff(e);this.streamEvents.clear(),this.http?.close()}};const v=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),y={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function b(e,t,i,a){let o=i.page??1,s=i.size??20,c=i.sort,l=i.filter,u=new n.Debouncer({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:r.DELETE_SYMBOL,page:{number:1,size:20,count:0,total:0,pages:1}}});let f=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},p=async e=>(await t.set({[d]:{loading:!0,error:r.DELETE_SYMBOL}}),await new Promise(n=>{n(u.do(async()=>{v(()=>{v(async()=>{try{let n=await a(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...y,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??y,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await p({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await p()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await p()},filter:async e=>{l=e,o=1,await p()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),p(e)])},subscribe:e=>m.subscribe(e),invalidate:async()=>{await t.set({[d]:r.DELETE_SYMBOL}),h()},id:()=>d}}const x=new Set([`id`,`metadata`]);function S(e){return new Proxy(e,{get(e,t,n){if(x.has(t)&&!(t in e))return t===`id`?()=>e._id_:()=>e._metadata_;let r=Reflect.get(e,t,n);return typeof r==`function`?r.bind(e):r}})}function C(e){return{...e,data:e.data.map(S)}}const w=new Set([`_id_`,`_metadata_`]);function T(e){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return[...e];let t={};for(let[n,r]of Object.entries(e))w.has(n)||(t[n]=r);return t}var E=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=b(t,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.collectionName},payload:e??{}}),n=t.data?.data??[];return C({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.collectionName,doc_id:e}})).data?.data;return t?S(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=await this.client.dispatch(`system:collections:document:create`,{arguments:{name:this.collectionName},payload:T(e.data)});return t.data?S(t.data.data):void 0}async update(e){let t=!!e.id,n=!!e.filter;if(t===n)throw Error(`update requires exactly one of id or filter`);let r=T(e.data);if(n){let t=await this.client.dispatch(`system:collections:document:update_many`,{arguments:{name:this.collectionName},payload:{set:r,filter:e.filter}});return t.data?S(t.data.data):void 0}let i=await this.client.dispatch(`system:collections:document:update`,{arguments:{name:this.collectionName,doc_id:e.id},payload:r});return i.data?S(i.data.data):void 0}async delete(e){await this.client.dispatch(`system:collections:document:delete`,{arguments:{name:this.collectionName,doc_id:e}})}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},D=class e{client;viewName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.viewName=t,this.defaultLimit=n,this.pager=b(t,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}static async create(t,n){return await t.dispatch(`system:collections:view:create`,{arguments:{name:n.name},payload:{query:n.query,materialized:n.materialized??!1}}),new e(t,n.name)}name(){return this.viewName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.viewName},payload:e??{}}),n=t.data?.data??[];return C({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.viewName,doc_id:e}})).data?.data;return t?S(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async refresh(){let e=(await this.client.dispatch(`system:collections:view:refresh`,{arguments:{name:this.viewName}})).data?.data;return e?S(e):void 0}async create(e){throw Error(`Create not supported for views: views are read-only`)}async update(e){throw Error(`Update not supported for views: views are read-only`)}async delete(e){throw Error(`Delete not supported for views: views are read-only`)}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for views`)}async subscribe(e,t){throw Error(`Subscription not implemented for views`)}async notify(e){throw Error(`Notify not implemented for views`)}stream(e,t){throw Error(`Stream not supported for views`)}page(e){return this.pager}},O=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.dispatch(`system:core:health:check`)).data.data}async session(){try{let e=await this.client.dispatch(`system:auth:session:get`,{notifyAuthStateChange:!1});return await this.provider.setIdentity(e.data.data.user),e.data.data}catch(e){if(k(e))return await this.provider.clear(),null;throw e}}async login(e,t){let n=await this.client.dispatch(`system:auth:session:create`,{payload:{email:e,password:t}});return await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{payload:{email:e,password:t,name:n}})).data.data}async logout(){try{await this.client.dispatch(`system:auth:session:delete`)}catch(e){if(!ee(e))throw e}finally{await this.provider.clear()}}async requestPasswordReset(e){await this.client.dispatch(`system:auth:password:reset`,{payload:{email:e}})}async confirmPasswordReset(e,t){await this.client.dispatch(`system:auth:password:confirm`,{payload:{password:t,token:e}})}async bootstrap(e,t,n){await this.client.dispatch(`system:auth:bootstrap:password:set`,{payload:{password:t,email:n},headers:{"X-API-Key":e}})}};function k(e){return e?.httpStatus===401||e?.code===`UNAUTHORIZED`||e?.code===`UNAUTHENTICATED`||e?.code===`AUTH_REQUIRED`||e?.code===`AUTH-002-UNAUTH`}function ee(e){return e?.code===`NO_ACTIVE_SESSION`||k(e)||e?.message?.includes(`no active session`)}var te=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=b(`users`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections:user:query`,{payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.dispatch(`system:users:user:get`,{arguments:{user_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){if(e.filter)throw Error(`filter-based update not supported for users`);if(!e.id)throw Error(`user id is required for update`);return(await this.client.dispatch(`system:users:user:update`,{arguments:{user_id:e.id},payload:T(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:users:user:delete`,{arguments:{user_id:e}})}async create({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:T(e)})).data.data}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.dispatch(`system:users:password:change`,{arguments:{user_id:e},payload:{current:t,new:n}})}},ne=class{client;pager;constructor(e){this.client=e,this.pager=b(`_api_key_`,new r.ReactiveDataStore({}),{},e=>this.find(e))}async find(e){let t=await this.client.dispatch(`system:apikeys:key:list`),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.dispatch(`system:apikeys:key:get`,{arguments:{key_id:e}})).data?.data}catch(e){if(e?.code===`DOCUMENT_NOT_FOUND`||e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.dispatch(`system:apikeys:key:create`,{payload:T(e.data)})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for API keys`);if(!e.id)throw Error(`key id is required for update`);return(await this.client.dispatch(`system:apikeys:key:update`,{arguments:{key_id:e.id},payload:T(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:apikeys:key:delete`,{arguments:{key_id:e}})}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.dispatch(`system:apikeys:key:rotate`,{arguments:{key_id:e}})).data.data}};function A(e){let t=e;return{...e,_id_:t._id_??e.name,_metadata_:t._metadata_??{checksum:``,created:``,updated:``,version:1}}}var j=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>A(e)),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:binding:get`,{arguments:{name:e}});return t.data?.data?A(t.data.data):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},M=class{client;pager;constructor(e){this.client=e,this.pager=b(`policies`,new r.ReactiveDataStore({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.dispatch(`system:collections:operation_policy:query`,{payload:e}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for policies`);let t=e.id;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}},N=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.dispatch(`system:policies:rule:list`)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:rule:get`,{arguments:{name:e}});if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.dispatch(`system:policies:rule:create`,{arguments:{name:t},payload:T(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){if(e.filter)throw Error(`filter-based update not supported for policy rules`);let t=e.id;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.dispatch(`system:policies:rule:update`,{arguments:{name:t},payload:T(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.dispatch(`system:policies:rule:delete`,{arguments:{name:e}})}async validate(e){return(await this.client.dispatch(`system:policies:rule:validate`,{payload:e})).data?.data??{valid:!1}}async reload(){return(await this.client.dispatch(`system:policies:reload`)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},P=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=b(`_audit_log_`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/audit_log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=m(),r=new AbortController,i=!1,a=()=>{i||(i=!0,n.status()===`active`&&this.client.openStream(`/system/audit/log/stream`,{onMessage(e){try{let t=JSON.parse(e);t?.data&&n.push(t.data)}catch{}},onError:()=>n.end(),onClose:()=>n.end()},{signal:r.signal}).catch(()=>n.end()))},o=async function*(){a(),yield*n.stream()};return{stream:()=>o(),cancel:()=>{r.abort(),n.cancel()},status:n.status}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}},F=class{client;baseUrl;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n}async query(e){return(await this.client.post(`/system/logs/list`,e??{})).data?.data??{entries:[],total:0,has_more:!1}}stream(e){let t=m(),n=new AbortController,r=new URLSearchParams;e?.level&&r.set(`level`,e.level);let i=r.toString(),a=`/system/logs/stream${i?`?`+i:``}`,o=!1,s=()=>{o||(o=!0,t.status()===`active`&&this.client.openStream(a,{onMessage(e){try{let n=JSON.parse(e);n?.data&&t.push(n.data)}catch{}},onError:()=>t.end(),onClose:()=>t.end()},{signal:n.signal}).catch(()=>t.end()))},c=async function*(){s(),yield*t.stream()};return{stream:()=>c(),cancel:()=>{n.abort(),t.cancel()},status:t.status}}getStreamUrl(e){let t=new URLSearchParams;e?.level&&t.set(`level`,e.level);let n=t.toString();return`${this.baseUrl}${this.apiPrefix}/system/logs/stream${n?`?`+n:``}`}};const re=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),I=Array(256);for(let e=0;e<256;e++)I[e]=e.toString(16).padStart(2,`0`);function ie(){try{let e=globalThis;return!!(e.__HESTIA_ALLOW_INSECURE_CRYPTO__||e.window?.__HESTIA_ALLOW_INSECURE_CRYPTO__)}catch{return!1}}function ae(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=t.length,r=n*8>>>0,i=Math.floor(n/536870912)>>>0,a=1779033703,o=-1150833019,s=1013904242,c=-1521486534,l=1359893119,u=-1694144372,d=528734635,f=1541459225,p=new Uint32Array(64),m=(e,t)=>e>>>t|e<<32-t;function h(e,t){for(let n=0;n<16;n++){let r=t+(n<<2);p[n]=e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]}for(let e=16;e<64;e++){let t=p[e-15],n=p[e-2],r=m(t,7)^m(t,18)^t>>>3,i=m(n,17)^m(n,19)^n>>>10;p[e]=p[e-16]+r+p[e-7]+i|0}let n=a,r=o,i=s,h=c,g=l,_=u,v=d,y=f;for(let e=0;e<64;e++){let t=m(g,6)^m(g,11)^m(g,25),a=g&_^~g&v,o=y+t+a+re[e]+p[e]|0,s=(m(n,2)^m(n,13)^m(n,22))+(n&r^n&i^r&i)|0;y=v,v=_,_=g,g=h+o|0,h=i,i=r,r=n,n=o+s|0}a=a+n|0,o=o+r|0,s=s+i|0,c=c+h|0,l=l+g|0,u=u+_|0,d=d+v|0,f=f+y|0}let g=n>>>6;for(let e=0;e<g;e++)h(t,e<<6);let _=g<<6,v=n-_,y=v<=55?64:128,b=new Uint8Array(y);b.set(t.subarray(_)),b[v]=128;let x=new DataView(b.buffer,b.byteOffset,b.byteLength);x.setUint32(y-8,i,!1),x.setUint32(y-4,r,!1),h(b,0),y===128&&h(b,64);let S=new Uint8Array(32),C=new DataView(S.buffer);C.setUint32(0,a,!1),C.setUint32(4,o,!1),C.setUint32(8,s,!1),C.setUint32(12,c,!1),C.setUint32(16,l,!1),C.setUint32(20,u,!1),C.setUint32(24,d,!1),C.setUint32(28,f,!1);let w=``;for(let e=0;e<32;e++)w+=I[S[e]];return w}async function L(e){let t=typeof crypto<`u`?crypto.subtle:void 0;if(t&&typeof t.digest==`function`){let n=await t.digest(`SHA-256`,e),r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=I[r[e]];return i}if(ie())return ae(e);throw Error(`Web Crypto (crypto.subtle) is unavailable. File uploads require a secure context (HTTPS or localhost). For local development over HTTP you may set globalThis.__HESTIA_ALLOW_INSECURE_CRYPTO__ = true to enable a pure-JS fallback (not recommended for production).`)}const R=.3;function z(e){return new Promise(t=>setTimeout(t,e))}function B(e,t,n){return e.slice(t,n)}function V(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function H(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function oe(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var U=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-R)+e*R}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},se=class{backing;state={jobs:{}};instanceId=V();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},W=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??V(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new U(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=H(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await z(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await B(this.file,t,i).arrayBuffer();this.blockHashes[r]=await L(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await z(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await L(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=oe(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=B(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await z(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},G=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;constructor(e,t,n={}){this.transport=e,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new W(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new W(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function K(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function ce(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var q=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=b(`blobs_${t}`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.dispatch(`system:blobs:blob:list`,{arguments:{ns:this.ns},payload:r})).data?.data?.blobs??[];return{data:i.map(K),loading:!1,page:ce(i),error:void 0}}async read(e){try{let t=await this.client.dispatch(`system:blobs:blob:head`,{arguments:{ns:this.ns,key:e}});return t.data?.data?K(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){if(e.filter)throw Error(`filter-based update not supported for blobs`);let t=e.id;if(!t)throw Error(`id is required for blob update`);return K((await this.client.dispatch(`system:blobs:blob:update`,{arguments:{ns:this.ns,key:t},payload:{custom:T(e.data)}})).data.data)}async delete(e){await this.client.dispatch(`system:blobs:blob:delete`,{arguments:{ns:this.ns,key:e}})}async rename(e,t){await this.client.dispatch(`system:blobs:blob:rename`,{arguments:{ns:this.ns,key:e},payload:{new_key:t}})}async stats(){return(await this.client.dispatch(`system:blobs:namespace:stats`,{arguments:{ns:this.ns}})).data.data}async verify(){await this.client.dispatch(`system:blobs:namespace:verify`,{arguments:{ns:this.ns}})}async compact(){return(await this.client.dispatch(`system:blobs:namespace:compact`,{arguments:{ns:this.ns}})).data.data}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new W(this,e,n,t,this.persistence)}queue(e){return this._queue||=new G(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),K((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return K((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.dispatch(`system:blobs:blob:download`,{arguments:{ns:this.ns,key:e},responseType:`blob`})).data;return{data:t,contentType:t.type}}},J=class{client;uploadPersistence;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n}async namespaces(){return(await this.client.dispatch(`system:blobs:namespace:list`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.dispatch(`system:blobs:namespace:create`,{arguments:{ns:e.ns},payload:{display_name:e.display_name,custom:e.custom}})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return this.client.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new q(this.client,e,this.uploadPersistence)}},Y=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:collections:collection:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});return t.data?t.data.data:void 0}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){let t=e.data.schema??e.data;return(await this.client.dispatch(`system:collections:collection:create`,{payload:t})).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.dispatch(`system:collections:collection:delete`,{arguments:{name:e}})}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new E(this.client,e)}view(e){return new D(this.client,e)}},X=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:notifications:notification:create`,{payload:T(e)})).data.data}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}stream(e,t){let n=new AbortController,r=AbortSignal.any([n.signal,...t?.signal?[t.signal]:[]]);return this.client.openStream(`/system/notifications/notification/stream`,{onMessage(t){try{let n=JSON.parse(t),r=n.data??n;e.onMessage(r)}catch(t){e.onError?.(t instanceof Error?t:Error(String(t)))}},onError:e.onError,onOpen:e.onOpen,onClose:e.onClose},{...t,signal:r}).catch(t=>{e.onError?.(t instanceof Error?t:Error(String(t)))}),n}async dispatchAction(e){if(!e.message)throw Error(`action has no message to dispatch`);await this.client.dispatch(e.message,{arguments:e.arguments??{}})}},Z=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:T(e)})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async all(){return(await this.client.dispatch(`system:schedules:schedule:all`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:T(t)})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},Q=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},le=class{client;constructor(e){this.client=e}async status(){return(await this.client.dispatch(`system:updates:status:get`)).data.data}async changelog(){return(await this.client.dispatch(`system:updates:changelog:get`)).data.data}async checkAvailability(){return(await this.client.dispatch(`system:updates:check:get`)).data.data}async stage(){return(await this.client.dispatch(`system:updates:stage:create`)).data.data}async check(){return(await this.client.dispatch(`system:updates:check:create`)).data.data}async apply(){return(await this.client.dispatch(`system:updates:update:apply`)).data.data}};let $=null;function ue(){return $}var de=class{client;constructor(e){this.client=e}async compile(e,t){return(await this.client.dispatch(`system:workflows:definition:compile`,{payload:{nodes:e,edges:t}})).data?.data}async create(e){return(await this.client.dispatch(`system:workflows:definition:create`,{payload:e})).data?.data?.id??``}async delete(e){await this.client.dispatch(`system:workflows:definition:delete`,{arguments:{id:e}})}async update(e,t){await this.client.dispatch(`system:workflows:definition:update`,{arguments:{id:e},payload:t})}async list(){return(await this.client.dispatch(`system:workflows:definition:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:workflows:definition:get`,{arguments:{id:e}})).data?.data??null}async run(e){return(await this.client.dispatch(`system:workflows:runtime:run`,{payload:e})).data?.data?.run_id??``}async emitEvent(e){await this.client.dispatch(`system:workflows:runtime:events`,{payload:e})}async abort(e){await this.client.dispatch(`system:workflows:runtime:abort`,{arguments:{run_id:e}})}async listRuns(){return(await this.client.dispatch(`system:workflows:run:list`)).data?.data??[]}async getRun(e){return(await this.client.dispatch(`system:workflows:run:get`,{arguments:{run_id:e}})).data?.data??null}async getOutcome(e){return(await this.client.dispatch(`system:workflows:run:outcome`,{arguments:{run_id:e}})).data?.data??null}async getEvents(e){return(await this.client.dispatch(`system:workflows:run:events`,{arguments:{run_id:e}})).data?.data?.events??[]}async getStore(e){return(await this.client.dispatch(`system:workflows:run:store`,{arguments:{run_id:e}})).data?.data?.state??null}async getRegistry(){return(await this.client.dispatch(`system:workflows:registry:list`)).data?.data?.nodes??[]}async getNodeDefinition(e){return(await this.client.dispatch(`system:workflows:registry:get`,{arguments:{kind:e}})).data?.data??null}async fetchHandles(){if($)return $;try{let e=(await this.client.dispatch(`system:workflows:registry:handles`)).data?.data?.code;return e?($=Function(`return (${e})`)(),$):($={},$)}catch{return $={},$}}async hasWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:has`,{arguments:{id:e}})).data?.data?.has??!1}async listWorkflows(){return(await this.client.dispatch(`system:workflows:runtime:list`)).data?.data?.workflow_ids??[]}async invokeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:invoke`,{payload:e})).data?.data}async resumeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:resume`,{payload:e})).data?.data}streamRun(e,t,n){let r=new AbortController,i=AbortSignal.any([r.signal,...n?.signal?[n.signal]:[]]);return this.client.openStream(`/system/workflows/run/stream/${encodeURIComponent(e)}`,{onMessage:e=>{try{let n=JSON.parse(e),r=n.data??n;t.onEvent(r)}catch{}},onError:t.onError,onOpen:t.onOpen,onClose:t.onDone},{...n,signal:i}).catch(e=>{t.onError?.(e instanceof Error?e:Error(String(e)))}),r}},fe=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:core:docs:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},pe=class{store;client;auth;users;keys;policies;rules;auditLogs;appLogs;collections;blobs;core;notifications;schedules;settings;updates;workflows;operations;tokenProvider;apiKeyMode;autoHeartbeat;authChannel;applyingRemoteAuth=!1;unsubscribeIdentity;closing;constructor(e){this.store=new r.ReactiveDataStore({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},n=e.apiPrefix??`/api`,i=e.apiKey?{"X-Api-Key":e.apiKey}:void 0,a=()=>{t.clear()};this.tokenProvider=t,this.apiKeyMode=!!e.apiKey,this.autoHeartbeat=e.autoHeartbeat!==!1,e.transport instanceof _?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(a),this.client=e.transport):this.client=e.transport??new f(e.baseUrl,n,a,i),this.auth=new O(this.client,t),this.users=new te(this.client),this.keys=new ne(this.client),this.policies=new M(this.client),this.rules=new N(this.client),this.auditLogs=new P(this.client,e.baseUrl,n),this.appLogs=new F(this.client,e.baseUrl,n),this.collections=new Y(this.client),this.blobs=new J(this.client,n,e.uploadPersistence),this.core=new fe(this.client),this.notifications=new X(this.client),this.schedules=new Z(this.client),this.settings=new Q(this.client),this.updates=new le(this.client),this.workflows=new de(this.client),this.operations=new j(this.client),this.unsubscribeIdentity=this.store.watch(`identity`,e=>{e.identity?this.autoHeartbeat&&this.startHeartbeat():this.stopHeartbeat(),this.applyingRemoteAuth||this.authChannel?.postMessage(`changed`)}),this.setupAuthChannel(e.baseUrl)}setupAuthChannel(e){if(typeof BroadcastChannel>`u`)return;let t=`hestia:auth:${e.replace(/\/+$/,``)}`;try{this.authChannel=new BroadcastChannel(t),this.authChannel.unref?.()}catch{return}this.authChannel.addEventListener(`message`,()=>{this.applyRemoteAuthChange()})}async applyRemoteAuthChange(){if(!this.applyingRemoteAuth){this.applyingRemoteAuth=!0;try{await this.auth.session()}catch{}finally{this.applyingRemoteAuth=!1}}}onAuthStateChange(e){return this.store.watch(`identity`,t=>{e(t.identity??null)})}async authenticated(){if(this.apiKeyMode)return!0;if(this.tokenProvider.identity()===null)return await this.auth.session()!==null;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){if(this.heartbeatTimer!==void 0&&e===void 0)return;this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}view(e){return this.collections.view(e)}ready(){return this.client.ready()}close(){return this.closing||=(async()=>{this.unsubscribeIdentity?.(),this.stopHeartbeat(),this.authChannel?.close(),await this.client.close?.(),await this.store.dispose()})(),this.closing}};function me(e){let t=`${e.collectionName}_array_pager_state_`,n=new r.ReactiveDataStore({}),a=[...e.initialData??[]],o=`collection`,s,c=e.page??1,l=e.size??20,u=[],d,f,{match:p}=(0,i.createMatcher)(e.customFunctions??{}),{sort:m}=(0,i.createSorter)(),h=n.select(e=>e[t]),g={data:[],loading:!0,error:void 0,page:{number:1,size:l,count:0,total:0,pages:1}},_=()=>({filters:d,sort:u,pagination:{type:`offset`,offset:(c-1)*l,limit:l}}),v=async(r=!0)=>{if(e.fetch){if(f=void 0,r){let e=h.get()??g;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=_(),n=await e.fetch(t);o=n.scope,s=n.total,a=n.replace?[...n.data]:[...a,...n.data]}catch(e){f=e}}let i=y(e.fetch?r:!1);await n.set({[t]:i})},y=e=>{let t=[...a];if(o===`collection`){d&&(t=t.filter(e=>p(e,d))),u.length>0&&(t=m(t,u));let n=t.length,r=Math.ceil(n/l)||1;c>r&&(c=r),c<1&&(c=1);let i=(c-1)*l,a=t.slice(i,i+l);return{data:a,loading:e,error:f,page:{number:c,size:l,count:a.length,total:n,pages:r}}}let n=s??t.length,r=Math.ceil(n/l)||1;return{data:t,loading:e,error:f,page:{number:c,size:l,count:t.length,total:n,pages:r}}};return v(!0),{id:()=>t,page:()=>h.get()??g,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);c=e,await v(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);l=e,c=t,await v(!0)},sort:async e=>{u=Array.isArray(e)?e:[e],c=1,await v(!0)},filter:async e=>{d=e,c=1,await v(!0)},refresh:async e=>{let r=h.get()??g;await n.set({[t]:{...r,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),v(!1)]);let a=h.get()??g;await n.set({[t]:{...a,loading:!1}})},subscribe:e=>h.subscribe(t=>{e(t)}),invalidate:async()=>{await n.set({[t]:r.DELETE_SYMBOL}),a=[]}}}exports.AimdController=U,exports.BlobNamespace=q,exports.HestiaAppLogs=F,exports.HestiaAuditLogs=P,exports.HestiaAuth=O,exports.HestiaBlobClient=J,exports.HestiaClient=pe,exports.HestiaCollection=E,exports.HestiaCollections=Y,exports.HestiaCore=fe,exports.HestiaDataView=D,exports.HestiaKeyStore=ne,exports.HestiaNetworkClient=p,exports.HestiaNotificationStore=X,exports.HestiaOperations=j,exports.HestiaPolicies=M,exports.HestiaResponse=d,exports.HestiaRules=N,exports.HestiaScheduleStore=Z,exports.HestiaSettingStore=Q,exports.HestiaUpdates=le,exports.HestiaUsers=te,exports.HestiaWorkflowStore=de,exports.HttpTransport=f,exports.ResumableUpload=W,exports.UploadJobStore=se,exports.UploadQueue=G,exports.WailsTransport=_,exports.createArrayPager=me,exports.createAsyncStream=m,exports.createPagedController=b,exports.getCachedHandles=ue,exports.getMissingRanges=H,exports.internalError=l,exports.notFound=s,exports.parseErrorBody=a,exports.permissionDenied=c,exports.proxiedDocument=S,exports.proxiedPage=C,exports.toSystemError=o;
|
package/index.d.cts
CHANGED
|
@@ -924,6 +924,8 @@ interface Transport<R extends string = RouteName$1> {
|
|
|
924
924
|
delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
925
925
|
check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
926
926
|
openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
|
|
927
|
+
/** Release any long-lived handles owned by the transport (e.g. streams). */
|
|
928
|
+
close?(): void | Promise<void>;
|
|
927
929
|
}
|
|
928
930
|
declare class HttpTransport<R extends string = RouteName$1> implements Transport<R> {
|
|
929
931
|
private baseUrl;
|
|
@@ -931,6 +933,7 @@ declare class HttpTransport<R extends string = RouteName$1> implements Transport
|
|
|
931
933
|
private onAuthStateChanged?;
|
|
932
934
|
private defaultHeaders?;
|
|
933
935
|
private raw;
|
|
936
|
+
private streams;
|
|
934
937
|
constructor(baseUrl: string, apiPrefix: string, onAuthStateChanged?: (() => void) | undefined, defaultHeaders?: Record<string, string> | undefined);
|
|
935
938
|
private substituteArgs;
|
|
936
939
|
dispatch<T>(name: R, input?: DispatchInput): Promise<HestiaResponse<T>>;
|
|
@@ -947,6 +950,7 @@ declare class HttpTransport<R extends string = RouteName$1> implements Transport
|
|
|
947
950
|
put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
948
951
|
delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
949
952
|
openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
|
|
953
|
+
close(): void;
|
|
950
954
|
}
|
|
951
955
|
declare const HestiaNetworkClient: typeof HttpTransport;
|
|
952
956
|
type HestiaNetworkClient = HttpTransport;
|
|
@@ -1009,6 +1013,7 @@ declare class WailsTransport implements Transport<RouteName$1> {
|
|
|
1009
1013
|
private config?;
|
|
1010
1014
|
private http?;
|
|
1011
1015
|
private onUnauthorized?;
|
|
1016
|
+
private streamEvents;
|
|
1012
1017
|
constructor(config?: WailsTransportConfig);
|
|
1013
1018
|
setOnUnauthorized(cb: () => void, provider?: IdentityProvider): void;
|
|
1014
1019
|
configure(baseUrl: string, apiPrefix: string, provider?: IdentityProvider): void;
|
|
@@ -1029,6 +1034,7 @@ declare class WailsTransport implements Transport<RouteName$1> {
|
|
|
1029
1034
|
put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
1030
1035
|
delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
1031
1036
|
openStream(path: string, handlers: StreamHandlers, _options?: StreamOptions): Promise<void>;
|
|
1037
|
+
close(): void;
|
|
1032
1038
|
}
|
|
1033
1039
|
//#endregion
|
|
1034
1040
|
//#region core/document.d.ts
|
|
@@ -1855,7 +1861,6 @@ declare class ResumableUpload {
|
|
|
1855
1861
|
private readonly transport;
|
|
1856
1862
|
private readonly persistence?;
|
|
1857
1863
|
private readonly aimd;
|
|
1858
|
-
private readonly startedAt;
|
|
1859
1864
|
private blockHashes;
|
|
1860
1865
|
private pauseRequested;
|
|
1861
1866
|
private cancelRequested;
|
|
@@ -1900,12 +1905,11 @@ declare class UploadQueue {
|
|
|
1900
1905
|
private readonly maxConcurrent;
|
|
1901
1906
|
private readonly persistence?;
|
|
1902
1907
|
private readonly transport;
|
|
1903
|
-
|
|
1904
|
-
constructor(transport: UploadTransport, ns: string, options?: UploadQueueOptions);
|
|
1908
|
+
constructor(transport: UploadTransport, _ns: string, options?: UploadQueueOptions);
|
|
1905
1909
|
enqueue(file: File, options: UploadOptions): ResumableUpload;
|
|
1906
1910
|
private pump;
|
|
1907
1911
|
/** Reconstruct uploads from persisted snapshots, paused and ready to resume. */
|
|
1908
|
-
restore(
|
|
1912
|
+
restore(_fileProvider?: (snapshot: UploadJobSnapshot) => File | undefined): ResumableUpload[];
|
|
1909
1913
|
restoreAsync(fileProvider?: (snapshot: UploadJobSnapshot) => File | undefined): Promise<ResumableUpload[]>;
|
|
1910
1914
|
pause(id: string): void;
|
|
1911
1915
|
resume(id: string): void;
|
|
@@ -2002,8 +2006,7 @@ declare class BlobNamespace implements DocumentStore<BlobMeta, QueryDSL<BlobMeta
|
|
|
2002
2006
|
declare class HestiaBlobClient {
|
|
2003
2007
|
private client;
|
|
2004
2008
|
private uploadPersistence?;
|
|
2005
|
-
|
|
2006
|
-
constructor(client: Transport, apiPrefix?: string, uploadPersistence?: UploadPersistence | undefined);
|
|
2009
|
+
constructor(client: Transport, _apiPrefix?: string, uploadPersistence?: UploadPersistence | undefined);
|
|
2007
2010
|
namespaces(): Promise<NamespaceInfo[]>;
|
|
2008
2011
|
createNamespace(data: CreateNamespaceRequest): Promise<NamespaceInfo>;
|
|
2009
2012
|
deleteNamespace(ns: string): Promise<void>;
|
|
@@ -2057,7 +2060,6 @@ interface Notification {
|
|
|
2057
2060
|
data?: Record<string, unknown>;
|
|
2058
2061
|
actions?: NotificationAction[];
|
|
2059
2062
|
read: boolean;
|
|
2060
|
-
created_at: number;
|
|
2061
2063
|
_metadata_: Record<string, unknown>;
|
|
2062
2064
|
}
|
|
2063
2065
|
interface UnreadCount {
|
|
@@ -3384,6 +3386,8 @@ interface Transport$1<R extends string = RouteName> {
|
|
|
3384
3386
|
delete<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
|
|
3385
3387
|
check<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
|
|
3386
3388
|
openStream(path: string, handlers: StreamHandlers$1, options?: StreamOptions$1): Promise<void>;
|
|
3389
|
+
/** Release any long-lived handles owned by the transport (e.g. streams). */
|
|
3390
|
+
close?(): void | Promise<void>;
|
|
3387
3391
|
}
|
|
3388
3392
|
//#endregion
|
|
3389
3393
|
//#region core/wails-transport.d.ts
|
|
@@ -3546,6 +3550,8 @@ declare class HestiaClient {
|
|
|
3546
3550
|
private readonly autoHeartbeat;
|
|
3547
3551
|
private authChannel?;
|
|
3548
3552
|
private applyingRemoteAuth;
|
|
3553
|
+
private unsubscribeIdentity?;
|
|
3554
|
+
private closing?;
|
|
3549
3555
|
constructor(config: HestiaConfig);
|
|
3550
3556
|
private setupAuthChannel;
|
|
3551
3557
|
private applyRemoteAuthChange;
|
|
@@ -3558,6 +3564,14 @@ declare class HestiaClient {
|
|
|
3558
3564
|
collection<T extends Record<string, any>>(name: string): HestiaCollection$1<T>;
|
|
3559
3565
|
view<T extends Record<string, any>>(name: string): HestiaDataView$1<T>;
|
|
3560
3566
|
ready(): Promise<void>;
|
|
3567
|
+
/**
|
|
3568
|
+
* Release every long-lived handle this client owns: the auto-heartbeat
|
|
3569
|
+
* timer, the cross-tab BroadcastChannel, open streams and the persistence
|
|
3570
|
+
* adapter (including file watchers). Idempotent — repeated calls return the
|
|
3571
|
+
* same promise. Call this before a short-lived Node process exits or when
|
|
3572
|
+
* tearing down a browser application.
|
|
3573
|
+
*/
|
|
3574
|
+
close(): Promise<void>;
|
|
3561
3575
|
}
|
|
3562
3576
|
//#endregion
|
|
3563
3577
|
//#region utils/pager.d.ts
|
package/index.d.mts
CHANGED
|
@@ -926,6 +926,8 @@ interface Transport<R extends string = RouteName> {
|
|
|
926
926
|
delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
927
927
|
check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
928
928
|
openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
|
|
929
|
+
/** Release any long-lived handles owned by the transport (e.g. streams). */
|
|
930
|
+
close?(): void | Promise<void>;
|
|
929
931
|
}
|
|
930
932
|
declare class HttpTransport<R extends string = RouteName> implements Transport<R> {
|
|
931
933
|
private baseUrl;
|
|
@@ -933,6 +935,7 @@ declare class HttpTransport<R extends string = RouteName> implements Transport<R
|
|
|
933
935
|
private onAuthStateChanged?;
|
|
934
936
|
private defaultHeaders?;
|
|
935
937
|
private raw;
|
|
938
|
+
private streams;
|
|
936
939
|
constructor(baseUrl: string, apiPrefix: string, onAuthStateChanged?: (() => void) | undefined, defaultHeaders?: Record<string, string> | undefined);
|
|
937
940
|
private substituteArgs;
|
|
938
941
|
dispatch<T>(name: R, input?: DispatchInput): Promise<HestiaResponse<T>>;
|
|
@@ -949,6 +952,7 @@ declare class HttpTransport<R extends string = RouteName> implements Transport<R
|
|
|
949
952
|
put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
950
953
|
delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
951
954
|
openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
|
|
955
|
+
close(): void;
|
|
952
956
|
}
|
|
953
957
|
declare const HestiaNetworkClient: typeof HttpTransport;
|
|
954
958
|
type HestiaNetworkClient = HttpTransport;
|
|
@@ -1011,6 +1015,7 @@ declare class WailsTransport implements Transport<RouteName> {
|
|
|
1011
1015
|
private config?;
|
|
1012
1016
|
private http?;
|
|
1013
1017
|
private onUnauthorized?;
|
|
1018
|
+
private streamEvents;
|
|
1014
1019
|
constructor(config?: WailsTransportConfig);
|
|
1015
1020
|
setOnUnauthorized(cb: () => void, provider?: IdentityProvider): void;
|
|
1016
1021
|
configure(baseUrl: string, apiPrefix: string, provider?: IdentityProvider): void;
|
|
@@ -1031,6 +1036,7 @@ declare class WailsTransport implements Transport<RouteName> {
|
|
|
1031
1036
|
put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
1032
1037
|
delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
|
|
1033
1038
|
openStream(path: string, handlers: StreamHandlers, _options?: StreamOptions): Promise<void>;
|
|
1039
|
+
close(): void;
|
|
1034
1040
|
}
|
|
1035
1041
|
//#endregion
|
|
1036
1042
|
//#region core/document.d.ts
|
|
@@ -1857,7 +1863,6 @@ declare class ResumableUpload {
|
|
|
1857
1863
|
private readonly transport;
|
|
1858
1864
|
private readonly persistence?;
|
|
1859
1865
|
private readonly aimd;
|
|
1860
|
-
private readonly startedAt;
|
|
1861
1866
|
private blockHashes;
|
|
1862
1867
|
private pauseRequested;
|
|
1863
1868
|
private cancelRequested;
|
|
@@ -1902,12 +1907,11 @@ declare class UploadQueue {
|
|
|
1902
1907
|
private readonly maxConcurrent;
|
|
1903
1908
|
private readonly persistence?;
|
|
1904
1909
|
private readonly transport;
|
|
1905
|
-
|
|
1906
|
-
constructor(transport: UploadTransport, ns: string, options?: UploadQueueOptions);
|
|
1910
|
+
constructor(transport: UploadTransport, _ns: string, options?: UploadQueueOptions);
|
|
1907
1911
|
enqueue(file: File, options: UploadOptions): ResumableUpload;
|
|
1908
1912
|
private pump;
|
|
1909
1913
|
/** Reconstruct uploads from persisted snapshots, paused and ready to resume. */
|
|
1910
|
-
restore(
|
|
1914
|
+
restore(_fileProvider?: (snapshot: UploadJobSnapshot) => File | undefined): ResumableUpload[];
|
|
1911
1915
|
restoreAsync(fileProvider?: (snapshot: UploadJobSnapshot) => File | undefined): Promise<ResumableUpload[]>;
|
|
1912
1916
|
pause(id: string): void;
|
|
1913
1917
|
resume(id: string): void;
|
|
@@ -2004,8 +2008,7 @@ declare class BlobNamespace implements DocumentStore<BlobMeta, QueryDSL<BlobMeta
|
|
|
2004
2008
|
declare class HestiaBlobClient {
|
|
2005
2009
|
private client;
|
|
2006
2010
|
private uploadPersistence?;
|
|
2007
|
-
|
|
2008
|
-
constructor(client: Transport, apiPrefix?: string, uploadPersistence?: UploadPersistence | undefined);
|
|
2011
|
+
constructor(client: Transport, _apiPrefix?: string, uploadPersistence?: UploadPersistence | undefined);
|
|
2009
2012
|
namespaces(): Promise<NamespaceInfo[]>;
|
|
2010
2013
|
createNamespace(data: CreateNamespaceRequest): Promise<NamespaceInfo>;
|
|
2011
2014
|
deleteNamespace(ns: string): Promise<void>;
|
|
@@ -2059,7 +2062,6 @@ interface Notification {
|
|
|
2059
2062
|
data?: Record<string, unknown>;
|
|
2060
2063
|
actions?: NotificationAction[];
|
|
2061
2064
|
read: boolean;
|
|
2062
|
-
created_at: number;
|
|
2063
2065
|
_metadata_: Record<string, unknown>;
|
|
2064
2066
|
}
|
|
2065
2067
|
interface UnreadCount {
|
|
@@ -2541,6 +2543,8 @@ declare class HestiaClient {
|
|
|
2541
2543
|
private readonly autoHeartbeat;
|
|
2542
2544
|
private authChannel?;
|
|
2543
2545
|
private applyingRemoteAuth;
|
|
2546
|
+
private unsubscribeIdentity?;
|
|
2547
|
+
private closing?;
|
|
2544
2548
|
constructor(config: HestiaConfig);
|
|
2545
2549
|
private setupAuthChannel;
|
|
2546
2550
|
private applyRemoteAuthChange;
|
|
@@ -2553,6 +2557,14 @@ declare class HestiaClient {
|
|
|
2553
2557
|
collection<T extends Record<string, any>>(name: string): import_dist.HestiaCollection<T>;
|
|
2554
2558
|
view<T extends Record<string, any>>(name: string): import_dist.HestiaDataView<T>;
|
|
2555
2559
|
ready(): Promise<void>;
|
|
2560
|
+
/**
|
|
2561
|
+
* Release every long-lived handle this client owns: the auto-heartbeat
|
|
2562
|
+
* timer, the cross-tab BroadcastChannel, open streams and the persistence
|
|
2563
|
+
* adapter (including file watchers). Idempotent — repeated calls return the
|
|
2564
|
+
* same promise. Call this before a short-lived Node process exits or when
|
|
2565
|
+
* tearing down a browser application.
|
|
2566
|
+
*/
|
|
2567
|
+
close(): Promise<void>;
|
|
2556
2568
|
}
|
|
2557
2569
|
//#endregion
|
|
2558
2570
|
//#region utils/pager.d.ts
|
package/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createNetworkClient as e}from"@asaidimu/network-client";import{Errors as t,SystemError as n}from"@asaidimu/utils-error";import{Debouncer as r,Once as i}from"@asaidimu/utils-sync";import{DELETE_SYMBOL as a,ReactiveDataStore as o}from"@asaidimu/utils-store";import{createMatcher as s,createSorter as c}from"@asaidimu/query";async function l(e){try{return(await e.clone().json())?.error??null}catch{return null}}function u(e,t){if(t)return new n({code:t.code??`UNKNOWN`,message:t.message??`Unknown error`,issues:t.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new n({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new n({code:`UNKNOWN`,message:r??`Unknown error`})}function d(e){return t.notFound(e)}function f(e){return t.permissionDenied(e)}function p(e){return t.internalError(e)}const m={"system:apikeys:key:create":{method:`POST`,route:`/system/apikeys/key/create`,arguments:[]},"system:apikeys:key:delete":{method:`DELETE`,route:`/system/apikeys/key/delete/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:get":{method:`GET`,route:`/system/apikeys/key/get/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:list":{method:`GET`,route:`/system/apikeys/key/list`,arguments:[]},"system:apikeys:key:rotate":{method:`POST`,route:`/system/apikeys/key/rotate/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:update":{method:`PATCH`,route:`/system/apikeys/key/update/{key_id}`,arguments:[`key_id`]},"system:audit:log:export":{method:`PATCH`,route:`/system/audit/log/export`,arguments:[]},"system:audit:log:stream":{method:`GET`,route:`/system/audit/log/stream`,arguments:[]},"system:auth:bootstrap:password:set":{method:`PATCH`,route:`/system/auth/bootstrap/password/set`,arguments:[]},"system:auth:password:confirm":{method:`PATCH`,route:`/system/auth/password/confirm`,arguments:[]},"system:auth:password:reset":{method:`POST`,route:`/system/auth/password/reset`,arguments:[]},"system:auth:session:create":{method:`POST`,route:`/system/auth/session/create`,arguments:[]},"system:auth:session:delete":{method:`DELETE`,route:`/system/auth/session/delete`,arguments:[]},"system:auth:session:get":{method:`GET`,route:`/system/auth/session/get`,arguments:[]},"system:auth:token:elevate":{method:`POST`,route:`/system/auth/token/elevate`,arguments:[]},"system:blobs:blob:abort":{method:`POST`,route:`/system/blobs/blob/abort/{ns}`,arguments:[`ns`]},"system:blobs:blob:begin":{method:`POST`,route:`/system/blobs/blob/begin/{ns}`,arguments:[`ns`]},"system:blobs:blob:chunk":{method:`POST`,route:`/system/blobs/blob/chunk/{ns}`,arguments:[`ns`]},"system:blobs:blob:complete":{method:`POST`,route:`/system/blobs/blob/complete/{ns}`,arguments:[`ns`]},"system:blobs:blob:delete":{method:`DELETE`,route:`/system/blobs/blob/delete/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:download":{method:`GET`,route:`/system/blobs/blob/download/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:head":{method:`POST`,route:`/system/blobs/blob/head/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:list":{method:`POST`,route:`/system/blobs/blob/list/{ns}`,arguments:[`ns`]},"system:blobs:blob:progress":{method:`POST`,route:`/system/blobs/blob/progress/{ns}`,arguments:[`ns`]},"system:blobs:blob:rename":{method:`PATCH`,route:`/system/blobs/blob/rename/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:update":{method:`PATCH`,route:`/system/blobs/blob/update/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:upload":{method:`POST`,route:`/system/blobs/blob/upload/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:namespace:compact":{method:`POST`,route:`/system/blobs/namespace/compact/{ns}`,arguments:[`ns`]},"system:blobs:namespace:create":{method:`POST`,route:`/system/blobs/namespace/create/{ns}`,arguments:[`ns`]},"system:blobs:namespace:delete":{method:`DELETE`,route:`/system/blobs/namespace/delete/{ns}`,arguments:[`ns`]},"system:blobs:namespace:list":{method:`POST`,route:`/system/blobs/namespace/list`,arguments:[]},"system:blobs:namespace:stats":{method:`POST`,route:`/system/blobs/namespace/stats/{ns}`,arguments:[`ns`]},"system:blobs:namespace:verify":{method:`POST`,route:`/system/blobs/namespace/verify/{ns}`,arguments:[`ns`]},"system:collections:audit_log:query":{method:`POST`,route:`/system/collections/audit_log/query`,arguments:[]},"system:collections:collection:create":{method:`POST`,route:`/system/collections/collection/create`,arguments:[]},"system:collections:collection:delete":{method:`DELETE`,route:`/system/collections/collection/delete/{name}`,arguments:[`name`]},"system:collections:collection:get":{method:`GET`,route:`/system/collections/collection/get/{name}`,arguments:[`name`]},"system:collections:collection:list":{method:`GET`,route:`/system/collections/collection/list`,arguments:[]},"system:collections:document:create":{method:`POST`,route:`/system/collections/document/create/{name}`,arguments:[`name`]},"system:collections:document:delete":{method:`DELETE`,route:`/system/collections/document/delete/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:get":{method:`GET`,route:`/system/collections/document/get/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:query":{method:`POST`,route:`/system/collections/document/query/{name}`,arguments:[`name`]},"system:collections:document:update":{method:`PATCH`,route:`/system/collections/document/update/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:update_many":{method:`PATCH`,route:`/system/collections/document/update_many/{name}`,arguments:[`name`]},"system:collections:operation_policy:query":{method:`POST`,route:`/system/collections/operation_policy/query`,arguments:[]},"system:collections:user:query":{method:`POST`,route:`/system/collections/user/query`,arguments:[]},"system:collections:view:create":{method:`POST`,route:`/system/collections/view/create/{name}`,arguments:[`name`]},"system:collections:view:refresh":{method:`PATCH`,route:`/system/collections/view/refresh/{name}`,arguments:[`name`]},"system:core:capability:list":{method:`GET`,route:`/system/core/capability/list`,arguments:[]},"system:core:capability:set":{method:`PATCH`,route:`/system/core/capability/set/{name}`,arguments:[`name`]},"system:core:docs:list":{method:`GET`,route:`/system/core/docs/list`,arguments:[]},"system:core:health:check":{method:`GET`,route:`/system/core/health/check`,arguments:[]},"system:core:heartbeat":{method:`GET`,route:`/system/core/heartbeat`,arguments:[]},"system:core:reset":{method:`DELETE`,route:`/system/core/reset`,arguments:[]},"system:logs:list":{method:`POST`,route:`/system/logs/list`,arguments:[]},"system:logs:stream":{method:`GET`,route:`/system/logs/stream`,arguments:[]},"system:notifications:notification:create":{method:`POST`,route:`/system/notifications/notification/create`,arguments:[]},"system:notifications:notification:list":{method:`GET`,route:`/system/notifications/notification/list`,arguments:[]},"system:notifications:notification:read":{method:`PATCH`,route:`/system/notifications/notification/read/{notification_id}`,arguments:[`notification_id`]},"system:notifications:notification:stream":{method:`GET`,route:`/system/notifications/notification/stream`,arguments:[]},"system:notifications:read:all":{method:`PATCH`,route:`/system/notifications/read/all`,arguments:[]},"system:notifications:unread:count":{method:`GET`,route:`/system/notifications/unread/count`,arguments:[]},"system:policies:binding:get":{method:`GET`,route:`/system/policies/binding/get/{name}`,arguments:[`name`]},"system:policies:binding:list":{method:`GET`,route:`/system/policies/binding/list`,arguments:[]},"system:policies:policy:create":{method:`POST`,route:`/system/policies/policy/create/{name}`,arguments:[`name`]},"system:policies:policy:list":{method:`GET`,route:`/system/policies/policy/list`,arguments:[]},"system:policies:policy:update":{method:`PATCH`,route:`/system/policies/policy/update/{name}`,arguments:[`name`]},"system:policies:reload":{method:`GET`,route:`/system/policies/reload`,arguments:[]},"system:policies:rule:create":{method:`POST`,route:`/system/policies/rule/create/{name}`,arguments:[`name`]},"system:policies:rule:delete":{method:`DELETE`,route:`/system/policies/rule/delete/{name}`,arguments:[`name`]},"system:policies:rule:get":{method:`GET`,route:`/system/policies/rule/get/{name}`,arguments:[`name`]},"system:policies:rule:list":{method:`GET`,route:`/system/policies/rule/list`,arguments:[]},"system:policies:rule:update":{method:`PATCH`,route:`/system/policies/rule/update/{name}`,arguments:[`name`]},"system:policies:rule:validate":{method:`POST`,route:`/system/policies/rule/validate`,arguments:[]},"system:scheduler:job:list":{method:`GET`,route:`/system/scheduler/job/list`,arguments:[]},"system:schedules:schedule:all":{method:`GET`,route:`/system/schedules/schedule/all`,arguments:[]},"system:schedules:schedule:create":{method:`POST`,route:`/system/schedules/schedule/create`,arguments:[]},"system:schedules:schedule:delete":{method:`DELETE`,route:`/system/schedules/schedule/delete/{id}`,arguments:[`id`]},"system:schedules:schedule:get":{method:`GET`,route:`/system/schedules/schedule/get/{id}`,arguments:[`id`]},"system:schedules:schedule:list":{method:`GET`,route:`/system/schedules/schedule/list`,arguments:[]},"system:schedules:schedule:update":{method:`PATCH`,route:`/system/schedules/schedule/update/{id}`,arguments:[`id`]},"system:settings:delete":{method:`DELETE`,route:`/system/settings/delete/{key}`,arguments:[`key`]},"system:settings:get":{method:`GET`,route:`/system/settings/get/{key}`,arguments:[`key`]},"system:settings:list":{method:`GET`,route:`/system/settings/list`,arguments:[]},"system:settings:set":{method:`POST`,route:`/system/settings/set/{key}`,arguments:[`key`]},"system:updates:changelog:get":{method:`GET`,route:`/system/updates/changelog/get`,arguments:[]},"system:updates:check:create":{method:`POST`,route:`/system/updates/check/create`,arguments:[]},"system:updates:check:get":{method:`GET`,route:`/system/updates/check/get`,arguments:[]},"system:updates:stage:create":{method:`POST`,route:`/system/updates/stage/create`,arguments:[]},"system:updates:status:get":{method:`GET`,route:`/system/updates/status/get`,arguments:[]},"system:updates:update:apply":{method:`POST`,route:`/system/updates/update/apply`,arguments:[]},"system:updates:update:discard":{method:`DELETE`,route:`/system/updates/update/discard`,arguments:[]},"system:users:password:change":{method:`PATCH`,route:`/system/users/password/change/{user_id}`,arguments:[`user_id`]},"system:users:user:create":{method:`POST`,route:`/system/users/user/create`,arguments:[]},"system:users:user:delete":{method:`DELETE`,route:`/system/users/user/delete/{user_id}`,arguments:[`user_id`]},"system:users:user:get":{method:`GET`,route:`/system/users/user/get/{user_id}`,arguments:[`user_id`]},"system:users:user:update":{method:`PATCH`,route:`/system/users/user/update/{user_id}`,arguments:[`user_id`]},"system:workflows:definition:compile":{method:`POST`,route:`/system/workflows/definition/compile`,arguments:[]},"system:workflows:definition:create":{method:`POST`,route:`/system/workflows/definition/create`,arguments:[]},"system:workflows:definition:delete":{method:`DELETE`,route:`/system/workflows/definition/delete/{id}`,arguments:[`id`]},"system:workflows:definition:get":{method:`GET`,route:`/system/workflows/definition/get/{id}`,arguments:[`id`]},"system:workflows:definition:list":{method:`GET`,route:`/system/workflows/definition/list`,arguments:[]},"system:workflows:definition:update":{method:`PATCH`,route:`/system/workflows/definition/update/{id}`,arguments:[`id`]},"system:workflows:registry:get":{method:`GET`,route:`/system/workflows/registry/get/{kind}`,arguments:[`kind`]},"system:workflows:registry:handles":{method:`GET`,route:`/system/workflows/registry/handles`,arguments:[]},"system:workflows:registry:list":{method:`GET`,route:`/system/workflows/registry/list`,arguments:[]},"system:workflows:run:events":{method:`GET`,route:`/system/workflows/run/events/{run_id}`,arguments:[`run_id`]},"system:workflows:run:get":{method:`GET`,route:`/system/workflows/run/get/{run_id}`,arguments:[`run_id`]},"system:workflows:run:list":{method:`GET`,route:`/system/workflows/run/list`,arguments:[]},"system:workflows:run:outcome":{method:`GET`,route:`/system/workflows/run/outcome/{run_id}`,arguments:[`run_id`]},"system:workflows:run:store":{method:`GET`,route:`/system/workflows/run/store/{run_id}`,arguments:[`run_id`]},"system:workflows:run:stream":{method:`GET`,route:`/system/workflows/run/stream/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:abort":{method:`DELETE`,route:`/system/workflows/runtime/abort/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:events":{method:`POST`,route:`/system/workflows/runtime/events`,arguments:[]},"system:workflows:runtime:has":{method:`GET`,route:`/system/workflows/runtime/has/{id}`,arguments:[`id`]},"system:workflows:runtime:invoke":{method:`POST`,route:`/system/workflows/runtime/invoke`,arguments:[]},"system:workflows:runtime:list":{method:`GET`,route:`/system/workflows/runtime/list`,arguments:[]},"system:workflows:runtime:resume":{method:`POST`,route:`/system/workflows/runtime/resume`,arguments:[]},"system:workflows:runtime:run":{method:`POST`,route:`/system/workflows/runtime/run`,arguments:[]}};var h=class{data;status;constructor(e,t){this.data=e,this.status=t}},g=class{baseUrl;apiPrefix;onAuthStateChanged;defaultHeaders;raw;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.onAuthStateChanged=r,this.defaultHeaders=i,this.raw=e({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`,...this.defaultHeaders?{defaultHeaders:this.defaultHeaders}:{}})}substituteArgs(e,t){return e.replace(/\{(\w+)(\*)?\}/g,(e,n,r)=>t[n]?r?t[n].split(`/`).map(encodeURIComponent).join(`/`):encodeURIComponent(t[n]):`{${n}}`)}async dispatch(e,t){let r=m[e];if(!r)throw new n({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});let i=this.substituteArgs(r.route,t?.arguments??{}),a=r.method,o={},s=t?.notifyAuthStateChange??!0;if(t?.headers&&(o.headers=t.headers),t?.responseType&&(o.responseType=t.responseType),t?.bodyType&&(o.bodyType=t.bodyType),t?.signal&&(o.signal=t.signal),t?.modifiers){let e=Object.entries(t.modifiers).flatMap(([e,t])=>(Array.isArray(t)?t:[t]).map(t=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join(`&`);if(e){let n=i.includes(`?`)?`&`:`?`;return this.request(a,`${i}${n}${e}`,t?.payload,o,s)}}return this.request(a,i,t?.payload,o,s)}routeUrl(e,t){let r=m[e];if(!r)throw new n({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});return`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(this.substituteArgs(r.route,t??{}))}`}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(){}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,t,n,r,i=!1){let a=this.canonicalPath(t),o={};r?.headers&&(o.headers={...r.headers}),r?.responseType&&(o.responseType=r.responseType),r?.bodyType&&(o.bodyType=r.bodyType),r?.signal&&(o.signal=r.signal),o.headers||={};let s;if(e===`GET`)s=await this.raw.get(a,o);else{let t=r?.bodyType?{type:r.bodyType}:void 0;s=await this.raw[e.toLowerCase()](a,n,o,t)}if(s.success||s.status===204)return new h(s.data,s.status);s.status===401&&i&&this.onAuthStateChanged?.();let c=s.raw?await l(s.raw):null;throw u(s,c)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,t,n){let r={Accept:`text/event-stream`,...this.defaultHeaders??{},...n?.headers??{}},i=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,a;try{a=await fetch(i,{method:`GET`,headers:r,credentials:n?.credentials??`same-origin`,signal:n?.signal})}catch(e){if(e instanceof Error&&e.name===`AbortError`){t.onClose?.();return}t.onError?.(e instanceof Error?e:Error(String(e)));return}if(!a.ok||!a.body){t.onError?.(Error(`Stream request failed with status ${a.status}`));return}t.onOpen?.();let o=a.body.getReader(),s=new TextDecoder,c=``;try{for(;;){let{done:e,value:n}=await o.read();if(e)break;c+=s.decode(n,{stream:!0});let r=c.indexOf(`
|
|
1
|
+
import{createNetworkClient as e}from"@asaidimu/network-client";import{Errors as t,SystemError as n}from"@asaidimu/utils-error";import{Debouncer as r,Once as i}from"@asaidimu/utils-sync";import{DELETE_SYMBOL as a,ReactiveDataStore as o}from"@asaidimu/utils-store";import{createMatcher as s,createSorter as c}from"@asaidimu/query";async function l(e){try{return(await e.clone().json())?.error??null}catch{return null}}function u(e,t){if(t)return new n({code:t.code??`UNKNOWN`,message:t.message??`Unknown error`,issues:t.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new n({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new n({code:`UNKNOWN`,message:r??`Unknown error`})}function d(e){return t.notFound(e)}function f(e){return t.permissionDenied(e)}function p(e){return t.internalError(e)}const m={"system:apikeys:key:create":{method:`POST`,route:`/system/apikeys/key/create`,arguments:[]},"system:apikeys:key:delete":{method:`DELETE`,route:`/system/apikeys/key/delete/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:get":{method:`GET`,route:`/system/apikeys/key/get/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:list":{method:`GET`,route:`/system/apikeys/key/list`,arguments:[]},"system:apikeys:key:rotate":{method:`POST`,route:`/system/apikeys/key/rotate/{key_id}`,arguments:[`key_id`]},"system:apikeys:key:update":{method:`PATCH`,route:`/system/apikeys/key/update/{key_id}`,arguments:[`key_id`]},"system:audit:log:export":{method:`PATCH`,route:`/system/audit/log/export`,arguments:[]},"system:audit:log:stream":{method:`GET`,route:`/system/audit/log/stream`,arguments:[]},"system:auth:bootstrap:password:set":{method:`PATCH`,route:`/system/auth/bootstrap/password/set`,arguments:[]},"system:auth:password:confirm":{method:`PATCH`,route:`/system/auth/password/confirm`,arguments:[]},"system:auth:password:reset":{method:`POST`,route:`/system/auth/password/reset`,arguments:[]},"system:auth:session:create":{method:`POST`,route:`/system/auth/session/create`,arguments:[]},"system:auth:session:delete":{method:`DELETE`,route:`/system/auth/session/delete`,arguments:[]},"system:auth:session:get":{method:`GET`,route:`/system/auth/session/get`,arguments:[]},"system:auth:token:elevate":{method:`POST`,route:`/system/auth/token/elevate`,arguments:[]},"system:blobs:blob:abort":{method:`POST`,route:`/system/blobs/blob/abort/{ns}`,arguments:[`ns`]},"system:blobs:blob:begin":{method:`POST`,route:`/system/blobs/blob/begin/{ns}`,arguments:[`ns`]},"system:blobs:blob:chunk":{method:`POST`,route:`/system/blobs/blob/chunk/{ns}`,arguments:[`ns`]},"system:blobs:blob:complete":{method:`POST`,route:`/system/blobs/blob/complete/{ns}`,arguments:[`ns`]},"system:blobs:blob:delete":{method:`DELETE`,route:`/system/blobs/blob/delete/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:download":{method:`GET`,route:`/system/blobs/blob/download/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:head":{method:`POST`,route:`/system/blobs/blob/head/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:list":{method:`POST`,route:`/system/blobs/blob/list/{ns}`,arguments:[`ns`]},"system:blobs:blob:progress":{method:`POST`,route:`/system/blobs/blob/progress/{ns}`,arguments:[`ns`]},"system:blobs:blob:rename":{method:`PATCH`,route:`/system/blobs/blob/rename/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:update":{method:`PATCH`,route:`/system/blobs/blob/update/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:blob:upload":{method:`POST`,route:`/system/blobs/blob/upload/{ns}/{key*}`,arguments:[`ns`,`key`]},"system:blobs:namespace:compact":{method:`POST`,route:`/system/blobs/namespace/compact/{ns}`,arguments:[`ns`]},"system:blobs:namespace:create":{method:`POST`,route:`/system/blobs/namespace/create/{ns}`,arguments:[`ns`]},"system:blobs:namespace:delete":{method:`DELETE`,route:`/system/blobs/namespace/delete/{ns}`,arguments:[`ns`]},"system:blobs:namespace:list":{method:`POST`,route:`/system/blobs/namespace/list`,arguments:[]},"system:blobs:namespace:stats":{method:`POST`,route:`/system/blobs/namespace/stats/{ns}`,arguments:[`ns`]},"system:blobs:namespace:verify":{method:`POST`,route:`/system/blobs/namespace/verify/{ns}`,arguments:[`ns`]},"system:collections:audit_log:query":{method:`POST`,route:`/system/collections/audit_log/query`,arguments:[]},"system:collections:collection:create":{method:`POST`,route:`/system/collections/collection/create`,arguments:[]},"system:collections:collection:delete":{method:`DELETE`,route:`/system/collections/collection/delete/{name}`,arguments:[`name`]},"system:collections:collection:get":{method:`GET`,route:`/system/collections/collection/get/{name}`,arguments:[`name`]},"system:collections:collection:list":{method:`GET`,route:`/system/collections/collection/list`,arguments:[]},"system:collections:document:create":{method:`POST`,route:`/system/collections/document/create/{name}`,arguments:[`name`]},"system:collections:document:delete":{method:`DELETE`,route:`/system/collections/document/delete/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:get":{method:`GET`,route:`/system/collections/document/get/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:query":{method:`POST`,route:`/system/collections/document/query/{name}`,arguments:[`name`]},"system:collections:document:update":{method:`PATCH`,route:`/system/collections/document/update/{name}/{doc_id}`,arguments:[`name`,`doc_id`]},"system:collections:document:update_many":{method:`PATCH`,route:`/system/collections/document/update_many/{name}`,arguments:[`name`]},"system:collections:operation_policy:query":{method:`POST`,route:`/system/collections/operation_policy/query`,arguments:[]},"system:collections:user:query":{method:`POST`,route:`/system/collections/user/query`,arguments:[]},"system:collections:view:create":{method:`POST`,route:`/system/collections/view/create/{name}`,arguments:[`name`]},"system:collections:view:refresh":{method:`PATCH`,route:`/system/collections/view/refresh/{name}`,arguments:[`name`]},"system:core:capability:list":{method:`GET`,route:`/system/core/capability/list`,arguments:[]},"system:core:capability:set":{method:`PATCH`,route:`/system/core/capability/set/{name}`,arguments:[`name`]},"system:core:docs:list":{method:`GET`,route:`/system/core/docs/list`,arguments:[]},"system:core:health:check":{method:`GET`,route:`/system/core/health/check`,arguments:[]},"system:core:heartbeat":{method:`GET`,route:`/system/core/heartbeat`,arguments:[]},"system:core:reset":{method:`DELETE`,route:`/system/core/reset`,arguments:[]},"system:logs:list":{method:`POST`,route:`/system/logs/list`,arguments:[]},"system:logs:stream":{method:`GET`,route:`/system/logs/stream`,arguments:[]},"system:notifications:notification:create":{method:`POST`,route:`/system/notifications/notification/create`,arguments:[]},"system:notifications:notification:list":{method:`GET`,route:`/system/notifications/notification/list`,arguments:[]},"system:notifications:notification:read":{method:`PATCH`,route:`/system/notifications/notification/read/{notification_id}`,arguments:[`notification_id`]},"system:notifications:notification:stream":{method:`GET`,route:`/system/notifications/notification/stream`,arguments:[]},"system:notifications:read:all":{method:`PATCH`,route:`/system/notifications/read/all`,arguments:[]},"system:notifications:unread:count":{method:`GET`,route:`/system/notifications/unread/count`,arguments:[]},"system:policies:binding:get":{method:`GET`,route:`/system/policies/binding/get/{name}`,arguments:[`name`]},"system:policies:binding:list":{method:`GET`,route:`/system/policies/binding/list`,arguments:[]},"system:policies:policy:create":{method:`POST`,route:`/system/policies/policy/create/{name}`,arguments:[`name`]},"system:policies:policy:list":{method:`GET`,route:`/system/policies/policy/list`,arguments:[]},"system:policies:policy:update":{method:`PATCH`,route:`/system/policies/policy/update/{name}`,arguments:[`name`]},"system:policies:reload":{method:`GET`,route:`/system/policies/reload`,arguments:[]},"system:policies:rule:create":{method:`POST`,route:`/system/policies/rule/create/{name}`,arguments:[`name`]},"system:policies:rule:delete":{method:`DELETE`,route:`/system/policies/rule/delete/{name}`,arguments:[`name`]},"system:policies:rule:get":{method:`GET`,route:`/system/policies/rule/get/{name}`,arguments:[`name`]},"system:policies:rule:list":{method:`GET`,route:`/system/policies/rule/list`,arguments:[]},"system:policies:rule:update":{method:`PATCH`,route:`/system/policies/rule/update/{name}`,arguments:[`name`]},"system:policies:rule:validate":{method:`POST`,route:`/system/policies/rule/validate`,arguments:[]},"system:scheduler:job:list":{method:`GET`,route:`/system/scheduler/job/list`,arguments:[]},"system:schedules:schedule:all":{method:`GET`,route:`/system/schedules/schedule/all`,arguments:[]},"system:schedules:schedule:create":{method:`POST`,route:`/system/schedules/schedule/create`,arguments:[]},"system:schedules:schedule:delete":{method:`DELETE`,route:`/system/schedules/schedule/delete/{id}`,arguments:[`id`]},"system:schedules:schedule:get":{method:`GET`,route:`/system/schedules/schedule/get/{id}`,arguments:[`id`]},"system:schedules:schedule:list":{method:`GET`,route:`/system/schedules/schedule/list`,arguments:[]},"system:schedules:schedule:update":{method:`PATCH`,route:`/system/schedules/schedule/update/{id}`,arguments:[`id`]},"system:settings:delete":{method:`DELETE`,route:`/system/settings/delete/{key}`,arguments:[`key`]},"system:settings:get":{method:`GET`,route:`/system/settings/get/{key}`,arguments:[`key`]},"system:settings:list":{method:`GET`,route:`/system/settings/list`,arguments:[]},"system:settings:set":{method:`POST`,route:`/system/settings/set/{key}`,arguments:[`key`]},"system:updates:changelog:get":{method:`GET`,route:`/system/updates/changelog/get`,arguments:[]},"system:updates:check:create":{method:`POST`,route:`/system/updates/check/create`,arguments:[]},"system:updates:check:get":{method:`GET`,route:`/system/updates/check/get`,arguments:[]},"system:updates:stage:create":{method:`POST`,route:`/system/updates/stage/create`,arguments:[]},"system:updates:status:get":{method:`GET`,route:`/system/updates/status/get`,arguments:[]},"system:updates:update:apply":{method:`POST`,route:`/system/updates/update/apply`,arguments:[]},"system:updates:update:discard":{method:`DELETE`,route:`/system/updates/update/discard`,arguments:[]},"system:users:password:change":{method:`PATCH`,route:`/system/users/password/change/{user_id}`,arguments:[`user_id`]},"system:users:user:create":{method:`POST`,route:`/system/users/user/create`,arguments:[]},"system:users:user:delete":{method:`DELETE`,route:`/system/users/user/delete/{user_id}`,arguments:[`user_id`]},"system:users:user:get":{method:`GET`,route:`/system/users/user/get/{user_id}`,arguments:[`user_id`]},"system:users:user:update":{method:`PATCH`,route:`/system/users/user/update/{user_id}`,arguments:[`user_id`]},"system:workflows:definition:compile":{method:`POST`,route:`/system/workflows/definition/compile`,arguments:[]},"system:workflows:definition:create":{method:`POST`,route:`/system/workflows/definition/create`,arguments:[]},"system:workflows:definition:delete":{method:`DELETE`,route:`/system/workflows/definition/delete/{id}`,arguments:[`id`]},"system:workflows:definition:get":{method:`GET`,route:`/system/workflows/definition/get/{id}`,arguments:[`id`]},"system:workflows:definition:list":{method:`GET`,route:`/system/workflows/definition/list`,arguments:[]},"system:workflows:definition:update":{method:`PATCH`,route:`/system/workflows/definition/update/{id}`,arguments:[`id`]},"system:workflows:registry:get":{method:`GET`,route:`/system/workflows/registry/get/{kind}`,arguments:[`kind`]},"system:workflows:registry:handles":{method:`GET`,route:`/system/workflows/registry/handles`,arguments:[]},"system:workflows:registry:list":{method:`GET`,route:`/system/workflows/registry/list`,arguments:[]},"system:workflows:run:events":{method:`GET`,route:`/system/workflows/run/events/{run_id}`,arguments:[`run_id`]},"system:workflows:run:get":{method:`GET`,route:`/system/workflows/run/get/{run_id}`,arguments:[`run_id`]},"system:workflows:run:list":{method:`GET`,route:`/system/workflows/run/list`,arguments:[]},"system:workflows:run:outcome":{method:`GET`,route:`/system/workflows/run/outcome/{run_id}`,arguments:[`run_id`]},"system:workflows:run:store":{method:`GET`,route:`/system/workflows/run/store/{run_id}`,arguments:[`run_id`]},"system:workflows:run:stream":{method:`GET`,route:`/system/workflows/run/stream/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:abort":{method:`DELETE`,route:`/system/workflows/runtime/abort/{run_id}`,arguments:[`run_id`]},"system:workflows:runtime:events":{method:`POST`,route:`/system/workflows/runtime/events`,arguments:[]},"system:workflows:runtime:has":{method:`GET`,route:`/system/workflows/runtime/has/{id}`,arguments:[`id`]},"system:workflows:runtime:invoke":{method:`POST`,route:`/system/workflows/runtime/invoke`,arguments:[]},"system:workflows:runtime:list":{method:`GET`,route:`/system/workflows/runtime/list`,arguments:[]},"system:workflows:runtime:resume":{method:`POST`,route:`/system/workflows/runtime/resume`,arguments:[]},"system:workflows:runtime:run":{method:`POST`,route:`/system/workflows/runtime/run`,arguments:[]}};var h=class{data;status;constructor(e,t){this.data=e,this.status=t}},g=class{baseUrl;apiPrefix;onAuthStateChanged;defaultHeaders;raw;streams=new Set;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.onAuthStateChanged=r,this.defaultHeaders=i,this.raw=e({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`,...this.defaultHeaders?{defaultHeaders:this.defaultHeaders}:{}})}substituteArgs(e,t){return e.replace(/\{(\w+)(\*)?\}/g,(e,n,r)=>t[n]?r?t[n].split(`/`).map(encodeURIComponent).join(`/`):encodeURIComponent(t[n]):`{${n}}`)}async dispatch(e,t){let r=m[e];if(!r)throw new n({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});let i=this.substituteArgs(r.route,t?.arguments??{}),a=r.method,o={},s=t?.notifyAuthStateChange??!0;if(t?.headers&&(o.headers=t.headers),t?.responseType&&(o.responseType=t.responseType),t?.bodyType&&(o.bodyType=t.bodyType),t?.signal&&(o.signal=t.signal),t?.modifiers){let e=Object.entries(t.modifiers).flatMap(([e,t])=>(Array.isArray(t)?t:[t]).map(t=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join(`&`);if(e){let n=i.includes(`?`)?`&`:`?`;return this.request(a,`${i}${n}${e}`,t?.payload,o,s)}}return this.request(a,i,t?.payload,o,s)}routeUrl(e,t){let r=m[e];if(!r)throw new n({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e}`});return`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(this.substituteArgs(r.route,t??{}))}`}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(){}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,t,n,r,i=!1){let a=this.canonicalPath(t),o={};r?.headers&&(o.headers={...r.headers}),r?.responseType&&(o.responseType=r.responseType),r?.bodyType&&(o.bodyType=r.bodyType),r?.signal&&(o.signal=r.signal),o.headers||={};let s;if(e===`GET`)s=await this.raw.get(a,o);else{let t=r?.bodyType?{type:r.bodyType}:void 0;s=await this.raw[e.toLowerCase()](a,n,o,t)}if(s.success||s.status===204)return new h(s.data,s.status);s.status===401&&i&&this.onAuthStateChanged?.();let c=s.raw?await l(s.raw):null;throw u(s,c)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,t,n){let r=new AbortController,i=n?.signal?AbortSignal.any([r.signal,n.signal]):r.signal;this.streams.add(r);try{let r={Accept:`text/event-stream`,...this.defaultHeaders??{},...n?.headers??{}},a=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,o;try{o=await fetch(a,{method:`GET`,headers:r,credentials:n?.credentials??`same-origin`,signal:i})}catch(e){if(e instanceof Error&&e.name===`AbortError`){t.onClose?.();return}t.onError?.(e instanceof Error?e:Error(String(e)));return}if(!o.ok||!o.body){t.onError?.(Error(`Stream request failed with status ${o.status}`));return}t.onOpen?.();let s=o.body.getReader(),c=new TextDecoder,l=``;try{for(;;){let{done:e,value:n}=await s.read();if(e)break;l+=c.decode(n,{stream:!0});let r=l.indexOf(`
|
|
2
2
|
|
|
3
|
-
`);for(;r!==-1;){let e=
|
|
3
|
+
`);for(;r!==-1;){let e=l.slice(0,r);l=l.slice(r+2);let n=e.split(`
|
|
4
4
|
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());n.length>0&&t.onMessage(n.join(`
|
|
5
|
-
`)),r=
|
|
5
|
+
`)),r=l.indexOf(`
|
|
6
6
|
|
|
7
|
-
`)}}}catch(e){e instanceof Error&&e.name===`AbortError`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}}};const _=g;function v(){let e=[],t=`active`,n=null,r=()=>{if(!n)return;let e=n;n=null,e()},i=n=>{t===`active`&&(e.push(n),r())},a=()=>{t===`active`&&(t=`completed`),r()},o=()=>{t===`active`&&(t=`cancelled`),r()};async function*s(){for(;t===`active`;){if(e.length>0){yield e.shift();continue}await new Promise(r=>{n=r,(e.length>0||t!==`active`)&&(n=null,r())})}for(;e.length>0;)yield e.shift()}return{stream:()=>s(),push:i,end:a,cancel:o,status:()=>t}}function ee(){try{let e=window.go;if(!e)return null;for(let t of Object.values(e))for(let e of Object.values(t))if(e?.Dispatch)return e;return null}catch{return null}}function y(){throw new n({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var b=class{baseUrl=``;apiPrefix=``;init=new i({throws:!0});config;http;onUnauthorized;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new g(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new g(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new g(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return ee()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw y();return this.http.routeUrl(e,t)}async ready(e=1e4){await this.init.do(async()=>{let t=Date.now();for(;!this.resolveService();){if(Date.now()-t>e)throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`Timed out after ${e}ms waiting for Wails bindings on window.go. Are you running inside a Wails desktop window?`});await new Promise(e=>setTimeout(e,50))}},e)}async dispatch(e,t){if(await this.ready(),this.http&&(t?.bodyType===`blob`||t?.bodyType===`stream`))return this.http.dispatch(e,t);let r=t?.notifyAuthStateChange??!0,a=t?.payload??null,o={...t?.modifiers??{}};t?.headers?.[`Content-Type`]&&(o.content_type=t.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:t?.arguments??{},modifiers:o,payload:a})}catch(t){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,t?.message??t),t instanceof n?t:new n({code:`DISPATCH_ERROR`,message:t?.message??String(t)})}if(c.status>=400){let t=c.data?.error,a=t?.code??`UNKNOWN`,o=t?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&r&&(this.init=new i({throws:!0}),this.onUnauthorized?.()),new n({code:a,message:o})}return new h(c.data,c.status)}throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Dispatch binding found on window.go. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}.`})}async check(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw y();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.delete(e,t,n)}async openStream(e,t,r){let i=this.resolveService();try{if(!i?.Stream)throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Stream binding found. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}`});let r=await i.Stream(e),a=`hestia:stream:${e}`;window.runtime?.EventsOn(a,e=>{t.onMessage(typeof e==`string`?e:JSON.stringify(e))}),t.onOpen?.(),r&&t.onMessage(r),t.onClose?.()}catch(e){t.onError?.(e instanceof Error?e:Error(String(e))),t.onClose?.()}}};const x=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),S={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function C(e,t,n,i){let o=n.page??1,s=n.size??20,c=n.sort,l=n.filter,u=new r({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:a,page:{number:1,size:20,count:0,total:0,pages:1}}});let f=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},p=async e=>(await t.set({[d]:{loading:!0,error:a}}),await new Promise(n=>{n(u.do(async()=>{x(()=>{x(async()=>{try{let n=await i(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...S,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??S,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await p({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await p()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await p()},filter:async e=>{l=e,o=1,await p()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),p(e)])},subscribe:e=>m.subscribe(e),invalidate:async()=>{await t.set({[d]:a}),h()},id:()=>d}}const te=new Set([`id`,`metadata`]);function w(e){return new Proxy(e,{get(e,t,n){if(te.has(t)&&!(t in e))return t===`id`?()=>e._id_:()=>e._metadata_;let r=Reflect.get(e,t,n);return typeof r==`function`?r.bind(e):r}})}function T(e){return{...e,data:e.data.map(w)}}const ne=new Set([`_id_`,`_metadata_`]);function E(e){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return[...e];let t={};for(let[n,r]of Object.entries(e))ne.has(n)||(t[n]=r);return t}var D=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=C(t,new o({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.collectionName},payload:e??{}}),n=t.data?.data??[];return T({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.collectionName,doc_id:e}})).data?.data;return t?w(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=await this.client.dispatch(`system:collections:document:create`,{arguments:{name:this.collectionName},payload:E(e.data)});return t.data?w(t.data.data):void 0}async update(e){let t=!!e.id,n=!!e.filter;if(t===n)throw Error(`update requires exactly one of id or filter`);let r=E(e.data);if(n){let t=await this.client.dispatch(`system:collections:document:update_many`,{arguments:{name:this.collectionName},payload:{set:r,filter:e.filter}});return t.data?w(t.data.data):void 0}let i=await this.client.dispatch(`system:collections:document:update`,{arguments:{name:this.collectionName,doc_id:e.id},payload:r});return i.data?w(i.data.data):void 0}async delete(e){await this.client.dispatch(`system:collections:document:delete`,{arguments:{name:this.collectionName,doc_id:e}})}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},O=class e{client;viewName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.viewName=t,this.defaultLimit=n,this.pager=C(t,new o({}),this.pagerOptions,e=>this.find(e))}static async create(t,n){return await t.dispatch(`system:collections:view:create`,{arguments:{name:n.name},payload:{query:n.query,materialized:n.materialized??!1}}),new e(t,n.name)}name(){return this.viewName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.viewName},payload:e??{}}),n=t.data?.data??[];return T({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.viewName,doc_id:e}})).data?.data;return t?w(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async refresh(){let e=(await this.client.dispatch(`system:collections:view:refresh`,{arguments:{name:this.viewName}})).data?.data;return e?w(e):void 0}async create(e){throw Error(`Create not supported for views: views are read-only`)}async update(e){throw Error(`Update not supported for views: views are read-only`)}async delete(e){throw Error(`Delete not supported for views: views are read-only`)}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for views`)}async subscribe(e,t){throw Error(`Subscription not implemented for views`)}async notify(e){throw Error(`Notify not implemented for views`)}stream(e,t){throw Error(`Stream not supported for views`)}page(e){return this.pager}},k=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.dispatch(`system:core:health:check`)).data.data}async session(){try{let e=await this.client.dispatch(`system:auth:session:get`,{notifyAuthStateChange:!1});return await this.provider.setIdentity(e.data.data.user),e.data.data}catch(e){if(A(e))return await this.provider.clear(),null;throw e}}async login(e,t){let n=await this.client.dispatch(`system:auth:session:create`,{payload:{email:e,password:t}});return await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{payload:{email:e,password:t,name:n}})).data.data}async logout(){try{await this.client.dispatch(`system:auth:session:delete`)}catch(e){if(!re(e))throw e}finally{await this.provider.clear()}}async requestPasswordReset(e){await this.client.dispatch(`system:auth:password:reset`,{payload:{email:e}})}async confirmPasswordReset(e,t){await this.client.dispatch(`system:auth:password:confirm`,{payload:{password:t,token:e}})}async bootstrap(e,t,n){await this.client.dispatch(`system:auth:bootstrap:password:set`,{payload:{password:t,email:n},headers:{"X-API-Key":e}})}};function A(e){return e?.httpStatus===401||e?.code===`UNAUTHORIZED`||e?.code===`UNAUTHENTICATED`||e?.code===`AUTH_REQUIRED`||e?.code===`AUTH-002-UNAUTH`}function re(e){return e?.code===`NO_ACTIVE_SESSION`||A(e)||e?.message?.includes(`no active session`)}var j=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=C(`users`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections:user:query`,{payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.dispatch(`system:users:user:get`,{arguments:{user_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){if(e.filter)throw Error(`filter-based update not supported for users`);if(!e.id)throw Error(`user id is required for update`);return(await this.client.dispatch(`system:users:user:update`,{arguments:{user_id:e.id},payload:E(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:users:user:delete`,{arguments:{user_id:e}})}async create({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:E(e)})).data.data}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.dispatch(`system:users:password:change`,{arguments:{user_id:e},payload:{current:t,new:n}})}},M=class{client;pager;constructor(e){this.client=e,this.pager=C(`_api_key_`,new o({}),{},e=>this.find(e))}async find(e){let t=await this.client.dispatch(`system:apikeys:key:list`),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.dispatch(`system:apikeys:key:get`,{arguments:{key_id:e}})).data?.data}catch(e){if(e?.code===`DOCUMENT_NOT_FOUND`||e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.dispatch(`system:apikeys:key:create`,{payload:E(e.data)})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for API keys`);if(!e.id)throw Error(`key id is required for update`);return(await this.client.dispatch(`system:apikeys:key:update`,{arguments:{key_id:e.id},payload:E(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:apikeys:key:delete`,{arguments:{key_id:e}})}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.dispatch(`system:apikeys:key:rotate`,{arguments:{key_id:e}})).data.data}};function N(e){let t=e;return{...e,_id_:t._id_??e.name,_metadata_:t._metadata_??{checksum:``,created:``,updated:``,version:1}}}var P=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>N(e)),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:binding:get`,{arguments:{name:e}});return t.data?.data?N(t.data.data):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},F=class{client;pager;constructor(e){this.client=e,this.pager=C(`policies`,new o({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.dispatch(`system:collections:operation_policy:query`,{payload:e}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for policies`);let t=e.id;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}},I=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.dispatch(`system:policies:rule:list`)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:rule:get`,{arguments:{name:e}});if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.dispatch(`system:policies:rule:create`,{arguments:{name:t},payload:E(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){if(e.filter)throw Error(`filter-based update not supported for policy rules`);let t=e.id;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.dispatch(`system:policies:rule:update`,{arguments:{name:t},payload:E(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.dispatch(`system:policies:rule:delete`,{arguments:{name:e}})}async validate(e){return(await this.client.dispatch(`system:policies:rule:validate`,{payload:e})).data?.data??{valid:!1}}async reload(){return(await this.client.dispatch(`system:policies:reload`)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},L=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=C(`_audit_log_`,new o({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/audit_log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=v(),r=new AbortController,i=!1,a=()=>{i||(i=!0,n.status()===`active`&&this.client.openStream(`/system/audit/log/stream`,{onMessage(e){try{let t=JSON.parse(e);t?.data&&n.push(t.data)}catch{}},onError:()=>n.end(),onClose:()=>n.end()},{signal:r.signal}).catch(()=>n.end()))},o=async function*(){a(),yield*n.stream()};return{stream:()=>o(),cancel:()=>{r.abort(),n.cancel()},status:n.status}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}},R=class{client;baseUrl;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n}async query(e){return(await this.client.post(`/system/logs/list`,e??{})).data?.data??{entries:[],total:0,has_more:!1}}stream(e){let t=v(),n=new AbortController,r=new URLSearchParams;e?.level&&r.set(`level`,e.level);let i=r.toString(),a=`/system/logs/stream${i?`?`+i:``}`,o=!1,s=()=>{o||(o=!0,t.status()===`active`&&this.client.openStream(a,{onMessage(e){try{let n=JSON.parse(e);n?.data&&t.push(n.data)}catch{}},onError:()=>t.end(),onClose:()=>t.end()},{signal:n.signal}).catch(()=>t.end()))},c=async function*(){s(),yield*t.stream()};return{stream:()=>c(),cancel:()=>{n.abort(),t.cancel()},status:t.status}}getStreamUrl(e){let t=new URLSearchParams;e?.level&&t.set(`level`,e.level);let n=t.toString();return`${this.baseUrl}${this.apiPrefix}/system/logs/stream${n?`?`+n:``}`}};const z=.3;function B(e){return new Promise(t=>setTimeout(t,e))}async function V(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function ie(e,t,n){return e.slice(t,n)}function H(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function U(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function ae(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var W=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-z)+e*z}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},oe=class{backing;state={jobs:{}};instanceId=H();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},G=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;startedAt=Date.now();blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??H(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new W(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=U(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await B(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await ie(this.file,t,i).arrayBuffer();this.blockHashes[r]=await V(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await B(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await V(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=ae(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=ie(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await B(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},K=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;ns;constructor(e,t,n={}){this.transport=e,this.ns=t,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new G(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new G(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function q(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function se(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var J=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=C(`blobs_${t}`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.dispatch(`system:blobs:blob:list`,{arguments:{ns:this.ns},payload:r})).data?.data?.blobs??[];return{data:i.map(q),loading:!1,page:se(i),error:void 0}}async read(e){try{let t=await this.client.dispatch(`system:blobs:blob:head`,{arguments:{ns:this.ns,key:e}});return t.data?.data?q(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){if(e.filter)throw Error(`filter-based update not supported for blobs`);let t=e.id;if(!t)throw Error(`id is required for blob update`);return q((await this.client.dispatch(`system:blobs:blob:update`,{arguments:{ns:this.ns,key:t},payload:{custom:E(e.data)}})).data.data)}async delete(e){await this.client.dispatch(`system:blobs:blob:delete`,{arguments:{ns:this.ns,key:e}})}async rename(e,t){await this.client.dispatch(`system:blobs:blob:rename`,{arguments:{ns:this.ns,key:e},payload:{new_key:t}})}async stats(){return(await this.client.dispatch(`system:blobs:namespace:stats`,{arguments:{ns:this.ns}})).data.data}async verify(){await this.client.dispatch(`system:blobs:namespace:verify`,{arguments:{ns:this.ns}})}async compact(){return(await this.client.dispatch(`system:blobs:namespace:compact`,{arguments:{ns:this.ns}})).data.data}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new G(this,e,n,t,this.persistence)}queue(e){return this._queue||=new K(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),q((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return q((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.dispatch(`system:blobs:blob:download`,{arguments:{ns:this.ns,key:e},responseType:`blob`})).data;return{data:t,contentType:t.type}}},Y=class{client;uploadPersistence;apiPrefix;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n,this.apiPrefix=t}async namespaces(){return(await this.client.dispatch(`system:blobs:namespace:list`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.dispatch(`system:blobs:namespace:create`,{arguments:{ns:e.ns},payload:{display_name:e.display_name,custom:e.custom}})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return this.client.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new J(this.client,e,this.uploadPersistence)}},X=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:collections:collection:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});return t.data?t.data.data:void 0}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){let t=e.data.schema??e.data;return(await this.client.dispatch(`system:collections:collection:create`,{payload:t})).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.dispatch(`system:collections:collection:delete`,{arguments:{name:e}})}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new D(this.client,e)}view(e){return new O(this.client,e)}},Z=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:notifications:notification:create`,{payload:E(e)})).data.data}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}stream(e,t){let n=new AbortController,r=AbortSignal.any([n.signal,...t?.signal?[t.signal]:[]]);return this.client.openStream(`/system/notifications/notification/stream`,{onMessage(t){try{let n=JSON.parse(t),r=n.data??n;e.onMessage(r)}catch(t){e.onError?.(t instanceof Error?t:Error(String(t)))}},onError:e.onError,onOpen:e.onOpen,onClose:e.onClose},{...t,signal:r}).catch(t=>{e.onError?.(t instanceof Error?t:Error(String(t)))}),n}async dispatchAction(e){if(!e.message)throw Error(`action has no message to dispatch`);await this.client.dispatch(e.message,{arguments:e.arguments??{}})}},Q=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:E(e)})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async all(){return(await this.client.dispatch(`system:schedules:schedule:all`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:E(t)})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},ce=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},le=class{client;constructor(e){this.client=e}async status(){return(await this.client.dispatch(`system:updates:status:get`)).data.data}async changelog(){return(await this.client.dispatch(`system:updates:changelog:get`)).data.data}async checkAvailability(){return(await this.client.dispatch(`system:updates:check:get`)).data.data}async stage(){return(await this.client.dispatch(`system:updates:stage:create`)).data.data}async check(){return(await this.client.dispatch(`system:updates:check:create`)).data.data}async apply(){return(await this.client.dispatch(`system:updates:update:apply`)).data.data}};let $=null;function ue(){return $}var de=class{client;constructor(e){this.client=e}async compile(e,t){return(await this.client.dispatch(`system:workflows:definition:compile`,{payload:{nodes:e,edges:t}})).data?.data}async create(e){return(await this.client.dispatch(`system:workflows:definition:create`,{payload:e})).data?.data?.id??``}async delete(e){await this.client.dispatch(`system:workflows:definition:delete`,{arguments:{id:e}})}async update(e,t){await this.client.dispatch(`system:workflows:definition:update`,{arguments:{id:e},payload:t})}async list(){return(await this.client.dispatch(`system:workflows:definition:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:workflows:definition:get`,{arguments:{id:e}})).data?.data??null}async run(e){return(await this.client.dispatch(`system:workflows:runtime:run`,{payload:e})).data?.data?.run_id??``}async emitEvent(e){await this.client.dispatch(`system:workflows:runtime:events`,{payload:e})}async abort(e){await this.client.dispatch(`system:workflows:runtime:abort`,{arguments:{run_id:e}})}async listRuns(){return(await this.client.dispatch(`system:workflows:run:list`)).data?.data??[]}async getRun(e){return(await this.client.dispatch(`system:workflows:run:get`,{arguments:{run_id:e}})).data?.data??null}async getOutcome(e){return(await this.client.dispatch(`system:workflows:run:outcome`,{arguments:{run_id:e}})).data?.data??null}async getEvents(e){return(await this.client.dispatch(`system:workflows:run:events`,{arguments:{run_id:e}})).data?.data?.events??[]}async getStore(e){return(await this.client.dispatch(`system:workflows:run:store`,{arguments:{run_id:e}})).data?.data?.state??null}async getRegistry(){return(await this.client.dispatch(`system:workflows:registry:list`)).data?.data?.nodes??[]}async getNodeDefinition(e){return(await this.client.dispatch(`system:workflows:registry:get`,{arguments:{kind:e}})).data?.data??null}async fetchHandles(){if($)return $;try{let e=(await this.client.dispatch(`system:workflows:registry:handles`)).data?.data?.code;return e?($=Function(`return (${e})`)(),$):($={},$)}catch{return $={},$}}async hasWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:has`,{arguments:{id:e}})).data?.data?.has??!1}async listWorkflows(){return(await this.client.dispatch(`system:workflows:runtime:list`)).data?.data?.workflow_ids??[]}async invokeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:invoke`,{payload:e})).data?.data}async resumeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:resume`,{payload:e})).data?.data}streamRun(e,t,n){let r=new AbortController,i=AbortSignal.any([r.signal,...n?.signal?[n.signal]:[]]);return this.client.openStream(`/system/workflows/run/stream/${encodeURIComponent(e)}`,{onMessage:e=>{try{let n=JSON.parse(e),r=n.data??n;t.onEvent(r)}catch{}},onError:t.onError,onOpen:t.onOpen,onClose:t.onDone},{...n,signal:i}).catch(e=>{t.onError?.(e instanceof Error?e:Error(String(e)))}),r}},fe=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:core:docs:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},pe=class{store;client;auth;users;keys;policies;rules;auditLogs;appLogs;collections;blobs;core;notifications;schedules;settings;updates;workflows;operations;tokenProvider;apiKeyMode;autoHeartbeat;authChannel;applyingRemoteAuth=!1;constructor(e){this.store=new o({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},n=e.apiPrefix??`/api`,r=e.apiKey?{"X-Api-Key":e.apiKey}:void 0,i=()=>{t.clear()};this.tokenProvider=t,this.apiKeyMode=!!e.apiKey,this.autoHeartbeat=e.autoHeartbeat!==!1,e.transport instanceof b?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(i),this.client=e.transport):this.client=e.transport??new g(e.baseUrl,n,i,r),this.auth=new k(this.client,t),this.users=new j(this.client),this.keys=new M(this.client),this.policies=new F(this.client),this.rules=new I(this.client),this.auditLogs=new L(this.client,e.baseUrl,n),this.appLogs=new R(this.client,e.baseUrl,n),this.collections=new X(this.client),this.blobs=new Y(this.client,n,e.uploadPersistence),this.core=new fe(this.client),this.notifications=new Z(this.client),this.schedules=new Q(this.client),this.settings=new ce(this.client),this.updates=new le(this.client),this.workflows=new de(this.client),this.operations=new P(this.client),this.store.watch(`identity`,e=>{e.identity?this.autoHeartbeat&&this.startHeartbeat():this.stopHeartbeat(),this.applyingRemoteAuth||this.authChannel?.postMessage(`changed`)}),this.setupAuthChannel(e.baseUrl)}setupAuthChannel(e){if(typeof BroadcastChannel>`u`)return;let t=`hestia:auth:${e.replace(/\/+$/,``)}`;try{this.authChannel=new BroadcastChannel(t),this.authChannel.unref?.()}catch{return}this.authChannel.addEventListener(`message`,()=>{this.applyRemoteAuthChange()})}async applyRemoteAuthChange(){if(!this.applyingRemoteAuth){this.applyingRemoteAuth=!0;try{await this.auth.session()}catch{}finally{this.applyingRemoteAuth=!1}}}onAuthStateChange(e){return this.store.watch(`identity`,t=>{e(t.identity??null)})}async authenticated(){if(this.apiKeyMode)return!0;if(this.tokenProvider.identity()===null)return await this.auth.session()!==null;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){if(this.heartbeatTimer!==void 0&&e===void 0)return;this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}view(e){return this.collections.view(e)}ready(){return this.client.ready()}};function me(e){let t=`${e.collectionName}_array_pager_state_`,n=new o({}),r=[...e.initialData??[]],i=`collection`,l,u=e.page??1,d=e.size??20,f=[],p,m,{match:h}=s(e.customFunctions??{}),{sort:g}=c(),_=n.select(e=>e[t]),v={data:[],loading:!0,error:void 0,page:{number:1,size:d,count:0,total:0,pages:1}},ee=()=>({filters:p,sort:f,pagination:{type:`offset`,offset:(u-1)*d,limit:d}}),y=async(a=!0)=>{if(e.fetch){if(m=void 0,a){let e=_.get()??v;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=ee(),n=await e.fetch(t);i=n.scope,l=n.total,r=n.replace?[...n.data]:[...r,...n.data]}catch(e){m=e}}let o=b(e.fetch?a:!1);await n.set({[t]:o})},b=e=>{let t=[...r];if(i===`collection`){p&&(t=t.filter(e=>h(e,p))),f.length>0&&(t=g(t,f));let n=t.length,r=Math.ceil(n/d)||1;u>r&&(u=r),u<1&&(u=1);let i=(u-1)*d,a=t.slice(i,i+d);return{data:a,loading:e,error:m,page:{number:u,size:d,count:a.length,total:n,pages:r}}}let n=l??t.length,a=Math.ceil(n/d)||1;return{data:t,loading:e,error:m,page:{number:u,size:d,count:t.length,total:n,pages:a}}};return y(!0),{id:()=>t,page:()=>_.get()??v,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);u=e,await y(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);d=e,u=t,await y(!0)},sort:async e=>{f=Array.isArray(e)?e:[e],u=1,await y(!0)},filter:async e=>{p=e,u=1,await y(!0)},refresh:async e=>{let r=_.get()??v;await n.set({[t]:{...r,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),y(!1)]);let a=_.get()??v;await n.set({[t]:{...a,loading:!1}})},subscribe:e=>_.subscribe(t=>{e(t)}),invalidate:async()=>{await n.set({[t]:a}),r=[]}}}export{W as AimdController,J as BlobNamespace,R as HestiaAppLogs,L as HestiaAuditLogs,k as HestiaAuth,Y as HestiaBlobClient,pe as HestiaClient,D as HestiaCollection,X as HestiaCollections,fe as HestiaCore,O as HestiaDataView,M as HestiaKeyStore,_ as HestiaNetworkClient,Z as HestiaNotificationStore,P as HestiaOperations,F as HestiaPolicies,h as HestiaResponse,I as HestiaRules,Q as HestiaScheduleStore,ce as HestiaSettingStore,le as HestiaUpdates,j as HestiaUsers,de as HestiaWorkflowStore,g as HttpTransport,G as ResumableUpload,oe as UploadJobStore,K as UploadQueue,b as WailsTransport,me as createArrayPager,v as createAsyncStream,C as createPagedController,ue as getCachedHandles,U as getMissingRanges,p as internalError,d as notFound,l as parseErrorBody,f as permissionDenied,w as proxiedDocument,T as proxiedPage,u as toSystemError};
|
|
7
|
+
`)}}}catch(e){e instanceof Error&&e.name===`AbortError`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}}finally{this.streams.delete(r)}}close(){for(let e of this.streams)e.abort()}};const _=g;function v(){let e=[],t=`active`,n=null,r=()=>{if(!n)return;let e=n;n=null,e()},i=n=>{t===`active`&&(e.push(n),r())},a=()=>{t===`active`&&(t=`completed`),r()},o=()=>{t===`active`&&(t=`cancelled`),r()};async function*s(){for(;t===`active`;){if(e.length>0){yield e.shift();continue}await new Promise(r=>{n=r,(e.length>0||t!==`active`)&&(n=null,r())})}for(;e.length>0;)yield e.shift()}return{stream:()=>s(),push:i,end:a,cancel:o,status:()=>t}}function y(){try{let e=window.go;if(!e)return null;for(let t of Object.values(e))for(let e of Object.values(t))if(e?.Dispatch)return e;return null}catch{return null}}function b(){throw new n({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var x=class{baseUrl=``;apiPrefix=``;init=new i({throws:!0});config;http;onUnauthorized;streamEvents=new Set;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new g(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new g(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new g(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return y()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw b();return this.http.routeUrl(e,t)}async ready(e=1e4){await this.init.do(async()=>{let t=Date.now();for(;!this.resolveService();){if(Date.now()-t>e)throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`Timed out after ${e}ms waiting for Wails bindings on window.go. Are you running inside a Wails desktop window?`});await new Promise(e=>setTimeout(e,50))}},e)}async dispatch(e,t){if(await this.ready(),this.http&&(t?.bodyType===`blob`||t?.bodyType===`stream`))return this.http.dispatch(e,t);let r=t?.notifyAuthStateChange??!0,a=t?.payload??null,o={...t?.modifiers??{}};t?.headers?.[`Content-Type`]&&(o.content_type=t.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:t?.arguments??{},modifiers:o,payload:a})}catch(t){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,t?.message??t),t instanceof n?t:new n({code:`DISPATCH_ERROR`,message:t?.message??String(t)})}if(c.status>=400){let t=c.data?.error,a=t?.code??`UNKNOWN`,o=t?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&r&&(this.init=new i({throws:!0}),this.onUnauthorized?.()),new n({code:a,message:o})}return new h(c.data,c.status)}throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Dispatch binding found on window.go. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}.`})}async check(e,t,n){if(await this.ready(),!this.http)throw b();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw b();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw b();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw b();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw b();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw b();return this.http.delete(e,t,n)}async openStream(e,t,r){let i=this.resolveService();try{if(!i?.Stream)throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Stream binding found. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}`});let r=await i.Stream(e),a=`hestia:stream:${e}`;window.runtime?.EventsOn(a,e=>{t.onMessage(typeof e==`string`?e:JSON.stringify(e))}),this.streamEvents.add(a),t.onOpen?.(),r&&t.onMessage(r),t.onClose?.()}catch(e){t.onError?.(e instanceof Error?e:Error(String(e))),t.onClose?.()}}close(){for(let e of this.streamEvents)window.runtime?.EventsOff(e);this.streamEvents.clear(),this.http?.close()}};const S=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),C={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function w(e,t,n,i){let o=n.page??1,s=n.size??20,c=n.sort,l=n.filter,u=new r({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:a,page:{number:1,size:20,count:0,total:0,pages:1}}});let f=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},p=async e=>(await t.set({[d]:{loading:!0,error:a}}),await new Promise(n=>{n(u.do(async()=>{S(()=>{S(async()=>{try{let n=await i(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...C,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??C,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await p({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await p()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await p()},filter:async e=>{l=e,o=1,await p()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),p(e)])},subscribe:e=>m.subscribe(e),invalidate:async()=>{await t.set({[d]:a}),h()},id:()=>d}}const ee=new Set([`id`,`metadata`]);function T(e){return new Proxy(e,{get(e,t,n){if(ee.has(t)&&!(t in e))return t===`id`?()=>e._id_:()=>e._metadata_;let r=Reflect.get(e,t,n);return typeof r==`function`?r.bind(e):r}})}function E(e){return{...e,data:e.data.map(T)}}const te=new Set([`_id_`,`_metadata_`]);function D(e){if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return[...e];let t={};for(let[n,r]of Object.entries(e))te.has(n)||(t[n]=r);return t}var O=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=w(t,new o({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.collectionName},payload:e??{}}),n=t.data?.data??[];return E({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.collectionName,doc_id:e}})).data?.data;return t?T(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=await this.client.dispatch(`system:collections:document:create`,{arguments:{name:this.collectionName},payload:D(e.data)});return t.data?T(t.data.data):void 0}async update(e){let t=!!e.id,n=!!e.filter;if(t===n)throw Error(`update requires exactly one of id or filter`);let r=D(e.data);if(n){let t=await this.client.dispatch(`system:collections:document:update_many`,{arguments:{name:this.collectionName},payload:{set:r,filter:e.filter}});return t.data?T(t.data.data):void 0}let i=await this.client.dispatch(`system:collections:document:update`,{arguments:{name:this.collectionName,doc_id:e.id},payload:r});return i.data?T(i.data.data):void 0}async delete(e){await this.client.dispatch(`system:collections:document:delete`,{arguments:{name:this.collectionName,doc_id:e}})}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},k=class e{client;viewName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.viewName=t,this.defaultLimit=n,this.pager=w(t,new o({}),this.pagerOptions,e=>this.find(e))}static async create(t,n){return await t.dispatch(`system:collections:view:create`,{arguments:{name:n.name},payload:{query:n.query,materialized:n.materialized??!1}}),new e(t,n.name)}name(){return this.viewName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.viewName},payload:e??{}}),n=t.data?.data??[];return E({data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null})}async read(e){try{let t=(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.viewName,doc_id:e}})).data?.data;return t?T(t):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async refresh(){let e=(await this.client.dispatch(`system:collections:view:refresh`,{arguments:{name:this.viewName}})).data?.data;return e?T(e):void 0}async create(e){throw Error(`Create not supported for views: views are read-only`)}async update(e){throw Error(`Update not supported for views: views are read-only`)}async delete(e){throw Error(`Delete not supported for views: views are read-only`)}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for views`)}async subscribe(e,t){throw Error(`Subscription not implemented for views`)}async notify(e){throw Error(`Notify not implemented for views`)}stream(e,t){throw Error(`Stream not supported for views`)}page(e){return this.pager}},ne=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.dispatch(`system:core:health:check`)).data.data}async session(){try{let e=await this.client.dispatch(`system:auth:session:get`,{notifyAuthStateChange:!1});return await this.provider.setIdentity(e.data.data.user),e.data.data}catch(e){if(re(e))return await this.provider.clear(),null;throw e}}async login(e,t){let n=await this.client.dispatch(`system:auth:session:create`,{payload:{email:e,password:t}});return await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{payload:{email:e,password:t,name:n}})).data.data}async logout(){try{await this.client.dispatch(`system:auth:session:delete`)}catch(e){if(!ie(e))throw e}finally{await this.provider.clear()}}async requestPasswordReset(e){await this.client.dispatch(`system:auth:password:reset`,{payload:{email:e}})}async confirmPasswordReset(e,t){await this.client.dispatch(`system:auth:password:confirm`,{payload:{password:t,token:e}})}async bootstrap(e,t,n){await this.client.dispatch(`system:auth:bootstrap:password:set`,{payload:{password:t,email:n},headers:{"X-API-Key":e}})}};function re(e){return e?.httpStatus===401||e?.code===`UNAUTHORIZED`||e?.code===`UNAUTHENTICATED`||e?.code===`AUTH_REQUIRED`||e?.code===`AUTH-002-UNAUTH`}function ie(e){return e?.code===`NO_ACTIVE_SESSION`||re(e)||e?.message?.includes(`no active session`)}var A=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=w(`users`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections:user:query`,{payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.dispatch(`system:users:user:get`,{arguments:{user_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){if(e.filter)throw Error(`filter-based update not supported for users`);if(!e.id)throw Error(`user id is required for update`);return(await this.client.dispatch(`system:users:user:update`,{arguments:{user_id:e.id},payload:D(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:users:user:delete`,{arguments:{user_id:e}})}async create({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:D(e)})).data.data}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.dispatch(`system:users:password:change`,{arguments:{user_id:e},payload:{current:t,new:n}})}},j=class{client;pager;constructor(e){this.client=e,this.pager=w(`_api_key_`,new o({}),{},e=>this.find(e))}async find(e){let t=await this.client.dispatch(`system:apikeys:key:list`),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.dispatch(`system:apikeys:key:get`,{arguments:{key_id:e}})).data?.data}catch(e){if(e?.code===`DOCUMENT_NOT_FOUND`||e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.dispatch(`system:apikeys:key:create`,{payload:D(e.data)})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for API keys`);if(!e.id)throw Error(`key id is required for update`);return(await this.client.dispatch(`system:apikeys:key:update`,{arguments:{key_id:e.id},payload:D(e.data)})).data.data}async delete(e){await this.client.dispatch(`system:apikeys:key:delete`,{arguments:{key_id:e}})}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.dispatch(`system:apikeys:key:rotate`,{arguments:{key_id:e}})).data.data}};function M(e){let t=e;return{...e,_id_:t._id_??e.name,_metadata_:t._metadata_??{checksum:``,created:``,updated:``,version:1}}}var N=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>M(e)),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:binding:get`,{arguments:{name:e}});return t.data?.data?M(t.data.data):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},P=class{client;pager;constructor(e){this.client=e,this.pager=w(`policies`,new o({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.dispatch(`system:collections:operation_policy:query`,{payload:e}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){if(e.filter)throw Error(`filter-based update not supported for policies`);let t=e.id;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}},F=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.dispatch(`system:policies:rule:list`)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:rule:get`,{arguments:{name:e}});if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.dispatch(`system:policies:rule:create`,{arguments:{name:t},payload:D(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){if(e.filter)throw Error(`filter-based update not supported for policy rules`);let t=e.id;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.dispatch(`system:policies:rule:update`,{arguments:{name:t},payload:D(e.data)});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.dispatch(`system:policies:rule:delete`,{arguments:{name:e}})}async validate(e){return(await this.client.dispatch(`system:policies:rule:validate`,{payload:e})).data?.data??{valid:!1}}async reload(){return(await this.client.dispatch(`system:policies:reload`)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},I=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=w(`_audit_log_`,new o({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/audit_log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=v(),r=new AbortController,i=!1,a=()=>{i||(i=!0,n.status()===`active`&&this.client.openStream(`/system/audit/log/stream`,{onMessage(e){try{let t=JSON.parse(e);t?.data&&n.push(t.data)}catch{}},onError:()=>n.end(),onClose:()=>n.end()},{signal:r.signal}).catch(()=>n.end()))},o=async function*(){a(),yield*n.stream()};return{stream:()=>o(),cancel:()=>{r.abort(),n.cancel()},status:n.status}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}},L=class{client;baseUrl;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n}async query(e){return(await this.client.post(`/system/logs/list`,e??{})).data?.data??{entries:[],total:0,has_more:!1}}stream(e){let t=v(),n=new AbortController,r=new URLSearchParams;e?.level&&r.set(`level`,e.level);let i=r.toString(),a=`/system/logs/stream${i?`?`+i:``}`,o=!1,s=()=>{o||(o=!0,t.status()===`active`&&this.client.openStream(a,{onMessage(e){try{let n=JSON.parse(e);n?.data&&t.push(n.data)}catch{}},onError:()=>t.end(),onClose:()=>t.end()},{signal:n.signal}).catch(()=>t.end()))},c=async function*(){s(),yield*t.stream()};return{stream:()=>c(),cancel:()=>{n.abort(),t.cancel()},status:t.status}}getStreamUrl(e){let t=new URLSearchParams;e?.level&&t.set(`level`,e.level);let n=t.toString();return`${this.baseUrl}${this.apiPrefix}/system/logs/stream${n?`?`+n:``}`}};const ae=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),R=Array(256);for(let e=0;e<256;e++)R[e]=e.toString(16).padStart(2,`0`);function oe(){try{let e=globalThis;return!!(e.__HESTIA_ALLOW_INSECURE_CRYPTO__||e.window?.__HESTIA_ALLOW_INSECURE_CRYPTO__)}catch{return!1}}function se(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=t.length,r=n*8>>>0,i=Math.floor(n/536870912)>>>0,a=1779033703,o=-1150833019,s=1013904242,c=-1521486534,l=1359893119,u=-1694144372,d=528734635,f=1541459225,p=new Uint32Array(64),m=(e,t)=>e>>>t|e<<32-t;function h(e,t){for(let n=0;n<16;n++){let r=t+(n<<2);p[n]=e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]}for(let e=16;e<64;e++){let t=p[e-15],n=p[e-2],r=m(t,7)^m(t,18)^t>>>3,i=m(n,17)^m(n,19)^n>>>10;p[e]=p[e-16]+r+p[e-7]+i|0}let n=a,r=o,i=s,h=c,g=l,_=u,v=d,y=f;for(let e=0;e<64;e++){let t=m(g,6)^m(g,11)^m(g,25),a=g&_^~g&v,o=y+t+a+ae[e]+p[e]|0,s=(m(n,2)^m(n,13)^m(n,22))+(n&r^n&i^r&i)|0;y=v,v=_,_=g,g=h+o|0,h=i,i=r,r=n,n=o+s|0}a=a+n|0,o=o+r|0,s=s+i|0,c=c+h|0,l=l+g|0,u=u+_|0,d=d+v|0,f=f+y|0}let g=n>>>6;for(let e=0;e<g;e++)h(t,e<<6);let _=g<<6,v=n-_,y=v<=55?64:128,b=new Uint8Array(y);b.set(t.subarray(_)),b[v]=128;let x=new DataView(b.buffer,b.byteOffset,b.byteLength);x.setUint32(y-8,i,!1),x.setUint32(y-4,r,!1),h(b,0),y===128&&h(b,64);let S=new Uint8Array(32),C=new DataView(S.buffer);C.setUint32(0,a,!1),C.setUint32(4,o,!1),C.setUint32(8,s,!1),C.setUint32(12,c,!1),C.setUint32(16,l,!1),C.setUint32(20,u,!1),C.setUint32(24,d,!1),C.setUint32(28,f,!1);let w=``;for(let e=0;e<32;e++)w+=R[S[e]];return w}async function z(e){let t=typeof crypto<`u`?crypto.subtle:void 0;if(t&&typeof t.digest==`function`){let n=await t.digest(`SHA-256`,e),r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=R[r[e]];return i}if(oe())return se(e);throw Error(`Web Crypto (crypto.subtle) is unavailable. File uploads require a secure context (HTTPS or localhost). For local development over HTTP you may set globalThis.__HESTIA_ALLOW_INSECURE_CRYPTO__ = true to enable a pure-JS fallback (not recommended for production).`)}const B=.3;function V(e){return new Promise(t=>setTimeout(t,e))}function ce(e,t,n){return e.slice(t,n)}function H(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function U(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function le(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var W=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-B)+e*B}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},ue=class{backing;state={jobs:{}};instanceId=H();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},G=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??H(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new W(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=U(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await V(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await ce(this.file,t,i).arrayBuffer();this.blockHashes[r]=await z(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await V(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await z(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=le(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=ce(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await V(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},K=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;constructor(e,t,n={}){this.transport=e,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new G(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new G(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function q(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function de(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var J=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=w(`blobs_${t}`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.dispatch(`system:blobs:blob:list`,{arguments:{ns:this.ns},payload:r})).data?.data?.blobs??[];return{data:i.map(q),loading:!1,page:de(i),error:void 0}}async read(e){try{let t=await this.client.dispatch(`system:blobs:blob:head`,{arguments:{ns:this.ns,key:e}});return t.data?.data?q(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){if(e.filter)throw Error(`filter-based update not supported for blobs`);let t=e.id;if(!t)throw Error(`id is required for blob update`);return q((await this.client.dispatch(`system:blobs:blob:update`,{arguments:{ns:this.ns,key:t},payload:{custom:D(e.data)}})).data.data)}async delete(e){await this.client.dispatch(`system:blobs:blob:delete`,{arguments:{ns:this.ns,key:e}})}async rename(e,t){await this.client.dispatch(`system:blobs:blob:rename`,{arguments:{ns:this.ns,key:e},payload:{new_key:t}})}async stats(){return(await this.client.dispatch(`system:blobs:namespace:stats`,{arguments:{ns:this.ns}})).data.data}async verify(){await this.client.dispatch(`system:blobs:namespace:verify`,{arguments:{ns:this.ns}})}async compact(){return(await this.client.dispatch(`system:blobs:namespace:compact`,{arguments:{ns:this.ns}})).data.data}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new G(this,e,n,t,this.persistence)}queue(e){return this._queue||=new K(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),q((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return q((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.dispatch(`system:blobs:blob:download`,{arguments:{ns:this.ns,key:e},responseType:`blob`})).data;return{data:t,contentType:t.type}}},Y=class{client;uploadPersistence;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n}async namespaces(){return(await this.client.dispatch(`system:blobs:namespace:list`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.dispatch(`system:blobs:namespace:create`,{arguments:{ns:e.ns},payload:{display_name:e.display_name,custom:e.custom}})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return this.client.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new J(this.client,e,this.uploadPersistence)}},X=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:collections:collection:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});return t.data?t.data.data:void 0}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){let t=e.data.schema??e.data;return(await this.client.dispatch(`system:collections:collection:create`,{payload:t})).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.dispatch(`system:collections:collection:delete`,{arguments:{name:e}})}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new O(this.client,e)}view(e){return new k(this.client,e)}},Z=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:notifications:notification:create`,{payload:D(e)})).data.data}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}stream(e,t){let n=new AbortController,r=AbortSignal.any([n.signal,...t?.signal?[t.signal]:[]]);return this.client.openStream(`/system/notifications/notification/stream`,{onMessage(t){try{let n=JSON.parse(t),r=n.data??n;e.onMessage(r)}catch(t){e.onError?.(t instanceof Error?t:Error(String(t)))}},onError:e.onError,onOpen:e.onOpen,onClose:e.onClose},{...t,signal:r}).catch(t=>{e.onError?.(t instanceof Error?t:Error(String(t)))}),n}async dispatchAction(e){if(!e.message)throw Error(`action has no message to dispatch`);await this.client.dispatch(e.message,{arguments:e.arguments??{}})}},fe=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:D(e)})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async all(){return(await this.client.dispatch(`system:schedules:schedule:all`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:D(t)})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},pe=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},me=class{client;constructor(e){this.client=e}async status(){return(await this.client.dispatch(`system:updates:status:get`)).data.data}async changelog(){return(await this.client.dispatch(`system:updates:changelog:get`)).data.data}async checkAvailability(){return(await this.client.dispatch(`system:updates:check:get`)).data.data}async stage(){return(await this.client.dispatch(`system:updates:stage:create`)).data.data}async check(){return(await this.client.dispatch(`system:updates:check:create`)).data.data}async apply(){return(await this.client.dispatch(`system:updates:update:apply`)).data.data}};let Q=null;function he(){return Q}var ge=class{client;constructor(e){this.client=e}async compile(e,t){return(await this.client.dispatch(`system:workflows:definition:compile`,{payload:{nodes:e,edges:t}})).data?.data}async create(e){return(await this.client.dispatch(`system:workflows:definition:create`,{payload:e})).data?.data?.id??``}async delete(e){await this.client.dispatch(`system:workflows:definition:delete`,{arguments:{id:e}})}async update(e,t){await this.client.dispatch(`system:workflows:definition:update`,{arguments:{id:e},payload:t})}async list(){return(await this.client.dispatch(`system:workflows:definition:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:workflows:definition:get`,{arguments:{id:e}})).data?.data??null}async run(e){return(await this.client.dispatch(`system:workflows:runtime:run`,{payload:e})).data?.data?.run_id??``}async emitEvent(e){await this.client.dispatch(`system:workflows:runtime:events`,{payload:e})}async abort(e){await this.client.dispatch(`system:workflows:runtime:abort`,{arguments:{run_id:e}})}async listRuns(){return(await this.client.dispatch(`system:workflows:run:list`)).data?.data??[]}async getRun(e){return(await this.client.dispatch(`system:workflows:run:get`,{arguments:{run_id:e}})).data?.data??null}async getOutcome(e){return(await this.client.dispatch(`system:workflows:run:outcome`,{arguments:{run_id:e}})).data?.data??null}async getEvents(e){return(await this.client.dispatch(`system:workflows:run:events`,{arguments:{run_id:e}})).data?.data?.events??[]}async getStore(e){return(await this.client.dispatch(`system:workflows:run:store`,{arguments:{run_id:e}})).data?.data?.state??null}async getRegistry(){return(await this.client.dispatch(`system:workflows:registry:list`)).data?.data?.nodes??[]}async getNodeDefinition(e){return(await this.client.dispatch(`system:workflows:registry:get`,{arguments:{kind:e}})).data?.data??null}async fetchHandles(){if(Q)return Q;try{let e=(await this.client.dispatch(`system:workflows:registry:handles`)).data?.data?.code;return e?(Q=Function(`return (${e})`)(),Q):(Q={},Q)}catch{return Q={},Q}}async hasWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:has`,{arguments:{id:e}})).data?.data?.has??!1}async listWorkflows(){return(await this.client.dispatch(`system:workflows:runtime:list`)).data?.data?.workflow_ids??[]}async invokeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:invoke`,{payload:e})).data?.data}async resumeWorkflow(e){return(await this.client.dispatch(`system:workflows:runtime:resume`,{payload:e})).data?.data}streamRun(e,t,n){let r=new AbortController,i=AbortSignal.any([r.signal,...n?.signal?[n.signal]:[]]);return this.client.openStream(`/system/workflows/run/stream/${encodeURIComponent(e)}`,{onMessage:e=>{try{let n=JSON.parse(e),r=n.data??n;t.onEvent(r)}catch{}},onError:t.onError,onOpen:t.onOpen,onClose:t.onDone},{...n,signal:i}).catch(e=>{t.onError?.(e instanceof Error?e:Error(String(e)))}),r}},$=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:core:docs:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},_e=class{store;client;auth;users;keys;policies;rules;auditLogs;appLogs;collections;blobs;core;notifications;schedules;settings;updates;workflows;operations;tokenProvider;apiKeyMode;autoHeartbeat;authChannel;applyingRemoteAuth=!1;unsubscribeIdentity;closing;constructor(e){this.store=new o({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},n=e.apiPrefix??`/api`,r=e.apiKey?{"X-Api-Key":e.apiKey}:void 0,i=()=>{t.clear()};this.tokenProvider=t,this.apiKeyMode=!!e.apiKey,this.autoHeartbeat=e.autoHeartbeat!==!1,e.transport instanceof x?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(i),this.client=e.transport):this.client=e.transport??new g(e.baseUrl,n,i,r),this.auth=new ne(this.client,t),this.users=new A(this.client),this.keys=new j(this.client),this.policies=new P(this.client),this.rules=new F(this.client),this.auditLogs=new I(this.client,e.baseUrl,n),this.appLogs=new L(this.client,e.baseUrl,n),this.collections=new X(this.client),this.blobs=new Y(this.client,n,e.uploadPersistence),this.core=new $(this.client),this.notifications=new Z(this.client),this.schedules=new fe(this.client),this.settings=new pe(this.client),this.updates=new me(this.client),this.workflows=new ge(this.client),this.operations=new N(this.client),this.unsubscribeIdentity=this.store.watch(`identity`,e=>{e.identity?this.autoHeartbeat&&this.startHeartbeat():this.stopHeartbeat(),this.applyingRemoteAuth||this.authChannel?.postMessage(`changed`)}),this.setupAuthChannel(e.baseUrl)}setupAuthChannel(e){if(typeof BroadcastChannel>`u`)return;let t=`hestia:auth:${e.replace(/\/+$/,``)}`;try{this.authChannel=new BroadcastChannel(t),this.authChannel.unref?.()}catch{return}this.authChannel.addEventListener(`message`,()=>{this.applyRemoteAuthChange()})}async applyRemoteAuthChange(){if(!this.applyingRemoteAuth){this.applyingRemoteAuth=!0;try{await this.auth.session()}catch{}finally{this.applyingRemoteAuth=!1}}}onAuthStateChange(e){return this.store.watch(`identity`,t=>{e(t.identity??null)})}async authenticated(){if(this.apiKeyMode)return!0;if(this.tokenProvider.identity()===null)return await this.auth.session()!==null;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){if(this.heartbeatTimer!==void 0&&e===void 0)return;this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}view(e){return this.collections.view(e)}ready(){return this.client.ready()}close(){return this.closing||=(async()=>{this.unsubscribeIdentity?.(),this.stopHeartbeat(),this.authChannel?.close(),await this.client.close?.(),await this.store.dispose()})(),this.closing}};function ve(e){let t=`${e.collectionName}_array_pager_state_`,n=new o({}),r=[...e.initialData??[]],i=`collection`,l,u=e.page??1,d=e.size??20,f=[],p,m,{match:h}=s(e.customFunctions??{}),{sort:g}=c(),_=n.select(e=>e[t]),v={data:[],loading:!0,error:void 0,page:{number:1,size:d,count:0,total:0,pages:1}},y=()=>({filters:p,sort:f,pagination:{type:`offset`,offset:(u-1)*d,limit:d}}),b=async(a=!0)=>{if(e.fetch){if(m=void 0,a){let e=_.get()??v;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=y(),n=await e.fetch(t);i=n.scope,l=n.total,r=n.replace?[...n.data]:[...r,...n.data]}catch(e){m=e}}let o=x(e.fetch?a:!1);await n.set({[t]:o})},x=e=>{let t=[...r];if(i===`collection`){p&&(t=t.filter(e=>h(e,p))),f.length>0&&(t=g(t,f));let n=t.length,r=Math.ceil(n/d)||1;u>r&&(u=r),u<1&&(u=1);let i=(u-1)*d,a=t.slice(i,i+d);return{data:a,loading:e,error:m,page:{number:u,size:d,count:a.length,total:n,pages:r}}}let n=l??t.length,a=Math.ceil(n/d)||1;return{data:t,loading:e,error:m,page:{number:u,size:d,count:t.length,total:n,pages:a}}};return b(!0),{id:()=>t,page:()=>_.get()??v,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);u=e,await b(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);d=e,u=t,await b(!0)},sort:async e=>{f=Array.isArray(e)?e:[e],u=1,await b(!0)},filter:async e=>{p=e,u=1,await b(!0)},refresh:async e=>{let r=_.get()??v;await n.set({[t]:{...r,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),b(!1)]);let a=_.get()??v;await n.set({[t]:{...a,loading:!1}})},subscribe:e=>_.subscribe(t=>{e(t)}),invalidate:async()=>{await n.set({[t]:a}),r=[]}}}export{W as AimdController,J as BlobNamespace,L as HestiaAppLogs,I as HestiaAuditLogs,ne as HestiaAuth,Y as HestiaBlobClient,_e as HestiaClient,O as HestiaCollection,X as HestiaCollections,$ as HestiaCore,k as HestiaDataView,j as HestiaKeyStore,_ as HestiaNetworkClient,Z as HestiaNotificationStore,N as HestiaOperations,P as HestiaPolicies,h as HestiaResponse,F as HestiaRules,fe as HestiaScheduleStore,pe as HestiaSettingStore,me as HestiaUpdates,A as HestiaUsers,ge as HestiaWorkflowStore,g as HttpTransport,G as ResumableUpload,ue as UploadJobStore,K as UploadQueue,x as WailsTransport,ve as createArrayPager,v as createAsyncStream,w as createPagedController,he as getCachedHandles,U as getMissingRanges,p as internalError,d as notFound,l as parseErrorBody,f as permissionDenied,T as proxiedDocument,E as proxiedPage,u as toSystemError};
|
package/package.json
CHANGED