@asaidimu/hestia 1.0.0 → 1.0.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/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import{createNetworkClient as e}from"@asaidimu/network-client";import{Errors as t,SystemError as n}from"@asaidimu/utils-error";import{DELETE_SYMBOL as r,ReactiveDataStore as i}from"@asaidimu/utils-store";import{Debouncer as a}from"@asaidimu/utils-sync";import{createMatcher as o,createSorter as s}from"@asaidimu/query";async function c(e){try{return(await e.clone().json())?.error??null}catch{return null}}function l(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 u(e){return t.notFound(e)}function d(e){return t.permissionDenied(e)}function f(e){return t.internalError(e)}var p=class{data;status;constructor(e,t){this.data=e,this.status=t}},m=class{baseUrl;apiPrefix;tokens;onAuthStateChanged;raw;refreshing=null;refreshFailed=!1;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.tokens=r,this.onAuthStateChanged=i,this.raw=e({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`,interceptors:{request:[e=>{let t=this.tokens.token(`access`);return t&&(e.headers.Authorization=`Bearer ${t}`),e}]}})}base(){return this.baseUrl}prefix(){return this.apiPrefix}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 storeTokens(e,t){this.refreshFailed=!1,await this.tokens.setTokens(e,t??``)}async refreshToken(){if(this.refreshing)return this.refreshing;this.refreshing=this.doRefresh();try{await this.refreshing}finally{this.refreshing=null,this.onAuthStateChanged&&this.onAuthStateChanged()}}async doRefresh(){let e=this.tokens.token(`refresh`),t=e?{refresh_token:e}:{},r=await this.raw.patch(this.canonicalPath(`/system/auth/session`),t);if(!r.success||!r.data)throw this.tokens.clear(),this.refreshFailed=!0,new n({code:`AUTH-002-UNAUTH`,message:`Token refresh failed`});let{access:i,refresh:a}=r.data.data.token;this.refreshFailed=!1,await this.tokens.setTokens(i,a)}async request(e,t,r,i){let a=this.canonicalPath(t),o={};i?.headers&&(o.headers=i.headers),i?.responseType&&(o.responseType=i.responseType),i?.bodyType&&(o.bodyType=i.bodyType),i?.signal&&(o.signal=i.signal);let s;if(e===`GET`)s=await this.raw.get(a,o);else{let t=i?.bodyType?{type:i.bodyType}:void 0;s=await this.raw[e.toLowerCase()](a,r,o,t)}if(s.success||s.status===204)return new p(s.data,s.status);if((s.status===401||s.status===403)&&!t.includes(`/system/auth/token`)&&!t.includes(`/system/auth/session`)){if(i?.headers?.[`X-API-Key`])throw new n({code:`AUTH-003-APIKEY`,message:`API key is invalid or expired`});if(this.refreshFailed)throw this.tokens.clear(),this.onAuthStateChanged?.(),new n({code:`AUTH-002-UNAUTH`,message:`Session expired`});try{await this.refreshToken()}catch{throw this.tokens.clear(),this.onAuthStateChanged?.(),new n({code:`AUTH-002-UNAUTH`,message:`Session expired`})}let t=this.tokens.token(`access`),c={...o};if(t&&(c.headers={...o.headers??{},Authorization:`Bearer ${t}`}),e===`GET`)s=await this.raw.get(a,c);else{let t=i?.bodyType?{type:i.bodyType}:void 0;s=await this.raw[e.toLowerCase()](a,r,c,t)}if(s.success||s.status===204)return new p(s.data,s.status)}let u=s.raw?await c(s.raw):null;throw l(s,u)}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,r){let i=async a=>{let o=this.tokens.token(`access`),s=!!r?.headers?.[`X-API-Key`],c={Accept:`text/event-stream`,...o&&!s?{Authorization:`Bearer ${o}`}:{},...r?.headers??{}},l=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,u;try{u=await fetch(l,{method:`GET`,headers:c,signal:r?.signal})}catch(e){if(e instanceof Error&&e.name===`AbortError`){t.onClose?.();return}t.onError?.(e instanceof Error?e:Error(String(e)));return}if(u.status===401&&!a&&!s){try{await this.refreshToken()}catch{this.tokens.clear(),this.onAuthStateChanged?.(),t.onError?.(new n({code:`AUTH-002-UNAUTH`,message:`Session expired`}));return}return i(!0)}if(!u.ok||!u.body){t.onError?.(Error(`Stream request failed with status ${u.status}`));return}t.onOpen?.();let d=u.body.getReader(),f=new TextDecoder,p=``;try{for(;;){let{done:e,value:n}=await d.read();if(e)break;p+=f.decode(n,{stream:!0});let r=p.indexOf(`
2
+
3
+ `);for(;r!==-1;){let e=p.slice(0,r);p=p.slice(r+2);let n=e.split(`
4
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());n.length>0&&t.onMessage(n.join(`
5
+ `)),r=p.indexOf(`
6
+
7
+ `)}}}catch(e){e instanceof Error&&e.name===`AbortError`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}};return i(!1)}};const h={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function g(e,t,n,i){let o=n.page??1,s=n.size??20,c=n.sort,l=n.filter,u=new a({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:r,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}}),await new Promise(n=>{n(u.do(async()=>{requestIdleCallback(()=>{requestIdleCallback(async()=>{try{let n=await i(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...h,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),g=m.subscribe(()=>{});return{page:()=>m.get()??h,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}),g()},id:()=>d}}var _=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=g(t,new i({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}get queryPath(){return`/system/collections/document/${encodeURIComponent(this.collectionName)}/query`}get documentsPath(){return`/system/collections/document/${encodeURIComponent(this.collectionName)}`}documentPath(e){return`${this.documentsPath}/${encodeURIComponent(e)}`}async find(e){let t=await this.client.post(this.queryPath,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 read(e){try{return(await this.client.get(this.documentPath(e))).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){return(await this.client.post(this.documentsPath,e.data)).data.data}async update(e){let t=e.options;return(await this.client.patch(this.documentPath(t),e.data)).data.data}async delete(e){await this.client.delete(this.documentPath(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}},v=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.get(`/system/core/health`)).data.data}async login(e,t){let n=(await this.client.post(`/system/auth/session`,{email:e,password:t})).data.data;return this.provider.setIdentity(n.user),this.client.storeTokens(n.token.access,n.token.refresh),n}async register(e,t,n){return(await this.client.post(`/system/auth/user`,{email:e,password:t,name:n})).data.data}async refresh(e){let t=e?{refresh_token:e}:{};return(await this.client.patch(`/system/auth/session`,t)).data.data.token}async logout(){let e=this.provider.token(`refresh`),t=e?{refresh_token:e}:{};await this.client.delete(`/system/auth/session`,t),await this.provider.clear()}async requestPasswordReset(e){await this.client.post(`/system/auth/password`,{email:e})}async confirmPasswordReset(e,t){await this.client.patch(`/system/auth/password`,{password:t,token:e},{headers:{Authorization:`Bearer ${e}`}})}async bootstrap(e,t,n){await this.client.patch(`/system/auth/bootstrap`,{password:t,email:n},{headers:{"X-API-Key":e}})}},y=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=g(`users`,new i({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.post(`/system/users/user/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}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.get(`/system/users/user/${encodeURIComponent(e)}`)).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){let t=e.options;return(await this.client.patch(`/system/users/user/${encodeURIComponent(t)}`,e.data)).data.data}async delete(e){await this.client.delete(`/system/users/user/${encodeURIComponent(e)}`)}async create(e){throw Error(`User creation requires email/password/name, use register endpoint`)}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.patch(`/system/users/password/${encodeURIComponent(e)}`,{current:t,new:n})}},b=class{client;pager;constructor(e){this.client=e,this.pager=g(`_api_key_`,new i({}),{},e=>this.find(e))}basePath=`/system/apikeys/key`;async find(e){let t=await this.client.get(this.basePath),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.get(`${this.basePath}/${encodeURIComponent(e)}`)).data?.data}catch(e){if(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.post(this.basePath,e.data)).data.data}async update(e){let t=e.options;return(await this.client.patch(`${this.basePath}/${encodeURIComponent(t)}`,e.data)).data.data}async delete(e){await this.client.delete(`${this.basePath}/${encodeURIComponent(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.post(`${this.basePath}/${encodeURIComponent(e)}`)).data.data}},x=class{client;pager;operationsPath=`/system/policies/operation`;rulesPath=`/system/policies/rule`;constructor(e){this.client=e,this.pager=g(`policies`,new i({}),{},e=>this.find(e))}async collectionQuery(e,t){let n=await this.client.post(`/system/collections/document/${encodeURIComponent(e)}/query`,t??{}),r=n.data?.data??[];return{data:r,loading:!1,page:n.data?.metadata?.page??{number:1,size:r.length,count:r.length,total:r.length,pages:1},error:null}}async find(e){return this.collectionQuery(`_operation_policy_`,e)}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.get(`${this.operationsPath}/${encodeURIComponent(e)}`)).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){let t=e.data.name;if(!t)throw Error(`Operation name is required for create`);return(await this.client.patch(`${this.operationsPath}/${encodeURIComponent(t)}`,e.data)).data.data}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);return(await this.client.patch(`${this.operationsPath}/${encodeURIComponent(t)}`,e.data)).data.data}async delete(e){await this.client.delete(`${this.operationsPath}/${encodeURIComponent(e)}`)}async upsertOperation(e,t){return(await this.client.patch(`${this.operationsPath}/${encodeURIComponent(e)}`,t)).data.data}async getRule(e){try{return(await this.client.get(`${this.rulesPath}/${encodeURIComponent(e)}`)).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async upsertRule(e,t){return(await this.client.patch(`${this.rulesPath}/${encodeURIComponent(e)}`,t)).data.data}async deleteRule(e){await this.client.delete(`${this.rulesPath}/${encodeURIComponent(e)}`)}async listRules(e){return this.collectionQuery(`_iam_rule_`,e)}async validateRule(e){return(await this.client.post(`${this.rulesPath}/validate`,{expression:e})).data?.data?.valid??!1}async reload(){return(await this.client.get(`${this.rulesPath}/reload`)).data.data}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}},S=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=g(`_audit_log_`,new i({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/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=this.getStreamUrl(),r=null,i=`active`,a=null,o=async function*(){let e=[];r=new EventSource(n,{withCredentials:!0}),r.onmessage=t=>{for(let n of t.data.split(`
8
+ `)){let t=n.trim();if(t)try{let n=JSON.parse(t);n?.data&&e.push(n.data)}catch{}}e.length>0&&a&&(a(),a=null)},r.onerror=()=>{i===`active`&&(i=`completed`),a&&=(a(),null)};try{for(;i===`active`;)e.length>0?yield e.shift():await new Promise(t=>{a=t,e.length>0&&(t(),a=null)})}finally{r?.close(),a&&=(a(),null),i===`active`&&(i=`completed`)}};return{stream:()=>o(),cancel:()=>{i===`active`&&(i=`cancelled`,r?.close())},status:()=>i}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}};function C(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function w(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var T=class{client;ns;pagerOptions={};pager;prefixFilter=``;constructor(e,t){this.client=e,this.ns=t,this.pager=g(`blobs_${t}`,new i({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}basePath(){return`/system/blobs/blob/${encodeURIComponent(this.ns)}`}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.post(`${this.basePath()}/query`,r)).data?.data?.blobs??[];return{data:i.map(C),loading:!1,page:w(i),error:void 0}}async read(e){try{let t=await this.client.get(`${this.basePath()}/${encodeURIComponent(e)}`);return t.data?.data?C(t.data.data):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob update`);return C((await this.client.patch(`${this.basePath()}/${encodeURIComponent(t)}`,{custom:e.data})).data.data)}async delete(e){await this.client.delete(`${this.basePath()}/${encodeURIComponent(e)}`)}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={},r=e.options?.contentType||e.file.type;return r&&(n[`Content-Type`]=r),C((await this.client.post(`${this.basePath()}/${encodeURIComponent(t)}`,e.file,{headers:n,bodyType:`blob`})).data.data)}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.get(`${this.basePath()}/${encodeURIComponent(e)}`,{responseType:`blob`})).data;return{data:t,contentType:t.type}}},E=class{client;apiPrefix;constructor(e,t=`/api`){this.client=e,this.apiPrefix=t}nsBase=`/system/blobs`;async namespaces(){return(await this.client.post(`${this.nsBase}/namespace/query`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.post(`${this.nsBase}/namespace`,e)).data.data}async deleteNamespace(e){await this.client.delete(`${this.nsBase}/namespace/${encodeURIComponent(e)}`)}blob(e,t){return`${this.client.base()}${this.apiPrefix}${this.nsBase}/blob/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}namespace(e){return new T(this.client,e)}},D=class{client;constructor(e){this.client=e}async find(e){let t=((await this.client.get(`/system/collections/collection`)).data?.data??[]).map(e=>({_id_:e.name,_metadata_:{checksum:``,created:e.created,updated:e.updated,version:1},name:e.name,schema:e.schema,created:e.created,updated:e.updated}));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.get(`/system/collections/collection/${encodeURIComponent(e)}`);if(!t.data)return;let n=t.data.data;return{_id_:n.name,_metadata_:{checksum:``,created:n.created,updated:n.updated,version:1},name:n.name,schema:n.schema,created:n.created,updated:n.updated}}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){return(await this.client.post(`/system/collections/collection`,e.data)).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.delete(`/system/collections/collection/${encodeURIComponent(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 _(this.client,e)}},O=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.get(`/system/core/docs`)).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`)}},k=class{store;client;auth;users;keys;policies;logs;collections;blobs;capabilities;tokenProvider;onAuthStateChanged;constructor(e){this.store=new i({access:null,refresh:null,identity:null},e.persistence);let t={identity:()=>this.store.get().identity,token:e=>this.store.get()[e],setTokens:async(e,t)=>void await this.store.set({access:e,refresh:t}),setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({access:null,refresh:null})},n=e.apiPrefix??`/api`;this.tokenProvider=t,this.client=new m(e.baseUrl,n,t,()=>this.onAuthStateChanged?.()),this.auth=new v(this.client,t),this.users=new y(this.client),this.keys=new b(this.client),this.policies=new x(this.client),this.logs=new S(this.client,e.baseUrl,n),this.collections=new D(this.client),this.blobs=new E(this.client,n),this.capabilities=new O(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}authenticated(){return this.tokenProvider.token(`access`)!==null}collection(e){return this.collections.documents(e)}};function A(e){let t=`${e.collectionName}_array_pager_state_`,n=new i({}),a=[...e.initialData??[]],c=`collection`,l,u=e.page??1,d=e.size??20,f=[],p,m,{match:h}=o(e.customFunctions??{}),{sort:g}=s(),_=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(r=!0)=>{if(e.fetch){if(m=void 0,r){let e=_.get()??v;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=y(),n=await e.fetch(t);c=n.scope,l=n.total,a=n.replace?[...n.data]:[...a,...n.data]}catch(e){m=e}}let i=x(e.fetch?r:!1);await n.set({[t]:i})},x=e=>{let t=[...a];if(c===`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,r=Math.ceil(n/d)||1;return{data:t,loading:e,error:m,page:{number:u,size:d,count:t.length,total:n,pages:r}}};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]:r}),a=[]}}}export{T as BlobNamespace,v as HestiaAuth,E as HestiaBlobClient,k as HestiaClient,_ as HestiaCollection,D as HestiaCollections,b as HestiaKeyStore,S as HestiaLogs,m as HestiaNetworkClient,x as HestiaPolicies,p as HestiaResponse,y as HestiaUsers,A as createArrayPager,g as createPagedController,f as internalError,u as notFound,c as parseErrorBody,d as permissionDenied,l as toSystemError};
package/package.json CHANGED
@@ -1,43 +1,50 @@
1
1
  {
2
2
  "name": "@asaidimu/hestia",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "TypeScript client SDK for the Hestia platform — auth, collections, API keys, policies, audit logs, blobs, and capabilities",
5
5
  "type": "module",
6
- "module": "index.ts",
7
- "main": "index.ts",
8
- "types": "index.ts",
9
- "scripts": {
10
- "test": "vitest run",
11
- "test:watch": "vitest",
12
- "test:browser": "vitest --browser --run"
6
+ "main": "./index.cjs",
7
+ "module": "./index.mjs",
8
+ "types": "./index.d.mts",
9
+ "exports": {
10
+ ".": {
11
+ "types": {
12
+ "import": "./index.d.mts",
13
+ "require": "./index.d.cts"
14
+ },
15
+ "import": "./index.mjs",
16
+ "require": "./index.cjs"
17
+ }
13
18
  },
14
19
  "files": [
15
- "*.ts",
16
- "*/**/*.ts",
17
- "!*.test.ts",
18
- "!*/**/*.test.ts"
20
+ "./*"
19
21
  ],
22
+ "keywords": [
23
+ "typescript"
24
+ ],
25
+ "author": "Saidimu <47994458+asaidimu@users.noreply.github.com>",
26
+ "license": "MIT",
20
27
  "repository": {
21
28
  "type": "git",
22
29
  "url": "git+https://github.com/asaidimu/hestia.git"
23
30
  },
24
- "license": "MIT",
25
- "author": "Asaidimu <dev@asaidimu.com>",
31
+ "bugs": {
32
+ "url": "git+https://github.com/asaidimu/hestia/issues"
33
+ },
34
+ "homepage": "https://github.com/asaidimu/hestia#readme",
26
35
  "publishConfig": {
36
+ "registry": "https://registry.npmjs.org/",
37
+ "tag": "latest",
27
38
  "access": "public"
28
39
  },
29
- "devDependencies": {
30
- "@types/bun": "latest",
31
- "vitest": "^4.1.10"
32
- },
33
- "peerDependencies": {
34
- "typescript": "^5"
35
- },
36
40
  "dependencies": {
37
41
  "@asaidimu/network-client": "^2.0.0",
42
+ "@asaidimu/query": "^1.0.0",
38
43
  "@asaidimu/utils-artifacts": "^8.2.25",
39
44
  "@asaidimu/utils-error": "^1.1.10",
45
+ "@asaidimu/utils-schema": "^1.0.10",
40
46
  "@asaidimu/utils-store": "^10.2.18",
47
+ "@asaidimu/utils-sync": "^2.3.0",
41
48
  "uuid": "^14.0.1"
42
49
  }
43
50
  }
package/auth/store.ts DELETED
@@ -1,75 +0,0 @@
1
- import { HestiaNetworkClient, IdentityProvider } from "../core/client";
2
- import type { LoginResult, ServerHealth, TokenPair } from "./types";
3
-
4
- export class HestiaAuth {
5
- constructor(
6
- private client: HestiaNetworkClient,
7
- private provider: IdentityProvider,
8
- ) {}
9
-
10
- async health(): Promise<ServerHealth> {
11
- const res = await this.client.get<{ data: ServerHealth }>("/system/core/health");
12
- return res.data!.data;
13
- }
14
-
15
- async login(email: string, password: string): Promise<LoginResult> {
16
- const res = await this.client.post<{ data: LoginResult }>(
17
- "/system/auth/session",
18
- { email, password },
19
- );
20
- const result = res.data!.data;
21
- this.provider.setIdentity(result.user);
22
- this.client.storeTokens(result.token.access, result.token.refresh);
23
- return result;
24
- }
25
-
26
- async register(
27
- email: string,
28
- password: string,
29
- name: string,
30
- ): Promise<{ _id_: string; email: string; name: string }> {
31
- const res = await this.client.post<{
32
- data: { _id_: string; email: string; name: string, scopes:string };
33
- }>("/system/auth/user", { email, password, name });
34
- return res.data!.data;
35
- }
36
-
37
- async refresh(refreshToken?: string): Promise<TokenPair> {
38
- const body = refreshToken ? { refresh_token: refreshToken } : {};
39
- const res = await this.client.patch<{ data: { token: TokenPair } }>(
40
- "/system/auth/session",
41
- body,
42
- );
43
- return res.data!.data.token;
44
- }
45
-
46
- async logout(): Promise<void> {
47
- const refresh = this.provider.token("refresh");
48
- const body = refresh ? { refresh_token: refresh } : {};
49
- await this.client.delete("/system/auth/session", body);
50
- await this.provider.clear();
51
- }
52
-
53
- async requestPasswordReset(email: string): Promise<void> {
54
- await this.client.post("/system/auth/password", { email });
55
- }
56
-
57
- async confirmPasswordReset(
58
- resetToken: string,
59
- password: string,
60
- ): Promise<void> {
61
- await this.client.patch(
62
- "/system/auth/password",
63
- { password, token:resetToken },
64
- { headers: { Authorization: `Bearer ${resetToken}` } },
65
- );
66
- }
67
-
68
- async bootstrap(key: string, password: string, email: string): Promise<void> {
69
- await this.client.patch(
70
- "/system/auth/bootstrap",
71
- { password, email },
72
- { headers: { "X-API-Key": key } },
73
- );
74
- }
75
- }
package/auth/types.ts DELETED
@@ -1,38 +0,0 @@
1
- import { UserIdentity } from "../system/identity/types"
2
-
3
- export interface TokenPair {
4
- access: string
5
- refresh: string
6
- type: string
7
- validity: number
8
- }
9
-
10
- export interface LoginResult {
11
- token: TokenPair
12
- user: UserIdentity
13
- }
14
-
15
- export interface ServerHealth {
16
- bootstrapped: boolean
17
- ok: boolean
18
- }
19
-
20
- export interface LoginRequest {
21
- email: string
22
- password: string
23
- }
24
-
25
- export interface RegisterRequest {
26
- email: string
27
- password: string
28
- name: string
29
- }
30
-
31
- export interface RefreshRequest {
32
- refresh_token: string
33
- }
34
-
35
- export interface BootstrapPasswordRequest {
36
- password: string
37
- email: string
38
- }
package/blobs/store.ts DELETED
@@ -1,208 +0,0 @@
1
- import type { QueryDSL } from "@asaidimu/query";
2
- import { ReactiveDataStore } from "@asaidimu/utils-store";
3
- import { HestiaNetworkClient } from "../core/client";
4
- import { createPagedController } from "../core/pager";
5
- import type { Page, PagedData } from "../core/types";
6
- import type {
7
- BlobDocument,
8
- BlobMeta,
9
- CreateNamespaceRequest,
10
- ListBlobsRequest,
11
- NamespaceInfo,
12
- } from "./types";
13
-
14
- function asDoc(b: BlobMeta): BlobDocument {
15
- return {
16
- _id_: b.key,
17
- _metadata_: {
18
- checksum: "",
19
- created: b.created_at,
20
- updated: b.updated_at ?? b.created_at,
21
- version: 1,
22
- },
23
- ...b,
24
- };
25
- }
26
-
27
- function pageMeta<T extends Record<string,any>>(items: T[]): Page<T>["page"] {
28
- return {
29
- number: 1,
30
- size: items.length,
31
- count: items.length,
32
- total: items.length,
33
- pages: 1,
34
- };
35
- }
36
-
37
- /**
38
- * Namespace-scoped blob facade shaped like HestiaCollection.
39
- * Wraps blob CRUD behind a DocumentStore-compatible interface
40
- * so you can use DataTable + PagedData.
41
- */
42
- export class BlobNamespace {
43
- private pagerOptions = {};
44
- private pager: PagedData<BlobMeta>;
45
- private prefixFilter = "";
46
-
47
- constructor(
48
- private client: HestiaNetworkClient,
49
- private ns: string,
50
- ) {
51
- this.pager = createPagedController<BlobMeta>(
52
- `blobs_${ns}`,
53
- new ReactiveDataStore<any>({}),
54
- this.pagerOptions,
55
- (query) => this.find(query),
56
- );
57
- }
58
-
59
- name() {
60
- return this.ns;
61
- }
62
-
63
- setPrefix(prefix: string) {
64
- this.prefixFilter = prefix;
65
- }
66
-
67
- private basePath() {
68
- return `/system/blobs/blob/${encodeURIComponent(this.ns)}`;
69
- }
70
-
71
- async find(query?: QueryDSL<BlobMeta>): Promise<Page<BlobMeta>> {
72
- const prefix = this.prefixFilter || (query as any)?.prefix || "";
73
- const limit =
74
- (query as any)?.limit ?? query?.pagination?.limit ?? 0;
75
-
76
- const req: ListBlobsRequest = {};
77
- if (prefix) req.prefix = prefix;
78
- if (limit) req.limit = limit;
79
-
80
- const res = await this.client.post<{
81
- data: { blobs: BlobMeta[] };
82
- }>(`${this.basePath()}/query`, req);
83
-
84
- const items = res.data?.data?.blobs ?? [];
85
- return { data: items.map(asDoc), loading: false, page: pageMeta(items), error: undefined };
86
- }
87
-
88
- async head(key: string): Promise<BlobDocument | undefined> {
89
- try {
90
- const res = await this.client.get<{ data: BlobMeta }>(
91
- `${this.basePath()}/${encodeURIComponent(key)}`,
92
- );
93
- if (!res.data?.data) return undefined;
94
- return asDoc(res.data.data);
95
- } catch (err: any) {
96
- if (
97
- err?.code === "SYNC-001-NF" ||
98
- (err?.code === "INTERNAL_ERROR" &&
99
- typeof err?.message === "string" &&
100
- err.message.includes("not found"))
101
- )
102
- return undefined;
103
- throw err;
104
- }
105
- }
106
-
107
- async upload(
108
- key: string,
109
- data: Blob,
110
- contentType?: string,
111
- ): Promise<BlobDocument> {
112
- const headers: Record<string, string> = {};
113
- const ct = contentType || data.type;
114
- if (ct) headers["Content-Type"] = ct;
115
-
116
- const res = await this.client.post<{ data: BlobMeta }>(
117
- `${this.basePath()}/${encodeURIComponent(key)}`,
118
- data,
119
- { headers, bodyType: "blob" },
120
- );
121
- return asDoc(res.data!.data);
122
- }
123
-
124
- async download(
125
- key: string,
126
- ): Promise<{ data: Blob; contentType: string }> {
127
- const res = await this.client.get<Blob>(
128
- `${this.basePath()}/${encodeURIComponent(key)}`,
129
- { responseType: "blob" },
130
- );
131
- const blob = res.data!;
132
- return { data: blob, contentType: blob.type };
133
- }
134
-
135
- async updateMetadata(key: string, custom: Record<string, any>): Promise<BlobMeta> {
136
- const res = await this.client.patch<{ data: BlobMeta }>(
137
- `${this.basePath()}/${encodeURIComponent(key)}`,
138
- { custom },
139
- );
140
- return res.data!.data;
141
- }
142
-
143
- async delete(key: string): Promise<void> {
144
- await this.client.delete(
145
- `${this.basePath()}/${encodeURIComponent(key)}`,
146
- );
147
- }
148
-
149
- async list(): Promise<BlobMeta[]> {
150
- const res = await this.client.post<{
151
- data: { blobs: BlobMeta[] };
152
- }>(`${this.basePath()}/query`, {});
153
- return res.data?.data?.blobs ?? [];
154
- }
155
-
156
- page(): PagedData<BlobMeta> {
157
- return this.pager;
158
- }
159
- }
160
-
161
- /**
162
- * Top-level blob client. Entry point for all blob operations.
163
- *
164
- * Usage:
165
- * client.blobs.listNamespaces()
166
- * const ns = client.blobs.namespace("my-bucket")
167
- * ns.find({ prefix: "images/" })
168
- * ns.upload("logo.png", file)
169
- * const { data } = await ns.download("logo.png")
170
- */
171
- export class HestiaBlobClient {
172
- constructor(private client: HestiaNetworkClient) {}
173
-
174
- private nsBase = "/system/blobs";
175
-
176
- // ── Namespace operations ──────────────────────────────────────────────
177
-
178
- async namespaces(): Promise<NamespaceInfo[]> {
179
- const res = await this.client.post<{
180
- data: { namespaces: NamespaceInfo[] };
181
- }>(`${this.nsBase}/namespace/query`);
182
- return res.data?.data?.namespaces ?? [];
183
- }
184
-
185
- async createNamespace(data: CreateNamespaceRequest): Promise<NamespaceInfo> {
186
- const res = await this.client.post<{ data: NamespaceInfo }>(
187
- `${this.nsBase}/namespace`,
188
- data,
189
- );
190
- return res.data!.data;
191
- }
192
-
193
- async deleteNamespace(ns: string): Promise<void> {
194
- await this.client.delete(
195
- `${this.nsBase}/namespace/${encodeURIComponent(ns)}`,
196
- );
197
- }
198
-
199
-
200
- blob(namespace: string, key:string) {
201
- return `${this.client.base()}${this.nsBase}/blob/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`
202
- }
203
- // ── Namespace-scoped facade ───────────────────────────────────────────
204
-
205
- namespace(ns: string): BlobNamespace {
206
- return new BlobNamespace(this.client, ns);
207
- }
208
- }
package/blobs/types.ts DELETED
@@ -1,28 +0,0 @@
1
- import type { Document } from "../core/types"
2
-
3
- export interface NamespaceInfo {
4
- id: string
5
- display_name: string
6
- }
7
-
8
- export interface BlobMeta {
9
- key: string
10
- namespace_id: string
11
- content_type: string
12
- size: number
13
- created_at: string
14
- updated_at?: string
15
- custom?: Record<string, any>
16
- }
17
-
18
- export type BlobDocument = Document<BlobMeta>
19
-
20
- export interface ListBlobsRequest {
21
- prefix?: string
22
- limit?: number
23
- }
24
-
25
- export interface CreateNamespaceRequest {
26
- display_name?: string
27
- ns?: string
28
- }
@@ -1,59 +0,0 @@
1
- import { HestiaNetworkClient } from "../core/client"
2
- import { HestiaCollection } from "../core/collection"
3
- import type { Document } from "../core/types"
4
- import type { CollectionMeta } from "./types"
5
-
6
- export class HestiaCollections {
7
- constructor(private client: HestiaNetworkClient) {}
8
-
9
- async list(): Promise<{ collections: CollectionMeta[]; total: number }> {
10
- const res = await this.client.get<{
11
- data: { name: string; schema: any; created: string; updated: string }[]
12
- }>("/system/collections/collection")
13
- const items = res.data?.data ?? []
14
- return {
15
- collections: items.map((i) => ({
16
- name: i.name,
17
- schema: i.schema,
18
- created: i.created,
19
- updated: i.updated,
20
- })),
21
- total: items.length,
22
- }
23
- }
24
-
25
- async read(name: string): Promise<CollectionMeta | undefined> {
26
- try {
27
- const res = await this.client.get<{ data: { name: string; schema: any; created: string; updated: string } }>(
28
- `/system/collections/collection/${encodeURIComponent(name)}`,
29
- )
30
- if (!res.data) return undefined
31
- return res.data.data
32
- } catch (err: any) {
33
- if (err?.code === "SYNC-001-NF") return undefined
34
- throw err
35
- }
36
- }
37
-
38
- async create(schema: any): Promise<Document<{ schema: any }>> {
39
- const res = await this.client.post<{ data: Document<{ schema: any }> }>("/system/collections/collection", schema)
40
- return res.data!.data
41
- }
42
-
43
- async update(name: string, schema: any): Promise<Document<{ schema: any }>> {
44
- throw new Error("Method not implemented")
45
- // const res = await this.client.patch<{ data: Document<{ schema: any }> }>(
46
- // `/api/admin/collections/${encodeURIComponent(name)}`,
47
- // schema,
48
- // )
49
- // return res.data!.data
50
- }
51
-
52
- async delete(name: string): Promise<void> {
53
- await this.client.delete(`/system/collections/collection/${encodeURIComponent(name)}`)
54
- }
55
-
56
- documents<T extends Record<string, any>>(collectionName: string): HestiaCollection<T> {
57
- return new HestiaCollection<T>(this.client,collectionName)
58
- }
59
- }
@@ -1,11 +0,0 @@
1
- import { SchemaDefinition } from "@asaidimu/utils-schema"
2
- import type { Document } from "../core/types"
3
-
4
- export interface CollectionMeta {
5
- name: string
6
- schema: SchemaDefinition
7
- created: string
8
- updated: string
9
- }
10
-
11
- export type CollectionDocument = Document<{ schema: any }>
package/container.ts DELETED
@@ -1,95 +0,0 @@
1
- import { ArtifactContainer } from "@asaidimu/utils-artifacts";
2
- import type { SimplePersistence } from "@asaidimu/utils-persistence";
3
- import { ReactiveDataStore } from "@asaidimu/utils-store";
4
- import { HestiaAuth } from "./auth/store";
5
- import { HestiaCollections } from "./collections/store";
6
- import {
7
- HestiaNetworkClient,
8
- type IdentityProvider,
9
- } from "./core/client";
10
- import { HestiaKeyStore } from "./system/api-keys/store";
11
- import { HestiaUsers } from "./system/identity/store";
12
- import { UserIdentity } from "./system/identity/types";
13
- import { HestiaLogs } from "./system/logs/store";
14
- import { HestiaPolicies } from "./system/policies/store";
15
- import { HestiaBlobClient } from "./blobs/store";
16
- import { HestiaCapabilities } from "./system/capabilities/store";
17
-
18
- export interface HestiaConfig {
19
- baseUrl: string;
20
- persistence?: SimplePersistence<AuthState>;
21
- }
22
-
23
- interface AuthState {
24
- access: string | null;
25
- refresh: string | null;
26
- identity: UserIdentity | null;
27
- }
28
-
29
- type Registry = Record<string, any>;
30
-
31
- export class HestiaClient {
32
- readonly store: ReactiveDataStore<AuthState>;
33
- readonly container: ArtifactContainer<Registry, any>;
34
- readonly client: HestiaNetworkClient;
35
- readonly auth: HestiaAuth;
36
- readonly users: HestiaUsers;
37
- readonly keys: HestiaKeyStore;
38
- readonly policies: HestiaPolicies;
39
- readonly logs: HestiaLogs;
40
- readonly collections: HestiaCollections;
41
- readonly blobs: HestiaBlobClient;
42
- readonly capabilities: HestiaCapabilities
43
- private tokenProvider: IdentityProvider;
44
-
45
- private onAuthStateChanged?: () => void;
46
-
47
- constructor(config: HestiaConfig) {
48
- this.store = new ReactiveDataStore<AuthState>(
49
- { access: null, refresh: null, identity: null },
50
- config.persistence,
51
- );
52
-
53
- this.container = new ArtifactContainer<Registry, any>(this.store);
54
-
55
- const tokenProvider: IdentityProvider = {
56
- identity: () => this.store.get().identity,
57
- token: (key: "access" | "refresh") => this.store.get()[key],
58
- setTokens: async (access: string, refresh: string) =>
59
- void (await this.store.set({ access, refresh })),
60
- setIdentity: async (identity) =>
61
- void (await this.store.set({ identity })),
62
- clear: async () =>
63
- void (await this.store.set({ access: null, refresh: null })),
64
- };
65
-
66
- this.tokenProvider = tokenProvider;
67
- this.client = new HestiaNetworkClient(config.baseUrl, tokenProvider, () =>
68
- this.onAuthStateChanged?.(),
69
- );
70
-
71
- this.auth = new HestiaAuth(this.client, tokenProvider);
72
- this.users = new HestiaUsers(this.client);
73
- this.keys = new HestiaKeyStore(this.client,);
74
- this.policies = new HestiaPolicies(this.client);
75
- this.logs = new HestiaLogs(
76
- this.client,
77
- config.baseUrl,
78
- );
79
- this.collections = new HestiaCollections(this.client);
80
- this.blobs = new HestiaBlobClient(this.client);
81
- this.capabilities = new HestiaCapabilities(this.client)
82
- }
83
-
84
- onAuthStateChange(callback: () => void) {
85
- this.onAuthStateChanged = callback;
86
- }
87
-
88
- authenticated(): boolean {
89
- return this.tokenProvider.token("access") !== null;
90
- }
91
-
92
- collection<T extends Record<string, any>>(name: string) {
93
- return this.collections.documents<T>(name);
94
- }
95
- }