@asaidimu/hestia 1.0.1 → 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/LICENSE.md +22 -0
- package/index.cjs +8 -0
- package/index.d.cts +920 -0
- package/index.d.mts +920 -0
- package/index.mjs +8 -0
- package/package.json +25 -22
- package/auth/store.ts +0 -75
- package/auth/types.ts +0 -38
- package/blobs/store.ts +0 -209
- package/blobs/types.ts +0 -28
- package/collections/store.ts +0 -88
- package/collections/types.ts +0 -11
- package/container.ts +0 -93
- package/core/client.ts +0 -408
- package/core/collection.ts +0 -145
- package/core/errors.ts +0 -55
- package/core/pager.ts +0 -162
- package/core/types.ts +0 -279
- package/index.ts +0 -39
- package/system/api-keys/store.ts +0 -107
- package/system/api-keys/types.ts +0 -31
- package/system/capabilities/store.ts +0 -67
- package/system/capabilities/types.ts +0 -1
- package/system/identity/store.ts +0 -113
- package/system/identity/types.ts +0 -31
- package/system/policies/store.ts +0 -177
- package/system/policies/types.ts +0 -43
- package/test-setup.ts +0 -53
- package/utils/index.ts +0 -1
- package/utils/pager.ts +0 -230
- package/vitest.config.ts +0 -8
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,39 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asaidimu/hestia",
|
|
3
|
-
"version": "1.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
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"types": "index.
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
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
|
-
"
|
|
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
|
-
"
|
|
25
|
-
|
|
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
|
-
"@faker-js/faker": "^10.5.0",
|
|
31
|
-
"@types/bun": "latest",
|
|
32
|
-
"vitest": "^4.1.10"
|
|
33
|
-
},
|
|
34
|
-
"peerDependencies": {
|
|
35
|
-
"typescript": "^5"
|
|
36
|
-
},
|
|
37
40
|
"dependencies": {
|
|
38
41
|
"@asaidimu/network-client": "^2.0.0",
|
|
39
42
|
"@asaidimu/query": "^1.0.0",
|
package/auth/store.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { HestiaNetworkClient, type 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, permissions: 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 type { 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,209 +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 { Document, Page, PagedData, StoreEvent } from "../core/types";
|
|
6
|
-
import type { DocumentStore } from "../core/types";
|
|
7
|
-
import type {
|
|
8
|
-
BlobDocument,
|
|
9
|
-
BlobMeta,
|
|
10
|
-
CreateNamespaceRequest,
|
|
11
|
-
ListBlobsRequest,
|
|
12
|
-
NamespaceInfo,
|
|
13
|
-
} from "./types";
|
|
14
|
-
|
|
15
|
-
function asDoc(b: BlobMeta): BlobDocument {
|
|
16
|
-
return {
|
|
17
|
-
_id_: b.key,
|
|
18
|
-
_metadata_: {
|
|
19
|
-
checksum: "",
|
|
20
|
-
created: b.created_at,
|
|
21
|
-
updated: b.updated_at ?? b.created_at,
|
|
22
|
-
version: 1,
|
|
23
|
-
},
|
|
24
|
-
...b,
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function pageMeta<T extends Record<string,any>>(items: T[]): Page<T>["page"] {
|
|
29
|
-
return {
|
|
30
|
-
number: 1,
|
|
31
|
-
size: items.length,
|
|
32
|
-
count: items.length,
|
|
33
|
-
total: items.length,
|
|
34
|
-
pages: 1,
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export class BlobNamespace implements DocumentStore<BlobMeta, QueryDSL<BlobMeta>, string, QueryDSL<BlobMeta>, Record<string, unknown>, string, Record<string, any>, Record<string, unknown>, { key: string; contentType?: string }, Record<string, unknown>> {
|
|
39
|
-
private pagerOptions = {};
|
|
40
|
-
private pager: PagedData<BlobMeta>;
|
|
41
|
-
private prefixFilter = "";
|
|
42
|
-
|
|
43
|
-
constructor(
|
|
44
|
-
private client: HestiaNetworkClient,
|
|
45
|
-
private ns: string,
|
|
46
|
-
) {
|
|
47
|
-
this.pager = createPagedController<BlobMeta>(
|
|
48
|
-
`blobs_${ns}`,
|
|
49
|
-
new ReactiveDataStore<any>({}),
|
|
50
|
-
this.pagerOptions,
|
|
51
|
-
(query) => this.find(query),
|
|
52
|
-
);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
name() {
|
|
56
|
-
return this.ns;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
setPrefix(prefix: string) {
|
|
60
|
-
this.prefixFilter = prefix;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
private basePath() {
|
|
64
|
-
return `/system/blobs/blob/${encodeURIComponent(this.ns)}`;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async find(query?: QueryDSL<BlobMeta>): Promise<Page<BlobMeta>> {
|
|
68
|
-
const prefix = this.prefixFilter || (query as any)?.prefix || "";
|
|
69
|
-
const limit =
|
|
70
|
-
(query as any)?.limit ?? query?.pagination?.limit ?? 0;
|
|
71
|
-
|
|
72
|
-
const req: ListBlobsRequest = {};
|
|
73
|
-
if (prefix) req.prefix = prefix;
|
|
74
|
-
if (limit) req.limit = limit;
|
|
75
|
-
|
|
76
|
-
const res = await this.client.post<{
|
|
77
|
-
data: { blobs: BlobMeta[] };
|
|
78
|
-
}>(`${this.basePath()}/query`, req);
|
|
79
|
-
|
|
80
|
-
const items = res.data?.data?.blobs ?? [];
|
|
81
|
-
return { data: items.map(asDoc), loading: false, page: pageMeta(items), error: undefined };
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
async read(key: string): Promise<Document<BlobMeta> | undefined> {
|
|
85
|
-
try {
|
|
86
|
-
const res = await this.client.get<{ data: BlobMeta }>(
|
|
87
|
-
`${this.basePath()}/${encodeURIComponent(key)}`,
|
|
88
|
-
);
|
|
89
|
-
if (!res.data?.data) return undefined;
|
|
90
|
-
return asDoc(res.data.data);
|
|
91
|
-
} catch (err: any) {
|
|
92
|
-
if (
|
|
93
|
-
err?.code === "SYNC-001-NF" ||
|
|
94
|
-
(err?.code === "INTERNAL_ERROR" &&
|
|
95
|
-
typeof err?.message === "string" &&
|
|
96
|
-
err.message.includes("not found"))
|
|
97
|
-
)
|
|
98
|
-
return undefined;
|
|
99
|
-
throw err;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
async create(_props: { data: Partial<BlobMeta> }): Promise<Document<BlobMeta> | undefined> {
|
|
104
|
-
throw new Error("Use upload() to create blobs");
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
async update(props: { data: Partial<BlobMeta>; options?: Record<string, any> }): Promise<Document<BlobMeta> | undefined> {
|
|
108
|
-
const key = props.options?.key as string;
|
|
109
|
-
if (!key) throw new Error("options.key is required for blob update");
|
|
110
|
-
const res = await this.client.patch<{ data: BlobMeta }>(
|
|
111
|
-
`${this.basePath()}/${encodeURIComponent(key)}`,
|
|
112
|
-
{ custom: props.data },
|
|
113
|
-
);
|
|
114
|
-
return asDoc(res.data!.data);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
async delete(key: string): Promise<void> {
|
|
118
|
-
await this.client.delete(
|
|
119
|
-
`${this.basePath()}/${encodeURIComponent(key)}`,
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async list(options?: QueryDSL<BlobMeta>): Promise<Page<BlobMeta>> {
|
|
124
|
-
return this.find(options ?? {});
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
async upload(props: { file: File; options?: { key?: string; contentType?: string } }): Promise<Document<BlobMeta> | undefined> {
|
|
128
|
-
const key = (props.options as any)?.key as string;
|
|
129
|
-
if (!key) throw new Error("options.key is required for blob upload");
|
|
130
|
-
const headers: Record<string, string> = {};
|
|
131
|
-
const ct = props.options?.contentType || props.file.type;
|
|
132
|
-
if (ct) headers["Content-Type"] = ct;
|
|
133
|
-
|
|
134
|
-
const res = await this.client.post<{ data: BlobMeta }>(
|
|
135
|
-
`${this.basePath()}/${encodeURIComponent(key)}`,
|
|
136
|
-
props.file,
|
|
137
|
-
{ headers, bodyType: "blob" },
|
|
138
|
-
);
|
|
139
|
-
return asDoc(res.data!.data);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
async subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void> {
|
|
143
|
-
throw new Error("Subscription not supported for blobs");
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
async notify(_event: StoreEvent): Promise<void> {
|
|
147
|
-
throw new Error("Notify not supported for blobs");
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
151
|
-
stream: () => AsyncIterable<Document<BlobMeta>>;
|
|
152
|
-
cancel: () => void;
|
|
153
|
-
status: () => "active" | "cancelled" | "completed";
|
|
154
|
-
} {
|
|
155
|
-
throw new Error("Stream not supported for blobs");
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
page(_options?: Record<string, unknown>): PagedData<BlobMeta> {
|
|
159
|
-
return this.pager;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
async download(key: string): Promise<{ data: Blob; contentType: string }> {
|
|
163
|
-
const res = await this.client.get<Blob>(
|
|
164
|
-
`${this.basePath()}/${encodeURIComponent(key)}`,
|
|
165
|
-
{ responseType: "blob" },
|
|
166
|
-
);
|
|
167
|
-
const blob = res.data!;
|
|
168
|
-
return { data: blob, contentType: blob.type };
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
export class HestiaBlobClient {
|
|
173
|
-
private apiPrefix: string;
|
|
174
|
-
|
|
175
|
-
constructor(private client: HestiaNetworkClient, apiPrefix: string = "/api") {
|
|
176
|
-
this.apiPrefix = apiPrefix;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
private nsBase = "/system/blobs";
|
|
180
|
-
|
|
181
|
-
async namespaces(): Promise<NamespaceInfo[]> {
|
|
182
|
-
const res = await this.client.post<{
|
|
183
|
-
data: { namespaces: NamespaceInfo[] };
|
|
184
|
-
}>(`${this.nsBase}/namespace/query`);
|
|
185
|
-
return res.data?.data?.namespaces ?? [];
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
async createNamespace(data: CreateNamespaceRequest): Promise<NamespaceInfo> {
|
|
189
|
-
const res = await this.client.post<{ data: NamespaceInfo }>(
|
|
190
|
-
`${this.nsBase}/namespace`,
|
|
191
|
-
data,
|
|
192
|
-
);
|
|
193
|
-
return res.data!.data;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
async deleteNamespace(ns: string): Promise<void> {
|
|
197
|
-
await this.client.delete(
|
|
198
|
-
`${this.nsBase}/namespace/${encodeURIComponent(ns)}`,
|
|
199
|
-
);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
blob(namespace: string, key:string) {
|
|
203
|
-
return `${this.client.base()}${this.apiPrefix}${this.nsBase}/blob/${encodeURIComponent(namespace)}/${encodeURIComponent(key)}`
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
namespace(ns: string): BlobNamespace {
|
|
207
|
-
return new BlobNamespace(this.client, ns);
|
|
208
|
-
}
|
|
209
|
-
}
|
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
|
-
}
|
package/collections/store.ts
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { HestiaNetworkClient } from "../core/client"
|
|
2
|
-
import { HestiaCollection } from "../core/collection"
|
|
3
|
-
import type { Document, Page, PagedData, StoreEvent } from "../core/types"
|
|
4
|
-
import type { DocumentStore } from "../core/types"
|
|
5
|
-
import type { CollectionMeta } from "./types"
|
|
6
|
-
|
|
7
|
-
export class HestiaCollections implements DocumentStore<CollectionMeta, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
8
|
-
constructor(private client: HestiaNetworkClient) {}
|
|
9
|
-
|
|
10
|
-
async find(_query?: Record<string, unknown>): Promise<Page<CollectionMeta>> {
|
|
11
|
-
const res = await this.client.get<{
|
|
12
|
-
data: { name: string; schema: any; created: string; updated: string }[]
|
|
13
|
-
}>("/system/collections/collection")
|
|
14
|
-
const items = res.data?.data ?? []
|
|
15
|
-
const docs: Document<CollectionMeta>[] = items.map((i) => ({
|
|
16
|
-
_id_: i.name,
|
|
17
|
-
_metadata_: { checksum: "", created: i.created, updated: i.updated, version: 1 },
|
|
18
|
-
name: i.name,
|
|
19
|
-
schema: i.schema,
|
|
20
|
-
created: i.created,
|
|
21
|
-
updated: i.updated,
|
|
22
|
-
}))
|
|
23
|
-
return {
|
|
24
|
-
data: docs,
|
|
25
|
-
loading: false,
|
|
26
|
-
page: { number: 1, size: docs.length, count: docs.length, total: docs.length, pages: 1 },
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
async read(name: string): Promise<Document<CollectionMeta> | undefined> {
|
|
31
|
-
try {
|
|
32
|
-
const res = await this.client.get<{ data: { name: string; schema: any; created: string; updated: string } }>(
|
|
33
|
-
`/system/collections/collection/${encodeURIComponent(name)}`,
|
|
34
|
-
)
|
|
35
|
-
if (!res.data) return undefined
|
|
36
|
-
const d = res.data.data
|
|
37
|
-
return { _id_: d.name, _metadata_: { checksum: "", created: d.created, updated: d.updated, version: 1 }, name: d.name, schema: d.schema, created: d.created, updated: d.updated }
|
|
38
|
-
} catch (err: any) {
|
|
39
|
-
if (err?.code === "SYNC-001-NF") return undefined
|
|
40
|
-
throw err
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async create(props: { data: Partial<CollectionMeta> }): Promise<Document<CollectionMeta> | undefined> {
|
|
45
|
-
const res = await this.client.post<{ data: Document<{ schema: any }> }>("/system/collections/collection", props.data)
|
|
46
|
-
return res.data!.data as any as Document<CollectionMeta>
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
async update(_props: { data: Partial<CollectionMeta>; options?: string }): Promise<Document<CollectionMeta> | undefined> {
|
|
50
|
-
throw new Error("Collection update not implemented")
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async delete(name: string): Promise<void> {
|
|
54
|
-
await this.client.delete(`/system/collections/collection/${encodeURIComponent(name)}`)
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async list(_options?: Record<string, unknown>): Promise<Page<CollectionMeta>> {
|
|
58
|
-
return this.find()
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
async upload(_props: { file: File }): Promise<Document<CollectionMeta> | undefined> {
|
|
62
|
-
throw new Error("Upload not supported for collections")
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
async subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void> {
|
|
66
|
-
throw new Error("Subscription not supported for collections")
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
async notify(_event: StoreEvent): Promise<void> {
|
|
70
|
-
throw new Error("Notify not supported for collections")
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
74
|
-
stream: () => AsyncIterable<Document<CollectionMeta>>;
|
|
75
|
-
cancel: () => void;
|
|
76
|
-
status: () => "active" | "cancelled" | "completed";
|
|
77
|
-
} {
|
|
78
|
-
throw new Error("Stream not supported for collections")
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
page(_options?: Record<string, unknown>): PagedData<CollectionMeta> {
|
|
82
|
-
throw new Error("Pagination not supported for collection metadata; use documents(name)")
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
documents<T extends Record<string, any>>(collectionName: string): HestiaCollection<T> {
|
|
86
|
-
return new HestiaCollection<T>(this.client, collectionName)
|
|
87
|
-
}
|
|
88
|
-
}
|
package/collections/types.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import type { 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,93 +0,0 @@
|
|
|
1
|
-
import type { SimplePersistence } from "@asaidimu/utils-persistence";
|
|
2
|
-
import { ReactiveDataStore } from "@asaidimu/utils-store";
|
|
3
|
-
import { HestiaAuth } from "./auth/store";
|
|
4
|
-
import { HestiaCollections } from "./collections/store";
|
|
5
|
-
import {
|
|
6
|
-
HestiaNetworkClient,
|
|
7
|
-
type IdentityProvider,
|
|
8
|
-
} from "./core/client";
|
|
9
|
-
import { HestiaKeyStore } from "./system/api-keys/store";
|
|
10
|
-
import { HestiaUsers } from "./system/identity/store";
|
|
11
|
-
import type { UserIdentity } from "./system/identity/types";
|
|
12
|
-
import { HestiaLogs } from "./system/logs/store";
|
|
13
|
-
import { HestiaPolicies } from "./system/policies/store";
|
|
14
|
-
import { HestiaBlobClient } from "./blobs/store";
|
|
15
|
-
import { HestiaCapabilities } from "./system/capabilities/store";
|
|
16
|
-
|
|
17
|
-
export interface HestiaConfig {
|
|
18
|
-
baseUrl: string;
|
|
19
|
-
apiPrefix?: 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
|
-
export class HestiaClient {
|
|
30
|
-
readonly store: ReactiveDataStore<AuthState>;
|
|
31
|
-
readonly client: HestiaNetworkClient;
|
|
32
|
-
readonly auth: HestiaAuth;
|
|
33
|
-
readonly users: HestiaUsers;
|
|
34
|
-
readonly keys: HestiaKeyStore;
|
|
35
|
-
readonly policies: HestiaPolicies;
|
|
36
|
-
readonly logs: HestiaLogs;
|
|
37
|
-
readonly collections: HestiaCollections;
|
|
38
|
-
readonly blobs: HestiaBlobClient;
|
|
39
|
-
readonly capabilities: HestiaCapabilities
|
|
40
|
-
private tokenProvider: IdentityProvider;
|
|
41
|
-
|
|
42
|
-
private onAuthStateChanged?: () => void;
|
|
43
|
-
|
|
44
|
-
constructor(config: HestiaConfig) {
|
|
45
|
-
this.store = new ReactiveDataStore<AuthState>(
|
|
46
|
-
{ access: null, refresh: null, identity: null },
|
|
47
|
-
config.persistence,
|
|
48
|
-
);
|
|
49
|
-
|
|
50
|
-
const tokenProvider: IdentityProvider = {
|
|
51
|
-
identity: () => this.store.get().identity,
|
|
52
|
-
token: (key: "access" | "refresh") => this.store.get()[key],
|
|
53
|
-
setTokens: async (access: string, refresh: string) =>
|
|
54
|
-
void (await this.store.set({ access, refresh })),
|
|
55
|
-
setIdentity: async (identity) =>
|
|
56
|
-
void (await this.store.set({ identity })),
|
|
57
|
-
clear: async () =>
|
|
58
|
-
void (await this.store.set({ access: null, refresh: null })),
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
const apiPrefix = config.apiPrefix ?? "/api";
|
|
62
|
-
|
|
63
|
-
this.tokenProvider = tokenProvider;
|
|
64
|
-
this.client = new HestiaNetworkClient(config.baseUrl, apiPrefix, tokenProvider, () =>
|
|
65
|
-
this.onAuthStateChanged?.(),
|
|
66
|
-
);
|
|
67
|
-
|
|
68
|
-
this.auth = new HestiaAuth(this.client, tokenProvider);
|
|
69
|
-
this.users = new HestiaUsers(this.client);
|
|
70
|
-
this.keys = new HestiaKeyStore(this.client,);
|
|
71
|
-
this.policies = new HestiaPolicies(this.client);
|
|
72
|
-
this.logs = new HestiaLogs(
|
|
73
|
-
this.client,
|
|
74
|
-
config.baseUrl,
|
|
75
|
-
apiPrefix,
|
|
76
|
-
);
|
|
77
|
-
this.collections = new HestiaCollections(this.client);
|
|
78
|
-
this.blobs = new HestiaBlobClient(this.client, apiPrefix);
|
|
79
|
-
this.capabilities = new HestiaCapabilities(this.client)
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
onAuthStateChange(callback: () => void) {
|
|
83
|
-
this.onAuthStateChanged = callback;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
authenticated(): boolean {
|
|
87
|
-
return this.tokenProvider.token("access") !== null;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
collection<T extends Record<string, any>>(name: string) {
|
|
91
|
-
return this.collections.documents<T>(name);
|
|
92
|
-
}
|
|
93
|
-
}
|