@memoryintelligence/sdk 2.0.0
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 +691 -0
- package/dist/index.d.mts +953 -0
- package/dist/index.d.ts +953 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +27 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +63 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
'use strict';var I=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var U=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var u=(s,e)=>()=>(s&&(e=s(s=0)),e);var ie=(s,e)=>{for(var t in e)I(s,t,{get:e[t],enumerable:true});},oe=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ne(e))!se.call(s,r)&&r!==t&&I(s,r,{get:()=>e[r],enumerable:!(n=re(e,r))||n.enumerable});return s};var ae=s=>oe(I({},"__esModule",{value:true}),s);exports.SDKError=void 0;exports.ConfigurationError=void 0;exports.AuthenticationError=void 0;exports.ValidationError=void 0;exports.RateLimitError=void 0;exports.APIError=void 0;var w=u(()=>{exports.SDKError=class s extends Error{constructor(t,n){super(t);this.code=n;this.name="SDKError",Object.setPrototypeOf(this,s.prototype);}},exports.ConfigurationError=class s extends exports.SDKError{constructor(e){super(e,"CONFIGURATION_ERROR"),this.name="ConfigurationError",Object.setPrototypeOf(this,s.prototype);}},exports.AuthenticationError=class s extends exports.SDKError{constructor(e){super(e,"AUTHENTICATION_ERROR"),this.name="AuthenticationError",Object.setPrototypeOf(this,s.prototype);}},exports.ValidationError=class s extends exports.SDKError{constructor(t,n){super(t,"VALIDATION_ERROR");this.field=n;this.name="ValidationError",Object.setPrototypeOf(this,s.prototype);}},exports.RateLimitError=class s extends exports.SDKError{constructor(t,n,r,i){super(t,"RATE_LIMIT_ERROR");this.retryAfter=n;this.limit=r;this.remaining=i;this.name="RateLimitError",Object.setPrototypeOf(this,s.prototype);}},exports.APIError=class s extends exports.SDKError{constructor(t,n,r,i){super(t,"API_ERROR");this.statusCode=n;this.requestId=r;this.details=i;this.name="APIError",Object.setPrototypeOf(this,s.prototype);}};});function G(s){if(!s)throw new exports.ConfigurationError("API key is required");if(typeof s!="string")throw new exports.ConfigurationError("API key must be a string");if(!s.startsWith("mi_sk_"))throw new exports.AuthenticationError("Invalid API key format. Must start with mi_sk_");let e=s.split("_");if(e.length<4)throw new exports.AuthenticationError("Invalid API key format. Expected: mi_sk_{env}_{secret}");let t=e[2],n=["beta","test","live"];if(!n.includes(t))throw new exports.AuthenticationError(`Invalid API key environment: ${t}. Must be one of: ${n.join(", ")}`)}function z(s){return s?s.replace(/\/$/,""):typeof process<"u"&&process.env?.MI_API_URL?process.env.MI_API_URL.replace(/\/$/,""):ce}var ce,V=u(()=>{w();ce="https://api.memoryintelligence.io";});exports.Scope=void 0;exports.RetentionPolicy=void 0;exports.PIIHandling=void 0;exports.ProvenanceMode=void 0;exports.ExplainLevel=void 0;var H=u(()=>{exports.Scope=(a=>(a.USER="user",a.CLIENT="client",a.PROJECT="project",a.TEAM="team",a.ORGANIZATION="org",a.ALL="all",a))(exports.Scope||{}),exports.RetentionPolicy=(n=>(n.MEANING_ONLY="meaning_only",n.FULL="full",n.SUMMARY_ONLY="summary_only",n))(exports.RetentionPolicy||{}),exports.PIIHandling=(r=>(r.DETECT_ONLY="detect_only",r.EXTRACT_AND_REDACT="extract_and_redact",r.HASH="hash",r.REJECT="reject",r))(exports.PIIHandling||{}),exports.ProvenanceMode=(n=>(n.STANDARD="standard",n.AUTHORSHIP="authorship",n.AUDIT="audit",n))(exports.ProvenanceMode||{}),exports.ExplainLevel=(r=>(r.NONE="none",r.HUMAN="human",r.AUDIT="audit",r.FULL="full",r))(exports.ExplainLevel||{});});var E,J=u(()=>{w();E=class{constructor(e){this.apiKey=e.apiKey,this.baseUrl=e.baseUrl,this.timeout=e.timeout||3e4,this.maxRetries=e.maxRetries||3;}async request(e,t={}){let n=`${this.baseUrl}${e}`,r=t.method||"GET",i;for(let a=0;a<this.maxRetries;a++)try{let o=await this.makeRequest(n,r,t),c=this.extractRateLimit(o),l=o.headers.get("x-request-id")||void 0;return o.ok||await this.handleErrorResponse(o,l),{data:await o.json(),rateLimit:c,requestId:l}}catch(o){if(i=o,o instanceof exports.AuthenticationError||o instanceof exports.ValidationError||o instanceof exports.RateLimitError)throw o;if(a<this.maxRetries-1){let c=Math.min(1e3*Math.pow(2,a),1e4);await this.sleep(c);}}throw new exports.APIError(`Request failed after ${this.maxRetries} attempts: ${i?.message}`,void 0,void 0,i)}async makeRequest(e,t,n){let r={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-MI-SDK-Version":"2.0.0","X-MI-SDK-Language":"typescript",...n.headers},i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout),o=n.signal||i.signal;try{return await fetch(e,{method:t,headers:r,body:n.body?JSON.stringify(n.body):void 0,signal:o})}finally{clearTimeout(a);}}extractRateLimit(e){let t=e.headers.get("x-ratelimit-limit"),n=e.headers.get("x-ratelimit-remaining"),r=e.headers.get("x-ratelimit-reset");if(!(!t&&!n&&!r))return {limit:t?parseInt(t,10):void 0,remaining:n?parseInt(n,10):void 0,reset:r?parseInt(r,10):void 0}}async handleErrorResponse(e,t){let n=e.status,r;try{r=await e.json();}catch{r={detail:e.statusText};}let i=r.detail||r.message||"Unknown error";switch(n){case 401:throw new exports.AuthenticationError(i);case 400:throw new exports.ValidationError(i);case 429:{let a=e.headers.get("retry-after"),o=this.extractRateLimit(e);throw new exports.RateLimitError(i,a?parseInt(a,10):void 0,o?.limit,o?.remaining)}default:throw new exports.APIError(i,n,t,r)}}sleep(e){return new Promise(t=>setTimeout(t,e))}};});exports.WebSocketManager=void 0;var j=u(()=>{w();exports.WebSocketManager=class{constructor(e){this.ws=null;this.reconnectAttempts=0;this.reconnectTimeout=null;this.pingIntervalId=null;this.subscriptions=new Map;this.connectionPromise=null;this.isConnecting=false;this.isClosed=false;this.onConnectHandlers=[];this.onDisconnectHandlers=[];this.onErrorHandlers=[];this.config={url:e.url,apiKey:e.apiKey,orgUlid:e.orgUlid,reconnectDelay:e.reconnectDelay||1e3,maxReconnectAttempts:e.maxReconnectAttempts||5,pingInterval:e.pingInterval||3e4};}async connect(){return this.ws?.readyState===WebSocket.OPEN?Promise.resolve():this.isConnecting&&this.connectionPromise?this.connectionPromise:(this.isConnecting=true,this.connectionPromise=new Promise((e,t)=>{try{let n=new URL(this.config.url);n.searchParams.append("api_key",this.config.apiKey),this.config.orgUlid&&n.searchParams.append("org_ulid",this.config.orgUlid),this.ws=new WebSocket(n.toString()),this.ws.onopen=()=>{this.isConnecting=!1,this.reconnectAttempts=0,this.startPingInterval(),this.onConnectHandlers.forEach(r=>r()),e();},this.ws.onmessage=r=>{try{let i=JSON.parse(r.data);this.handleMessage(i);}catch(i){console.error("Failed to parse WebSocket message:",i);}},this.ws.onerror=()=>{let r=new exports.SDKError("WebSocket connection error");this.onErrorHandlers.forEach(i=>i(r)),this.isConnecting&&(this.isConnecting=!1,t(r));},this.ws.onclose=()=>{this.stopPingInterval(),this.onDisconnectHandlers.forEach(r=>r()),this.isClosed||this.attemptReconnect();};}catch(n){this.isConnecting=false,t(n instanceof Error?n:new exports.SDKError("Failed to connect"));}}),this.connectionPromise)}disconnect(){this.isClosed=true,this.stopPingInterval(),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(),this.ws=null),this.subscriptions.clear();}async subscribe(e,t){await this.connect(),this.subscriptions.set(e.subscription_id,t),this.send(e);}unsubscribe(e){this.subscriptions.delete(e),this.ws?.readyState===WebSocket.OPEN&&this.send({type:"unsubscribe",subscription_id:e,stream:""});}onConnect(e){this.onConnectHandlers.push(e);}onDisconnect(e){this.onDisconnectHandlers.push(e);}onError(e){this.onErrorHandlers.push(e);}isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new exports.SDKError("WebSocket not connected");this.ws.send(JSON.stringify(e));}handleMessage(e){if(e.type!=="pong"&&e.subscription_id){let t=this.subscriptions.get(e.subscription_id);t&&t(e);}}startPingInterval(){this.stopPingInterval(),this.pingIntervalId=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.send({type:"ping"});},this.config.pingInterval);}stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null);}attemptReconnect(){if(this.reconnectAttempts>=this.config.maxReconnectAttempts){let t=new exports.SDKError(`Failed to reconnect after ${this.config.maxReconnectAttempts} attempts`);this.onErrorHandlers.forEach(n=>n(t));return}let e=this.config.reconnectDelay*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.connect().catch(t=>{console.error("Reconnect failed:",t);});},e);}};});exports.BaseSubscription=void 0;var P=u(()=>{exports.BaseSubscription=class{constructor(e){this.eventHandlers=new Map;this.isActive=false;this.ws=e,this.subscriptionId=this.generateSubscriptionId();}stop(){this.isActive&&(this.ws.unsubscribe(this.subscriptionId),this.isActive=false,this.emit("disconnected",null));}on(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),this}off(e,t){let n=this.eventHandlers.get(e);if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1);}return this}emit(e,t){let n=this.eventHandlers.get(e);n&&n.forEach(r=>{try{r(t);}catch(i){console.error(`Error in ${e} handler:`,i);}});}generateSubscriptionId(){return `sub_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}isSubscribed(){return this.isActive}};});exports.DriftSubscription=void 0;var Y=u(()=>{P();exports.DriftSubscription=class extends exports.BaseSubscription{constructor(e,t={}){super(e),this.options=t;}async start(){let e={};this.options.entityUlids&&(e.entity_ulids=this.options.entityUlids),this.options.orgUlid&&(e.org_ulid=this.options.orgUlid),await this.ws.subscribe({type:"subscribe",subscription_id:this.subscriptionId,stream:"drift_updates",filters:e},t=>this.handleMessage(t)),this.isActive=true;}handleMessage(e){switch(e.type){case "subscribed":this.emit("connected",void 0);break;case "drift_update":let t={entityUlid:e.entity_ulid,canonicalName:e.canonical_name,driftEpoch:e.drift_epoch,driftMagnitude:e.drift_magnitude,meaningStable:e.meaning_stable,updatedAt:e.updated_at,explainHuman:{driftSummary:e.explain_human.drift_summary,whatChanged:{summary:e.explain_human.what_changed.summary,changes:e.explain_human.what_changed.changes},impactOnResults:e.explain_human.impact_on_results,confidenceAssessment:e.explain_human.confidence_assessment},signals:e.signals||[]};this.emit("update",t);break;case "error":this.emit("error",new Error(e.message||"Subscription error"));break}}};});exports.ComputeSubscription=void 0;var X=u(()=>{P();exports.ComputeSubscription=class extends exports.BaseSubscription{constructor(e,t,n={}){super(e),this.functionName=t,this.parameters=n;}async start(){await this.ws.subscribe({type:"subscribe",subscription_id:this.subscriptionId,stream:"compute_result",function_name:this.functionName,parameters:this.parameters},e=>this.handleMessage(e)),this.isActive=true;}handleMessage(e){switch(e.type){case "subscribed":this.emit("connected",void 0);break;case "compute_progress":let t={status:e.status,progressPercent:e.progress_percent,message:e.message};this.emit("progress",t);break;case "compute_result":let n={status:e.status,result:e.result,error:e.error,executionTimeMs:e.execution_time_ms,explainHuman:e.explain_human};this.emit("result",n),this.stop();break;case "error":this.emit("error",new Error(e.message||"Compute error"));break}}};});var L=u(()=>{P();Y();X();});var Z={};ie(Z,{ComputeNamespace:()=>exports.ComputeNamespace,DriftNamespace:()=>exports.DriftNamespace,MemoryClient:()=>exports.MemoryClient,UMONamespace:()=>exports.UMONamespace});exports.UMONamespace=void 0;exports.DriftNamespace=void 0;exports.ComputeNamespace=void 0;exports.MemoryClient=void 0;var W=u(()=>{V();H();J();j();L();exports.UMONamespace=class{constructor(e,t){this.client=e;this.http=t;}resolveUserUlid(e){return e||this.client.userUlid}async process(e,t={}){let n=this.resolveUserUlid(t.userUlid),r={content:e,user_ulid:n,org_ulid:this.client.orgUlid,retention_policy:t.retentionPolicy||"meaning_only",pii_handling:t.piiHandling||"extract_and_redact",provenance_mode:t.provenanceMode||"standard",scope:t.scope||"user",scope_id:t.scopeId,source:t.source||"api",metadata:t.metadata||{}};return (await this.http.request("/v1/process",{method:"POST",body:r})).data}async search(e,t={}){let n=this.resolveUserUlid(t.userUlid),r=new URLSearchParams;return r.append("q",e),n&&r.append("user_ulid",n),t.limit&&r.append("limit",t.limit.toString()),t.scope&&r.append("scope",t.scope),t.scopeId&&r.append("scope_id",t.scopeId),t.explain&&r.append("explain",t.explain),(await this.http.request(`/v1/search?${r.toString()}`)).data}async match(e,t,n={}){let r={umo_id_1:e,umo_id_2:t,explain:n.explain||"none"};return (await this.http.request("/v1/match",{method:"POST",body:r})).data}async explain(e,t="full"){return (await this.http.request(`/v1/explain/${e}?level=${t}`)).data}async delete(e={}){let t=this.resolveUserUlid(e.userUlid),n={};return e.umoId&&(n.umo_id=e.umoId),t&&(n.user_ulid=t),e.scope&&(n.scope=e.scope),(await this.http.request("/v1/delete",{method:"DELETE",body:n})).data}async batch(e){let t={items:e.map(r=>({content:r.content,user_ulid:this.resolveUserUlid(r.userUlid),metadata:r.metadata||{}}))};return (await this.http.request("/v1/batch",{method:"POST",body:t})).data}},exports.DriftNamespace=class{constructor(e){this.ws=e;}watch(e={}){return new exports.DriftSubscription(this.ws,e)}},exports.ComputeNamespace=class{constructor(e){this.ws=e;}disconnect(){this.ws.disconnect();}watch(e,t={}){return new exports.ComputeSubscription(this.ws,e,t)}},exports.MemoryClient=class s{constructor(e){G(e.apiKey);let t=z(e.baseUrl),n=e.wsUrl||t.replace(/^http/,"ws")+"/v1/ws";this.userUlid=e.userUlid,this.orgUlid=e.orgUlid,this.http=new E({apiKey:e.apiKey,baseUrl:t,timeout:e.timeout,maxRetries:e.maxRetries}),this.ws=new exports.WebSocketManager({url:n,apiKey:e.apiKey,orgUlid:e.orgUlid}),this.umo=new exports.UMONamespace(this,this.http),this.drift=new exports.DriftNamespace(this.ws),this.compute=new exports.ComputeNamespace(this.ws);}forUser(e){return new s({apiKey:this.http.apiKey,baseUrl:this.http.baseUrl,userUlid:e,orgUlid:this.orgUlid,timeout:this.http.timeout,maxRetries:this.http.maxRetries})}async capture(e,t){return this.umo.process(e,{userUlid:t})}async search(e,t){return this.umo.search(e,{limit:t})}async explain(e){return this.umo.explain(e)}async forget(e){return this.umo.delete({umoId:e})}};});W();j();L();H();var q=class{constructor(e){this.client=e;}async*processBatch(e){let{items:t,config:n={}}=e,{chunkSize:r=10,onProgress:i,onChunk:a,concurrency:o=3}=n,c=t.length,l=0;for(let h=0;h<t.length;h+=r){let B=t.slice(h,h+r),F=await this.processChunk(B,o);l+=B.length,i&&i(l,c),a&&a(F,Math.floor(h/r));for(let te of F)yield te;h+r<t.length&&await this.sleep(100);}}async processChunk(e,t){let n=[];for(let r=0;r<e.length;r+=t){let a=e.slice(r,r+t).map(c=>this.client.umo.process(c.content,{source:c.type||"text/plain",metadata:c.metadata})),o=await Promise.all(a);n.push(...o);}return n}async*searchBatch(e){let{queries:t,searchOptions:n={},config:r={}}=e,{onProgress:i}=r,a=t.length;for(let o=0;o<t.length;o++){let c=t[o],l=await this.client.umo.search(c,{limit:n.limit||10});i&&i(o+1,a),yield {query:c,results:l.results},o<t.length-1&&await this.sleep(50);}}sleep(e){return new Promise(t=>setTimeout(t,e))}};async function*le(s){let{source:e,chunkSize:t,processor:n,onProgress:r}=s,i=[],a=0;if(Array.isArray(e))for(let o=0;o<e.length;o++)i.push(e[o]),(i.length>=t||o===e.length-1)&&(await n(i),yield i,a+=i.length,r&&r(a),i=[]);else {for await(let o of e)i.push(o),i.length>=t&&(await n(i),yield i,a+=i.length,r&&r(a),i=[]);i.length>0&&(await n(i),yield i,a+=i.length,r&&r(a));}}var K=class{constructor(e){this.client=e;}async*paginate(e,t={}){let{pageSize:n=20,maxResults:r=100}=t,i=0,a=0;for(;a<r;){let o=Math.min(n,r-a),l=(await this.client.umo.search(e,{limit:o})).results;if(l.length===0||(yield l,a+=l.length,i+=l.length,l.length<o))break}}},$=class{constructor(e,t){this.processed=0;this.total=e,this.startTime=Date.now(),this.onUpdate=t;}update(e=1){this.processed+=e,this.onUpdate&&this.onUpdate(this.getProgress());}getProgress(){let e=Date.now()-this.startTime,t=this.processed/(e/1e3),r=(this.total-this.processed)/t;return {processed:this.processed,total:this.total,percentage:this.processed/this.total*100,elapsed:e,rate:t,eta:isFinite(r)?r:void 0}}};function k(){let s=[],e=[],t=[];return typeof global.fetch>"u"&&(s.push("fetch"),t.push("whatwg-fetch")),typeof global.WebSocket>"u"&&(s.push("WebSocket"),e.push("WebSocket not available - drift/compute subscriptions will not work")),typeof global.crypto>"u"&&(s.push("crypto"),t.push("react-native-get-random-values"),t.push("crypto-js")),typeof global.TextEncoder>"u"&&(s.push("TextEncoder"),t.push("text-encoding")),typeof global.TextDecoder>"u"&&(s.push("TextDecoder"),t.push("text-encoding")),typeof global.AbortController>"u"&&(s.push("AbortController"),t.push("abortcontroller-polyfill")),typeof global.URL>"u"&&(s.push("URL"),e.push("URL constructor not available")),{compatible:s.length===0,missing:s,warnings:e,polyfillsAvailable:[...new Set(t)]}}function pe(){try{if(typeof global.fetch>"u")try{U("whatwg-fetch"),console.log("\u2713 fetch polyfill loaded");}catch{console.warn("\u26A0\uFE0F whatwg-fetch not installed. Install with: npm install whatwg-fetch");}if(typeof global.crypto>"u")try{let s=U("react-native-get-random-values");typeof global.crypto>"u"&&(global.crypto={getRandomValues:s.getRandomValues}),console.log("\u2713 crypto polyfill loaded");}catch{console.warn("\u26A0\uFE0F react-native-get-random-values not installed. Install with: npm install react-native-get-random-values");}if(typeof global.TextEncoder>"u"||typeof global.TextDecoder>"u")try{let s=U("text-encoding");typeof global.TextEncoder>"u"&&(global.TextEncoder=s.TextEncoder),typeof global.TextDecoder>"u"&&(global.TextDecoder=s.TextDecoder),console.log("\u2713 TextEncoder/TextDecoder polyfill loaded");}catch{console.warn("\u26A0\uFE0F text-encoding not installed. Install with: npm install text-encoding");}if(typeof global.AbortController>"u")try{let s=U("abortcontroller-polyfill/dist/cjs-ponyfill").AbortController;global.AbortController=s,console.log("\u2713 AbortController polyfill loaded");}catch{console.warn("\u26A0\uFE0F abortcontroller-polyfill not installed. Install with: npm install abortcontroller-polyfill");}}catch(s){console.error("Error setting up React Native polyfills:",s);}}function ue(s,e={}){let{MemoryClient:t}=(W(),ae(Z));e.fetch&&(global.fetch=e.fetch),e.WebSocket&&(global.WebSocket=e.WebSocket),e.crypto&&(global.crypto=e.crypto),e.TextEncoder&&(global.TextEncoder=e.TextEncoder),e.TextDecoder&&(global.TextDecoder=e.TextDecoder);let n=k();return n.compatible||console.warn(`Memory Intelligence SDK is not fully compatible with this React Native environment.
|
|
2
|
+
Missing APIs:`,n.missing.join(", ")+`
|
|
3
|
+
Install polyfills:`,n.polyfillsAvailable.join(", ")),n.warnings.length>0&&n.warnings.forEach(r=>console.warn("\u26A0\uFE0F ",r)),new t({apiKey:s,baseUrl:e.baseUrl})}var Q={isReactNative(){return typeof navigator<"u"&&navigator.product==="ReactNative"},getRecommendedPolyfills(){return k().polyfillsAvailable},getInstallCommand(){let s=this.getRecommendedPolyfills();return s.length===0?null:`npm install ${s.join(" ")}`}};function ee(s){if(!(s instanceof Error))return false;let e=s.message.toLowerCase();return e.includes("fetch is not defined")||e.includes("websocket is not defined")||e.includes("crypto is not defined")||e.includes("textencoder is not defined")||e.includes("abortcontroller is not defined")}function de(s){return ee(s)?`
|
|
4
|
+
React Native Polyfill Required
|
|
5
|
+
==============================
|
|
6
|
+
|
|
7
|
+
The Memory Intelligence SDK requires some Web APIs that are not available
|
|
8
|
+
in React Native by default.
|
|
9
|
+
|
|
10
|
+
Missing APIs: ${k().missing.join(", ")}
|
|
11
|
+
|
|
12
|
+
To fix this, install the required polyfills:
|
|
13
|
+
|
|
14
|
+
${Q.getInstallCommand()}
|
|
15
|
+
|
|
16
|
+
Then in your app entry point (App.tsx):
|
|
17
|
+
|
|
18
|
+
import 'react-native-get-random-values'; // Must be first
|
|
19
|
+
import 'whatwg-fetch';
|
|
20
|
+
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
|
|
21
|
+
import { MemoryClient } from '@memoryintelligence/sdk';
|
|
22
|
+
|
|
23
|
+
const client = new MemoryClient({ apiKey: 'your-key' });
|
|
24
|
+
|
|
25
|
+
For more info: https://docs.memoryintelligence.io/sdk/react-native
|
|
26
|
+
`:null}w();var je="2.0.0";exports.ProgressTracker=$;exports.ReactNativeUtils=Q;exports.SearchResultStream=K;exports.UMOStreamProcessor=q;exports.VERSION=je;exports.checkReactNativeCompatibility=k;exports.createReactNativeClient=ue;exports.getPolyfillErrorHelp=de;exports.isPolyfillError=ee;exports.setupReactNativePolyfills=pe;exports.streamLargeDataset=le;//# sourceMappingURL=index.js.map
|
|
27
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/auth.ts","../src/enums.ts","../src/http.ts","../src/websocket.ts","../src/subscriptions/base.ts","../src/subscriptions/drift.ts","../src/subscriptions/compute.ts","../src/subscriptions/index.ts","../src/client.ts","../src/index.ts","../src/streaming.ts","../src/react-native.ts"],"names":["SDKError","ConfigurationError","AuthenticationError","ValidationError","RateLimitError","APIError","init_errors","__esmMin","_SDKError","message","code","_ConfigurationError","_AuthenticationError","_ValidationError","field","_RateLimitError","retryAfter","limit","remaining","_APIError","statusCode","requestId","details","validateApiKey","apiKey","parts","environment","validEnvironments","resolveBaseUrl","providedUrl","DEFAULT_BASE_URL","init_auth","Scope","RetentionPolicy","PIIHandling","ProvenanceMode","ExplainLevel","init_enums","HTTPClient","init_http","config","endpoint","options","url","method","lastError","attempt","response","rateLimit","error","delay","headers","controller","timeoutId","signal","reset","errorData","ms","resolve","WebSocketManager","init_websocket","reject","handler","event","subscriptionId","BaseSubscription","init_base","ws","handlers","index","data","DriftSubscription","init_drift","filters","update","ComputeSubscription","init_compute","functionName","parameters","progress","result","init_subscriptions","client_exports","__export","ComputeNamespace","DriftNamespace","MemoryClient","UMONamespace","init_client","client","http","explicit","content","userUlid","payload","query","params","umoId1","umoId2","umoId","level","items","item","_MemoryClient","baseUrl","wsUrl","UMOStreamProcessor","chunkSize","onProgress","onChunk","concurrency","total","processed","i","chunk","results","promises","batchResults","queries","searchOptions","streamLargeDataset","source","processor","SearchResultStream","pageSize","maxResults","offset","totalRetrieved","ProgressTracker","onUpdate","count","elapsed","rate","eta","checkReactNativeCompatibility","missing","warnings","polyfillsAvailable","setupReactNativePolyfills","getRandomValues","encoding","AbortController","createReactNativeClient","compatibility","warning","ReactNativeUtils","polyfills","isPolyfillError","getPolyfillErrorHelp","VERSION"],"mappings":"otBAMaA,uBAAAA,CAQAC,kCAQAC,kCAAAA,CAQAC,8BAAAA,CAQAC,8BAaAC,uBAAAA,KAnDbC,CAAAA,CAAAC,EAAA,IAAA,CAMaP,gBAAAA,CAAN,MAAMQ,CAAAA,SAAiB,KAAM,CAClC,WAAA,CAAYC,CAAAA,CAAwBC,EAAe,CACjD,KAAA,CAAMD,CAAO,CAAA,CADqB,IAAA,CAAA,IAAA,CAAAC,EAElC,IAAA,CAAK,IAAA,CAAO,WACZ,MAAA,CAAO,cAAA,CAAe,KAAMF,CAAAA,CAAS,SAAS,EAChD,CACF,CAAA,CAEaP,2BAAN,MAAMU,CAAAA,SAA2BX,gBAAS,CAC/C,WAAA,CAAYS,EAAiB,CAC3B,KAAA,CAAMA,CAAAA,CAAS,qBAAqB,CAAA,CACpC,IAAA,CAAK,KAAO,oBAAA,CACZ,MAAA,CAAO,eAAe,IAAA,CAAME,CAAAA,CAAmB,SAAS,EAC1D,CACF,EAEaT,2BAAAA,CAAN,MAAMU,UAA4BZ,gBAAS,CAChD,YAAYS,CA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;AAAA;AAAA;;AAAA,cAAA,EAFeqF,CAAAA,EAA8B,CASxB,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC;;AAAA;;AAAA,EAAA,EAI5CW,CAAAA,CAAiB,mBAAmB;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA,CAAA,CAfF,IA4BtC,CF1MA3I,CAAAA,EAAAA,CAUO,IAAM+I,EAAAA,CAAU","file":"index.js","sourcesContent":["/**\n * Error classes for Memory Intelligence SDK\n * \n * All errors extend SDKError for consistency with Python SDK patterns.\n */\n\nexport class SDKError extends Error {\n constructor(message: string, public code?: string) {\n super(message);\n this.name = 'SDKError';\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n\nexport class ConfigurationError extends SDKError {\n constructor(message: string) {\n super(message, 'CONFIGURATION_ERROR');\n this.name = 'ConfigurationError';\n Object.setPrototypeOf(this, ConfigurationError.prototype);\n }\n}\n\nexport class AuthenticationError extends SDKError {\n constructor(message: string) {\n super(message, 'AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\nexport class ValidationError extends SDKError {\n constructor(message: string, public field?: string) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class RateLimitError extends SDKError {\n constructor(\n message: string,\n public retryAfter?: number,\n public limit?: number,\n public remaining?: number\n ) {\n super(message, 'RATE_LIMIT_ERROR');\n this.name = 'RateLimitError';\n Object.setPrototypeOf(this, RateLimitError.prototype);\n }\n}\n\nexport class APIError extends SDKError {\n constructor(\n message: string,\n public statusCode?: number,\n public requestId?: string,\n public details?: unknown\n ) {\n super(message, 'API_ERROR');\n this.name = 'APIError';\n Object.setPrototypeOf(this, APIError.prototype);\n }\n}\n","/**\n * Authentication utilities for Memory Intelligence SDK\n */\n\nimport { AuthenticationError, ConfigurationError } from './errors.js';\n\nconst DEFAULT_BASE_URL = 'https://api.memoryintelligence.io';\n\n/**\n * Validate API key format.\n * Keys should be in format: mi_sk_beta_<secret> or mi_sk_live_<secret>\n */\nexport function validateApiKey(apiKey: string): void {\n if (!apiKey) {\n throw new ConfigurationError('API key is required');\n }\n\n if (typeof apiKey !== 'string') {\n throw new ConfigurationError('API key must be a string');\n }\n\n if (!apiKey.startsWith('mi_sk_')) {\n throw new AuthenticationError(\n 'Invalid API key format. Must start with mi_sk_'\n );\n }\n\n const parts = apiKey.split('_');\n if (parts.length < 4) {\n throw new AuthenticationError(\n 'Invalid API key format. Expected: mi_sk_{env}_{secret}'\n );\n }\n\n const environment = parts[2];\n const validEnvironments = ['beta', 'test', 'live'];\n if (!validEnvironments.includes(environment)) {\n throw new AuthenticationError(\n `Invalid API key environment: ${environment}. Must be one of: ${validEnvironments.join(', ')}`\n );\n }\n}\n\n/**\n * Resolve base URL from environment or use default.\n */\nexport function resolveBaseUrl(providedUrl?: string): string {\n // Explicit URL takes precedence\n if (providedUrl) {\n return providedUrl.replace(/\\/$/, ''); // Remove trailing slash\n }\n\n // Check environment variable\n if (typeof process !== 'undefined' && process.env?.MI_API_URL) {\n return process.env.MI_API_URL.replace(/\\/$/, '');\n }\n\n // Use default\n return DEFAULT_BASE_URL;\n}\n\n/**\n * Extract key prefix (e.g., \"mi_sk_beta\", \"mi_sk_test\", \"mi_sk_live\").\n */\nexport function getKeyPrefix(apiKey: string): string {\n const parts = apiKey.split('_');\n if (parts.length >= 3) {\n return `${parts[0]}_${parts[1]}_${parts[2]}`;\n }\n return apiKey.substring(0, 20); // Fallback for malformed keys\n}\n\n/**\n * Get key environment (beta/test/production).\n */\nexport function getKeyEnvironment(apiKey: string): string {\n const parts = apiKey.split('_');\n const env = parts[2] || 'unknown';\n \n // Map 'live' to 'production' for consistency\n if (env === 'live') {\n return 'production';\n }\n \n return env;\n}\n","/**\n * Enumerations for Memory Intelligence SDK\n * \n * These enums match the Python SDK exactly to ensure API compatibility.\n */\n\n/**\n * Governance scope for memory isolation.\n * Scopes are cryptographic boundaries—data in one scope is\n * technically inaccessible from another.\n */\nexport enum Scope {\n USER = 'user',\n CLIENT = 'client',\n PROJECT = 'project',\n TEAM = 'team',\n ORGANIZATION = 'org',\n ALL = 'all',\n}\n\n/**\n * What to retain after processing.\n * Privacy by design: MEANING_ONLY is the default.\n */\nexport enum RetentionPolicy {\n MEANING_ONLY = 'meaning_only',\n FULL = 'full',\n SUMMARY_ONLY = 'summary_only',\n}\n\n/**\n * How to handle detected PII.\n */\nexport enum PIIHandling {\n DETECT_ONLY = 'detect_only',\n EXTRACT_AND_REDACT = 'extract_and_redact',\n HASH = 'hash',\n REJECT = 'reject',\n}\n\n/**\n * Provenance tracking level.\n */\nexport enum ProvenanceMode {\n STANDARD = 'standard',\n AUTHORSHIP = 'authorship',\n AUDIT = 'audit',\n}\n\n/**\n * Level of explanation to include in responses.\n */\nexport enum ExplainLevel {\n NONE = 'none',\n HUMAN = 'human',\n AUDIT = 'audit',\n FULL = 'full',\n}\n","/**\n * HTTP client for Memory Intelligence SDK\n * \n * Provides fetch wrapper with:\n * - Automatic retries\n * - Rate limit handling\n * - Error mapping\n * - Request ID tracking\n */\n\nimport {\n APIError,\n AuthenticationError,\n RateLimitError,\n ValidationError,\n} from './errors.js';\nimport type { RateLimit, SDKResponse } from './models.js';\n\nexport interface HTTPClientConfig {\n apiKey: string;\n baseUrl: string;\n timeout?: number;\n maxRetries?: number;\n}\n\nexport interface RequestOptions {\n method?: string;\n body?: unknown;\n signal?: AbortSignal;\n headers?: Record<string, string>;\n}\n\n/**\n * HTTP client with retry logic and error handling.\n */\nexport class HTTPClient {\n private apiKey: string;\n private baseUrl: string;\n private timeout: number;\n private maxRetries: number;\n\n constructor(config: HTTPClientConfig) {\n this.apiKey = config.apiKey;\n this.baseUrl = config.baseUrl;\n this.timeout = config.timeout || 30000; // 30s default\n this.maxRetries = config.maxRetries || 3;\n }\n\n /**\n * Make HTTP request with retry logic.\n */\n async request<T>(\n endpoint: string,\n options: RequestOptions = {}\n ): Promise<SDKResponse<T>> {\n const url = `${this.baseUrl}${endpoint}`;\n const method = options.method || 'GET';\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt < this.maxRetries; attempt++) {\n try {\n const response = await this.makeRequest(url, method, options);\n const rateLimit = this.extractRateLimit(response);\n const requestId = response.headers.get('x-request-id') || undefined;\n\n // Handle error responses\n if (!response.ok) {\n await this.handleErrorResponse(response, requestId);\n }\n\n const data = await response.json();\n\n return {\n data: data as T,\n rateLimit,\n requestId,\n };\n } catch (error) {\n lastError = error as Error;\n\n // Don't retry on auth errors or validation errors\n if (\n error instanceof AuthenticationError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n\n // Don't retry on rate limit errors (should wait)\n if (error instanceof RateLimitError) {\n throw error;\n }\n\n // Wait before retry (exponential backoff)\n if (attempt < this.maxRetries - 1) {\n const delay = Math.min(1000 * Math.pow(2, attempt), 10000);\n await this.sleep(delay);\n }\n }\n }\n\n // All retries failed\n throw new APIError(\n `Request failed after ${this.maxRetries} attempts: ${lastError?.message}`,\n undefined,\n undefined,\n lastError\n );\n }\n\n /**\n * Make single HTTP request.\n */\n private async makeRequest(\n url: string,\n method: string,\n options: RequestOptions\n ): Promise<Response> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n 'X-MI-SDK-Version': '2.0.0',\n 'X-MI-SDK-Language': 'typescript',\n ...options.headers,\n };\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Combine user signal with timeout signal\n const signal = options.signal || controller.signal;\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal,\n });\n\n return response;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Extract rate limit information from response headers.\n */\n private extractRateLimit(response: Response): RateLimit | undefined {\n const limit = response.headers.get('x-ratelimit-limit');\n const remaining = response.headers.get('x-ratelimit-remaining');\n const reset = response.headers.get('x-ratelimit-reset');\n\n if (!limit && !remaining && !reset) {\n return undefined;\n }\n\n return {\n limit: limit ? parseInt(limit, 10) : undefined,\n remaining: remaining ? parseInt(remaining, 10) : undefined,\n reset: reset ? parseInt(reset, 10) : undefined,\n };\n }\n\n /**\n * Handle error responses from API.\n */\n private async handleErrorResponse(\n response: Response,\n requestId?: string\n ): Promise<never> {\n const statusCode = response.status;\n let errorData: any;\n\n try {\n errorData = await response.json();\n } catch {\n errorData = { detail: response.statusText };\n }\n\n const message = errorData.detail || errorData.message || 'Unknown error';\n\n // Map status codes to error types\n switch (statusCode) {\n case 401:\n throw new AuthenticationError(message);\n\n case 400:\n throw new ValidationError(message);\n\n case 429: {\n const retryAfter = response.headers.get('retry-after');\n const rateLimit = this.extractRateLimit(response);\n throw new RateLimitError(\n message,\n retryAfter ? parseInt(retryAfter, 10) : undefined,\n rateLimit?.limit,\n rateLimit?.remaining\n );\n }\n\n default:\n throw new APIError(message, statusCode, requestId, errorData);\n }\n }\n\n /**\n * Sleep utility for retry backoff.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * WebSocket connection manager for Memory Intelligence SDK\n * \n * Handles persistent connections, auto-reconnect, and subscription routing.\n */\n\nimport { SDKError } from './errors.js';\n\nexport interface WebSocketConfig {\n url: string;\n apiKey: string;\n orgUlid?: string;\n reconnectDelay?: number;\n maxReconnectAttempts?: number;\n pingInterval?: number;\n}\n\ninterface ResolvedWebSocketConfig {\n url: string;\n apiKey: string;\n orgUlid?: string;\n reconnectDelay: number;\n maxReconnectAttempts: number;\n pingInterval: number;\n}\n\nexport interface SubscriptionMessage {\n type: 'subscribe' | 'unsubscribe';\n subscription_id: string;\n stream: string;\n filters?: Record<string, any>;\n function_name?: string;\n parameters?: Record<string, any>;\n}\n\nexport interface ServerMessage {\n type: string;\n subscription_id?: string;\n [key: string]: any;\n}\n\nexport type MessageHandler = (message: ServerMessage) => void;\n\n/**\n * WebSocket connection manager with auto-reconnect and subscription routing.\n */\nexport class WebSocketManager {\n private ws: WebSocket | null = null;\n private config: ResolvedWebSocketConfig;\n private reconnectAttempts = 0;\n private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;\n private pingIntervalId: ReturnType<typeof setInterval> | null = null;\n private subscriptions = new Map<string, MessageHandler>();\n private connectionPromise: Promise<void> | null = null;\n private isConnecting = false;\n private isClosed = false;\n\n // Event handlers\n private onConnectHandlers: Array<() => void> = [];\n private onDisconnectHandlers: Array<() => void> = [];\n private onErrorHandlers: Array<(error: Error) => void> = [];\n\n constructor(config: WebSocketConfig) {\n this.config = {\n url: config.url,\n apiKey: config.apiKey,\n orgUlid: config.orgUlid,\n reconnectDelay: config.reconnectDelay || 1000,\n maxReconnectAttempts: config.maxReconnectAttempts || 5,\n pingInterval: config.pingInterval || 30000,\n };\n }\n\n /**\n * Connect to WebSocket server.\n */\n async connect(): Promise<void> {\n if (this.ws?.readyState === WebSocket.OPEN) {\n return Promise.resolve();\n }\n\n if (this.isConnecting && this.connectionPromise) {\n return this.connectionPromise;\n }\n\n this.isConnecting = true;\n this.connectionPromise = new Promise((resolve, reject) => {\n try {\n // Build WebSocket URL with auth\n const url = new URL(this.config.url);\n url.searchParams.append('api_key', this.config.apiKey);\n if (this.config.orgUlid) {\n url.searchParams.append('org_ulid', this.config.orgUlid);\n }\n\n this.ws = new WebSocket(url.toString());\n\n this.ws.onopen = () => {\n this.isConnecting = false;\n this.reconnectAttempts = 0;\n this.startPingInterval();\n this.onConnectHandlers.forEach((handler) => handler());\n resolve();\n };\n\n this.ws.onmessage = (event) => {\n try {\n const message: ServerMessage = JSON.parse(event.data);\n this.handleMessage(message);\n } catch (error) {\n console.error('Failed to parse WebSocket message:', error);\n }\n };\n\n this.ws.onerror = () => {\n const error = new SDKError('WebSocket connection error');\n this.onErrorHandlers.forEach((handler) => handler(error));\n \n if (this.isConnecting) {\n this.isConnecting = false;\n reject(error);\n }\n };\n\n this.ws.onclose = () => {\n this.stopPingInterval();\n this.onDisconnectHandlers.forEach((handler) => handler());\n\n if (!this.isClosed) {\n this.attemptReconnect();\n }\n };\n } catch (error) {\n this.isConnecting = false;\n reject(error instanceof Error ? error : new SDKError('Failed to connect'));\n }\n });\n\n return this.connectionPromise;\n }\n\n /**\n * Disconnect from WebSocket server.\n */\n disconnect(): void {\n this.isClosed = true;\n this.stopPingInterval();\n \n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n\n this.subscriptions.clear();\n }\n\n /**\n * Subscribe to a stream.\n */\n async subscribe(message: SubscriptionMessage, handler: MessageHandler): Promise<void> {\n await this.connect();\n\n this.subscriptions.set(message.subscription_id, handler);\n this.send(message);\n }\n\n /**\n * Unsubscribe from a stream.\n */\n unsubscribe(subscriptionId: string): void {\n this.subscriptions.delete(subscriptionId);\n \n if (this.ws?.readyState === WebSocket.OPEN) {\n this.send({\n type: 'unsubscribe',\n subscription_id: subscriptionId,\n stream: '', // Required by API but not used for unsubscribe\n });\n }\n }\n\n /**\n * Register connect event handler.\n */\n onConnect(handler: () => void): void {\n this.onConnectHandlers.push(handler);\n }\n\n /**\n * Register disconnect event handler.\n */\n onDisconnect(handler: () => void): void {\n this.onDisconnectHandlers.push(handler);\n }\n\n /**\n * Register error event handler.\n */\n onError(handler: (error: Error) => void): void {\n this.onErrorHandlers.push(handler);\n }\n\n /**\n * Check if connected.\n */\n isConnected(): boolean {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n /**\n * Send message to server.\n */\n private send(message: any): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new SDKError('WebSocket not connected');\n }\n\n this.ws.send(JSON.stringify(message));\n }\n\n /**\n * Handle incoming message from server.\n */\n private handleMessage(message: ServerMessage): void {\n // Handle pong\n if (message.type === 'pong') {\n return;\n }\n\n // Route to subscription handler\n if (message.subscription_id) {\n const handler = this.subscriptions.get(message.subscription_id);\n if (handler) {\n handler(message);\n }\n }\n }\n\n /**\n * Start ping interval to keep connection alive.\n */\n private startPingInterval(): void {\n this.stopPingInterval();\n \n this.pingIntervalId = setInterval(() => {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.send({ type: 'ping' });\n }\n }, this.config.pingInterval);\n }\n\n /**\n * Stop ping interval.\n */\n private stopPingInterval(): void {\n if (this.pingIntervalId) {\n clearInterval(this.pingIntervalId);\n this.pingIntervalId = null;\n }\n }\n\n /**\n * Attempt to reconnect with exponential backoff.\n */\n private attemptReconnect(): void {\n if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {\n const error = new SDKError(\n `Failed to reconnect after ${this.config.maxReconnectAttempts} attempts`\n );\n this.onErrorHandlers.forEach((handler) => handler(error));\n return;\n }\n\n const delay = this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts);\n this.reconnectAttempts++;\n\n this.reconnectTimeout = setTimeout(() => {\n this.connect().catch((error) => {\n console.error('Reconnect failed:', error);\n });\n }, delay);\n }\n}\n","/**\n * Base subscription class for all WebSocket subscriptions.\n */\n\nimport type { WebSocketManager, ServerMessage } from '../websocket.js';\n\nexport type EventHandler<T = any> = (data: T) => void;\n\n/**\n * Base class for WebSocket subscriptions.\n */\nexport abstract class BaseSubscription<T = any> {\n protected subscriptionId: string;\n protected ws: WebSocketManager;\n protected eventHandlers = new Map<string, EventHandler<T>[]>();\n protected isActive = false;\n\n constructor(ws: WebSocketManager) {\n this.ws = ws;\n this.subscriptionId = this.generateSubscriptionId();\n }\n\n /**\n * Start the subscription.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stop the subscription.\n */\n stop(): void {\n if (this.isActive) {\n this.ws.unsubscribe(this.subscriptionId);\n this.isActive = false;\n this.emit('disconnected', null as any);\n }\n }\n\n /**\n * Register an event handler.\n */\n on(event: string, handler: EventHandler<T>): this {\n if (!this.eventHandlers.has(event)) {\n this.eventHandlers.set(event, []);\n }\n this.eventHandlers.get(event)!.push(handler);\n return this;\n }\n\n /**\n * Remove an event handler.\n */\n off(event: string, handler: EventHandler<T>): this {\n const handlers = this.eventHandlers.get(event);\n if (handlers) {\n const index = handlers.indexOf(handler);\n if (index !== -1) {\n handlers.splice(index, 1);\n }\n }\n return this;\n }\n\n /**\n * Emit an event to all registered handlers.\n */\n protected emit(event: string, data: T): void {\n const handlers = this.eventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n console.error(`Error in ${event} handler:`, error);\n }\n });\n }\n }\n\n /**\n * Handle incoming message from server.\n */\n protected abstract handleMessage(message: ServerMessage): void;\n\n /**\n * Generate unique subscription ID.\n */\n protected generateSubscriptionId(): string {\n return `sub_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n }\n\n /**\n * Check if subscription is active.\n */\n isSubscribed(): boolean {\n return this.isActive;\n }\n}\n","/**\n * Drift subscription for real-time entity meaning change notifications.\n */\n\nimport { BaseSubscription } from './base.js';\nimport type { WebSocketManager, ServerMessage } from '../websocket.js';\n\nexport interface DriftUpdate {\n entityUlid: string;\n canonicalName: string;\n driftEpoch: number;\n driftMagnitude: number;\n meaningStable: boolean;\n updatedAt: string;\n explainHuman: {\n driftSummary: string;\n whatChanged: {\n summary: string;\n changes: string[];\n };\n impactOnResults: string;\n confidenceAssessment: string;\n };\n signals: Array<{\n signal: string;\n magnitude: number;\n isAnomalous: boolean;\n }>;\n}\n\nexport interface DriftSubscriptionOptions {\n entityUlids?: string[];\n orgUlid?: string;\n}\n\n/**\n * Subscription for drift updates on entities.\n * \n * Events:\n * - 'update': (update: DriftUpdate) => void - New drift update received\n * - 'connected': () => void - Subscription established\n * - 'disconnected': () => void - Subscription closed\n * - 'error': (error: Error) => void - Error occurred\n */\nexport class DriftSubscription extends BaseSubscription<DriftUpdate> {\n private options: DriftSubscriptionOptions;\n\n constructor(ws: WebSocketManager, options: DriftSubscriptionOptions = {}) {\n super(ws);\n this.options = options;\n }\n\n /**\n * Start the drift subscription.\n */\n async start(): Promise<void> {\n const filters: Record<string, any> = {};\n \n if (this.options.entityUlids) {\n filters.entity_ulids = this.options.entityUlids;\n }\n \n if (this.options.orgUlid) {\n filters.org_ulid = this.options.orgUlid;\n }\n\n await this.ws.subscribe(\n {\n type: 'subscribe',\n subscription_id: this.subscriptionId,\n stream: 'drift_updates',\n filters,\n },\n (message) => this.handleMessage(message)\n );\n\n this.isActive = true;\n }\n\n /**\n * Handle incoming drift update message.\n */\n protected handleMessage(message: ServerMessage): void {\n switch (message.type) {\n case 'subscribed':\n this.emit('connected', undefined as any);\n break;\n\n case 'drift_update':\n const update: DriftUpdate = {\n entityUlid: message.entity_ulid,\n canonicalName: message.canonical_name,\n driftEpoch: message.drift_epoch,\n driftMagnitude: message.drift_magnitude,\n meaningStable: message.meaning_stable,\n updatedAt: message.updated_at,\n explainHuman: {\n driftSummary: message.explain_human.drift_summary,\n whatChanged: {\n summary: message.explain_human.what_changed.summary,\n changes: message.explain_human.what_changed.changes,\n },\n impactOnResults: message.explain_human.impact_on_results,\n confidenceAssessment: message.explain_human.confidence_assessment,\n },\n signals: message.signals || [],\n };\n this.emit('update', update);\n break;\n\n case 'error':\n this.emit('error', new Error(message.message || 'Subscription error') as any);\n break;\n }\n }\n}\n","/**\n * Compute subscription for long-running operation progress and results.\n */\n\nimport { BaseSubscription } from './base.js';\nimport type { WebSocketManager, ServerMessage } from '../websocket.js';\n\nexport interface ComputeProgress {\n status: 'analyzing' | 'processing' | 'finalizing';\n progressPercent: number;\n message: string;\n}\n\nexport interface ComputeResult<T = any> {\n status: 'complete' | 'failed';\n result?: T;\n error?: string;\n executionTimeMs: number;\n explainHuman?: {\n summary: string;\n [key: string]: any;\n };\n}\n\nexport type ComputeUpdate<T = any> = ComputeProgress | ComputeResult<T>;\n\n/**\n * Subscription for long-running compute operations.\n * \n * Events:\n * - 'progress': (progress: ComputeProgress) => void - Progress update\n * - 'result': (result: ComputeResult) => void - Final result\n * - 'connected': () => void - Subscription established\n * - 'disconnected': () => void - Subscription closed\n * - 'error': (error: Error) => void - Error occurred\n */\nexport class ComputeSubscription<T = any> extends BaseSubscription<ComputeUpdate<T>> {\n private functionName: string;\n private parameters: Record<string, any>;\n\n constructor(\n ws: WebSocketManager,\n functionName: string,\n parameters: Record<string, any> = {}\n ) {\n super(ws);\n this.functionName = functionName;\n this.parameters = parameters;\n }\n\n /**\n * Start the compute subscription.\n */\n async start(): Promise<void> {\n await this.ws.subscribe(\n {\n type: 'subscribe',\n subscription_id: this.subscriptionId,\n stream: 'compute_result',\n function_name: this.functionName,\n parameters: this.parameters,\n },\n (message) => this.handleMessage(message)\n );\n\n this.isActive = true;\n }\n\n /**\n * Handle incoming compute message.\n */\n protected handleMessage(message: ServerMessage): void {\n switch (message.type) {\n case 'subscribed':\n this.emit('connected', undefined as any);\n break;\n\n case 'compute_progress':\n const progress: ComputeProgress = {\n status: message.status,\n progressPercent: message.progress_percent,\n message: message.message,\n };\n this.emit('progress', progress as any);\n break;\n\n case 'compute_result':\n const result: ComputeResult<T> = {\n status: message.status,\n result: message.result,\n error: message.error,\n executionTimeMs: message.execution_time_ms,\n explainHuman: message.explain_human,\n };\n this.emit('result', result as any);\n \n // Auto-unsubscribe after result\n this.stop();\n break;\n\n case 'error':\n this.emit('error', new Error(message.message || 'Compute error') as any);\n break;\n }\n }\n}\n","/**\n * Subscription exports for WebSocket streaming.\n */\n\nexport { BaseSubscription } from './base.js';\nexport { DriftSubscription } from './drift.js';\nexport { ComputeSubscription } from './compute.js';\n\nexport type { EventHandler } from './base.js';\nexport type { DriftUpdate, DriftSubscriptionOptions } from './drift.js';\nexport type { ComputeProgress, ComputeResult, ComputeUpdate } from './compute.js';\n","/**\n * Main client for Memory Intelligence SDK\n * \n * Provides the MemoryClient class and UMONamespace for all memory operations.\n */\n\nimport { validateApiKey, resolveBaseUrl } from './auth.js';\nimport {\n ExplainLevel,\n PIIHandling,\n ProvenanceMode,\n RetentionPolicy,\n Scope,\n} from './enums.js';\nimport { HTTPClient } from './http.js';\nimport { WebSocketManager } from './websocket.js';\nimport {\n DriftSubscription,\n ComputeSubscription,\n type DriftSubscriptionOptions,\n} from './subscriptions/index.js';\nimport type {\n BatchResult,\n DeleteResult,\n Explanation,\n MatchResult,\n MeaningObject,\n SearchResponse,\n} from './models.js';\n\nexport interface MemoryClientConfig {\n apiKey: string;\n baseUrl?: string;\n wsUrl?: string;\n userUlid?: string;\n orgUlid?: string;\n timeout?: number;\n maxRetries?: number;\n}\n\n/**\n * UMO Namespace - All memory operations under `mi.umo.*`\n */\nexport class UMONamespace {\n constructor(private client: MemoryClient, private http: HTTPClient) {}\n\n /**\n * Resolve user_ulid from explicit argument or client default.\n */\n private resolveUserUlid(explicit?: string): string | undefined {\n return explicit || this.client.userUlid;\n }\n\n /**\n * Process content into a Meaning Object.\n * \n * @param content - Raw text content to process\n * @param options - Processing options\n * @returns Meaning Object with entities, topics, embedding\n */\n async process(\n content: string,\n options: {\n userUlid?: string;\n retentionPolicy?: RetentionPolicy;\n piiHandling?: PIIHandling;\n provenanceMode?: ProvenanceMode;\n scope?: Scope;\n scopeId?: string;\n source?: string;\n metadata?: Record<string, unknown>;\n } = {}\n ): Promise<MeaningObject> {\n const userUlid = this.resolveUserUlid(options.userUlid);\n\n const payload = {\n content,\n user_ulid: userUlid,\n org_ulid: this.client.orgUlid,\n retention_policy: options.retentionPolicy || RetentionPolicy.MEANING_ONLY,\n pii_handling: options.piiHandling || PIIHandling.EXTRACT_AND_REDACT,\n provenance_mode: options.provenanceMode || ProvenanceMode.STANDARD,\n scope: options.scope || Scope.USER,\n scope_id: options.scopeId,\n source: options.source || 'api',\n metadata: options.metadata || {},\n };\n\n const response = await this.http.request<MeaningObject>('/v1/process', {\n method: 'POST',\n body: payload,\n });\n\n return response.data;\n }\n\n /**\n * Search memories semantically.\n * \n * @param query - Natural language query\n * @param options - Search options\n * @returns Search results with relevance scores\n */\n async search(\n query: string,\n options: {\n userUlid?: string;\n limit?: number;\n scope?: Scope;\n scopeId?: string;\n explain?: ExplainLevel;\n } = {}\n ): Promise<SearchResponse> {\n const userUlid = this.resolveUserUlid(options.userUlid);\n\n const params = new URLSearchParams();\n params.append('q', query);\n if (userUlid) params.append('user_ulid', userUlid);\n if (options.limit) params.append('limit', options.limit.toString());\n if (options.scope) params.append('scope', options.scope);\n if (options.scopeId) params.append('scope_id', options.scopeId);\n if (options.explain) params.append('explain', options.explain);\n\n const response = await this.http.request<SearchResponse>(\n `/v1/search?${params.toString()}`\n );\n\n return response.data;\n }\n\n /**\n * Match two memories for relevance.\n * \n * @param umoId1 - First meaning object ID\n * @param umoId2 - Second meaning object ID\n * @param options - Match options\n * @returns Match score and breakdown\n */\n async match(\n umoId1: string,\n umoId2: string,\n options: {\n explain?: ExplainLevel;\n } = {}\n ): Promise<MatchResult> {\n const payload = {\n umo_id_1: umoId1,\n umo_id_2: umoId2,\n explain: options.explain || ExplainLevel.NONE,\n };\n\n const response = await this.http.request<MatchResult>('/v1/match', {\n method: 'POST',\n body: payload,\n });\n\n return response.data;\n }\n\n /**\n * Get explanation for a memory.\n * \n * @param umoId - Meaning object ID\n * @param level - Explanation detail level\n * @returns Explanation with human and/or audit details\n */\n async explain(\n umoId: string,\n level: ExplainLevel = ExplainLevel.FULL\n ): Promise<Explanation> {\n const response = await this.http.request<Explanation>(\n `/v1/explain/${umoId}?level=${level}`\n );\n\n return response.data;\n }\n\n /**\n * Delete memories.\n * \n * @param options - Deletion options\n * @returns Number of memories deleted\n */\n async delete(\n options: {\n umoId?: string;\n userUlid?: string;\n scope?: Scope;\n } = {}\n ): Promise<DeleteResult> {\n const userUlid = this.resolveUserUlid(options.userUlid);\n\n const payload: any = {};\n if (options.umoId) payload.umo_id = options.umoId;\n if (userUlid) payload.user_ulid = userUlid;\n if (options.scope) payload.scope = options.scope;\n\n const response = await this.http.request<DeleteResult>('/v1/delete', {\n method: 'DELETE',\n body: payload,\n });\n\n return response.data;\n }\n\n /**\n * Batch process multiple items.\n * \n * @param items - Array of items to process\n * @returns Batch results with success/failure per item\n */\n async batch(\n items: Array<{\n content: string;\n userUlid?: string;\n metadata?: Record<string, unknown>;\n }>\n ): Promise<BatchResult> {\n const payload = {\n items: items.map((item) => ({\n content: item.content,\n user_ulid: this.resolveUserUlid(item.userUlid),\n metadata: item.metadata || {},\n })),\n };\n\n const response = await this.http.request<BatchResult>('/v1/batch', {\n method: 'POST',\n body: payload,\n });\n\n return response.data;\n }\n}\n\n/**\n * Drift Namespace - Real-time entity meaning change subscriptions\n */\nexport class DriftNamespace {\n constructor(private ws: WebSocketManager) {}\n\n /**\n * Watch for drift updates on specific entities.\n * \n * @param options - Subscription options (entity ULIDs, org filter)\n * @returns DriftSubscription instance\n * \n * @example\n * ```typescript\n * const subscription = mi.drift.watch({\n * entityUlids: ['01ARZ3NDEV5ARZ3ND']\n * });\n * \n * subscription.on('update', (update) => {\n * if (!update.meaningStable) {\n * console.log('Meaning changed:', update.explainHuman.driftSummary);\n * }\n * });\n * \n * await subscription.start();\n * ```\n */\n watch(options: DriftSubscriptionOptions = {}): DriftSubscription {\n return new DriftSubscription(this.ws, options);\n }\n}\n\n/**\n * Compute Namespace - Long-running operation progress tracking\n */\nexport class ComputeNamespace {\n constructor(private ws: WebSocketManager) {}\n\n /**\n * Watch progress of a long-running compute operation.\n * \n * @param functionName - Name of compute function\n * @param parameters - Function parameters\n * @returns ComputeSubscription instance\n * \n * Disconnect WebSocket connections.\n * Call this when shutting down the client.\n */\n disconnect(): void {\n this.ws.disconnect();\n }\n\n /**\n * @example\n * ```typescript\n * const subscription = mi.compute.watch('analyze_decision_process', {\n * narrative_ulid: '01ARZ3NDFQ69G5FAVSV4RRFF'\n * });\n * \n * subscription.on('progress', (progress) => {\n * console.log(`${progress.progressPercent}%: ${progress.message}`);\n * });\n * \n * subscription.on('result', (result) => {\n * console.log('Complete:', result.result);\n * });\n * \n * await subscription.start();\n * ```\n */\n watch<T = any>(\n functionName: string,\n parameters: Record<string, any> = {}\n ): ComputeSubscription<T> {\n return new ComputeSubscription<T>(this.ws, functionName, parameters);\n }\n}\n\n/**\n * Main Memory Intelligence Client\n * \n * Usage:\n * ```typescript\n * const mi = new MemoryClient({ apiKey: 'mi_sk_beta_...' });\n * \n * // Search\n * const results = await mi.umo.search('project planning');\n * \n * // Process\n * const umo = await mi.umo.process('Important meeting notes');\n * \n * // Watch drift\n * const driftSub = mi.drift.watch({ entityUlids: ['01ARZ...'] });\n * await driftSub.start();\n * ```\n */\nexport class MemoryClient {\n public readonly userUlid?: string;\n public readonly orgUlid?: string;\n public readonly umo: UMONamespace;\n public readonly drift: DriftNamespace;\n public readonly compute: ComputeNamespace;\n\n private http: HTTPClient;\n private ws: WebSocketManager;\n\n constructor(config: MemoryClientConfig) {\n // Validate API key\n validateApiKey(config.apiKey);\n\n // Resolve base URL\n const baseUrl = resolveBaseUrl(config.baseUrl);\n\n // Resolve WebSocket URL\n const wsUrl = config.wsUrl || baseUrl.replace(/^http/, 'ws') + '/v1/ws';\n\n // Store config\n this.userUlid = config.userUlid;\n this.orgUlid = config.orgUlid;\n\n // Initialize HTTP client\n this.http = new HTTPClient({\n apiKey: config.apiKey,\n baseUrl,\n timeout: config.timeout,\n maxRetries: config.maxRetries,\n });\n\n // Initialize WebSocket manager\n this.ws = new WebSocketManager({\n url: wsUrl,\n apiKey: config.apiKey,\n orgUlid: config.orgUlid,\n });\n\n // Initialize namespaces\n this.umo = new UMONamespace(this, this.http);\n this.drift = new DriftNamespace(this.ws);\n this.compute = new ComputeNamespace(this.ws);\n }\n\n /**\n * Create a new client instance with a different user context.\n * Useful for multi-user scenarios.\n * \n * @param userUlid - User ULID for the new context\n * @returns New MemoryClient instance\n */\n forUser(userUlid: string): MemoryClient {\n return new MemoryClient({\n apiKey: (this.http as any).apiKey, // Access private apiKey\n baseUrl: (this.http as any).baseUrl,\n userUlid,\n orgUlid: this.orgUlid,\n timeout: (this.http as any).timeout,\n maxRetries: (this.http as any).maxRetries,\n });\n }\n\n /**\n * Convenience alias for process (Batch 4.2)\n */\n async capture(content: string, userUlid?: string): Promise<MeaningObject> {\n return this.umo.process(content, { userUlid });\n }\n\n /**\n * Convenience alias for search (Batch 4.2)\n */\n async search(query: string, limit?: number): Promise<SearchResponse> {\n return this.umo.search(query, { limit });\n }\n\n /**\n * Convenience alias for explain (Batch 4.2)\n */\n async explain(umoId: string): Promise<Explanation> {\n return this.umo.explain(umoId);\n }\n\n /**\n * Convenience alias for delete (Batch 4.2)\n */\n async forget(umoId: string): Promise<DeleteResult> {\n return this.umo.delete({ umoId });\n }\n}\n","/**\n * Memory Intelligence JavaScript/TypeScript SDK\n * \n * Official SDK for building web apps, Node.js services, and edge functions\n * powered by Memory Intelligence.\n * \n * @packageDocumentation\n */\n\n// Main client\nexport { MemoryClient, UMONamespace, DriftNamespace, ComputeNamespace } from './client.js';\nexport type { MemoryClientConfig } from './client.js';\n\n// WebSocket\nexport { WebSocketManager } from './websocket.js';\nexport type { WebSocketConfig, SubscriptionMessage, ServerMessage } from './websocket.js';\n\n// Subscriptions\nexport {\n BaseSubscription,\n DriftSubscription,\n ComputeSubscription,\n} from './subscriptions/index.js';\nexport type {\n EventHandler,\n DriftUpdate,\n DriftSubscriptionOptions,\n ComputeProgress,\n ComputeResult,\n ComputeUpdate,\n} from './subscriptions/index.js';\n\n// Enums\nexport {\n Scope,\n RetentionPolicy,\n PIIHandling,\n ProvenanceMode,\n ExplainLevel,\n} from './enums.js';\n\n// Types\nexport type {\n Entity,\n Topic,\n Embedding,\n Provenance,\n MeaningObject,\n SearchResult,\n SearchResponse,\n MatchResult,\n Explanation,\n DeleteResult,\n BatchItemResult,\n BatchResult,\n RateLimit,\n SDKResponse,\n} from './models.js';\n\n// Streaming utilities\nexport {\n UMOStreamProcessor,\n SearchResultStream,\n ProgressTracker,\n streamLargeDataset,\n} from './streaming.js';\nexport type {\n StreamConfig,\n BatchProcessOptions,\n BatchSearchOptions,\n StreamIteratorOptions,\n ProgressUpdate,\n} from './streaming.js';\n\n// React Native compatibility\nexport {\n checkReactNativeCompatibility,\n setupReactNativePolyfills,\n createReactNativeClient,\n ReactNativeUtils,\n isPolyfillError,\n getPolyfillErrorHelp,\n} from './react-native.js';\nexport type {\n CompatibilityCheck,\n ReactNativeConfig,\n} from './react-native.js';\n\n// Errors\nexport {\n SDKError,\n ConfigurationError,\n AuthenticationError,\n ValidationError,\n RateLimitError,\n APIError,\n} from './errors.js';\n\n// Version\nexport const VERSION = '2.0.0';\n","/**\n * Streaming utilities for handling large datasets\n * \n * Provides:\n * - Chunked response processing\n * - Batch UMO processing\n * - Memory-efficient iteration\n * - Progress tracking\n */\n\nimport type { MeaningObject, SearchResult } from './models.js';\nimport type { MemoryClient } from './client.js';\n\nexport interface StreamConfig {\n /** Chunk size for batch operations */\n chunkSize?: number;\n /** Callback for progress updates */\n onProgress?: (processed: number, total: number) => void;\n /** Callback for chunk completion */\n onChunk?: (chunk: any[], chunkIndex: number) => void;\n /** Maximum concurrent operations */\n concurrency?: number;\n}\n\nexport interface BatchProcessOptions {\n /** Content items to process */\n items: Array<{ content: string; type?: string; metadata?: Record<string, any> }>;\n /** Streaming configuration */\n config?: StreamConfig;\n}\n\nexport interface BatchSearchOptions {\n /** Search queries to execute */\n queries: string[];\n /** Search options for each query */\n searchOptions?: {\n limit?: number;\n filters?: Record<string, any>;\n };\n /** Streaming configuration */\n config?: StreamConfig;\n}\n\nexport interface StreamIteratorOptions<T> {\n /** Data source (array or async generator) */\n source: T[] | AsyncGenerator<T>;\n /** Chunk size for processing */\n chunkSize: number;\n /** Processing function for each chunk */\n processor: (chunk: T[]) => Promise<void>;\n /** Progress callback */\n onProgress?: (processed: number) => void;\n}\n\n/**\n * Streaming helper for batch UMO processing\n */\nexport class UMOStreamProcessor {\n private client: MemoryClient;\n\n constructor(client: MemoryClient) {\n this.client = client;\n }\n\n /**\n * Process multiple content items in batches\n * to avoid overwhelming the API or memory.\n */\n async *processBatch(\n options: BatchProcessOptions\n ): AsyncGenerator<MeaningObject, void, unknown> {\n const { items, config = {} } = options;\n const { chunkSize = 10, onProgress, onChunk, concurrency = 3 } = config;\n\n const total = items.length;\n let processed = 0;\n\n // Process in chunks\n for (let i = 0; i < items.length; i += chunkSize) {\n const chunk = items.slice(i, i + chunkSize);\n \n // Process chunk with controlled concurrency\n const results = await this.processChunk(chunk, concurrency);\n \n processed += chunk.length;\n \n if (onProgress) {\n onProgress(processed, total);\n }\n\n if (onChunk) {\n onChunk(results, Math.floor(i / chunkSize));\n }\n\n // Yield each result\n for (const result of results) {\n yield result;\n }\n\n // Small delay to avoid rate limiting\n if (i + chunkSize < items.length) {\n await this.sleep(100);\n }\n }\n }\n\n /**\n * Process a chunk of items with concurrency control\n */\n private async processChunk(\n items: Array<{ content: string; type?: string; metadata?: Record<string, any> }>,\n concurrency: number\n ): Promise<MeaningObject[]> {\n const results: MeaningObject[] = [];\n \n // Process with concurrency limit\n for (let i = 0; i < items.length; i += concurrency) {\n const batch = items.slice(i, i + concurrency);\n const promises = batch.map(item =>\n this.client.umo.process(item.content, {\n source: item.type || 'text/plain',\n metadata: item.metadata,\n })\n );\n\n const batchResults = await Promise.all(promises);\n results.push(...batchResults);\n }\n\n return results;\n }\n\n /**\n * Execute multiple search queries in sequence\n */\n async *searchBatch(\n options: BatchSearchOptions\n ): AsyncGenerator<{ query: string; results: SearchResult[] }, void, unknown> {\n const { queries, searchOptions = {}, config = {} } = options;\n const { onProgress } = config;\n\n const total = queries.length;\n\n for (let i = 0; i < queries.length; i++) {\n const query = queries[i];\n \n const response = await this.client.umo.search(query, {\n limit: searchOptions.limit || 10,\n });\n\n if (onProgress) {\n onProgress(i + 1, total);\n }\n\n yield {\n query,\n results: response.results,\n };\n\n // Rate limit protection\n if (i < queries.length - 1) {\n await this.sleep(50);\n }\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Generic streaming iterator for large datasets\n */\nexport async function* streamLargeDataset<T>(\n options: StreamIteratorOptions<T>\n): AsyncGenerator<T[], void, unknown> {\n const { source, chunkSize, processor, onProgress } = options;\n let chunk: T[] = [];\n let processed = 0;\n\n if (Array.isArray(source)) {\n // Handle array source\n for (let i = 0; i < source.length; i++) {\n chunk.push(source[i]);\n\n if (chunk.length >= chunkSize || i === source.length - 1) {\n await processor(chunk);\n yield chunk;\n \n processed += chunk.length;\n if (onProgress) {\n onProgress(processed);\n }\n\n chunk = [];\n }\n }\n } else {\n // Handle async generator source\n for await (const item of source) {\n chunk.push(item);\n\n if (chunk.length >= chunkSize) {\n await processor(chunk);\n yield chunk;\n \n processed += chunk.length;\n if (onProgress) {\n onProgress(processed);\n }\n\n chunk = [];\n }\n }\n\n // Process remaining items\n if (chunk.length > 0) {\n await processor(chunk);\n yield chunk;\n \n processed += chunk.length;\n if (onProgress) {\n onProgress(processed);\n }\n }\n }\n}\n\n/**\n * Helper for processing search results in streaming fashion\n */\nexport class SearchResultStream {\n private client: MemoryClient;\n\n constructor(client: MemoryClient) {\n this.client = client;\n }\n\n /**\n * Stream search results with pagination\n */\n async *paginate(\n query: string,\n options: {\n pageSize?: number;\n maxResults?: number;\n filters?: Record<string, any>;\n } = {}\n ): AsyncGenerator<SearchResult[], void, unknown> {\n const { pageSize = 20, maxResults = 100 } = options;\n \n let offset = 0;\n let totalRetrieved = 0;\n\n while (totalRetrieved < maxResults) {\n const limit = Math.min(pageSize, maxResults - totalRetrieved);\n \n // Note: The search method doesn't support offset currently\n // This is a placeholder for when pagination is fully supported\n const response = await this.client.umo.search(query, {\n limit,\n });\n\n const results = response.results;\n \n if (results.length === 0) {\n break; // No more results\n }\n\n yield results;\n \n totalRetrieved += results.length;\n offset += results.length;\n\n // If we got fewer results than requested, we've reached the end\n if (results.length < limit) {\n break;\n }\n }\n }\n}\n\n/**\n * Progress tracker for streaming operations\n */\nexport class ProgressTracker {\n private total: number;\n private processed: number = 0;\n private startTime: number;\n private onUpdate?: (progress: ProgressUpdate) => void;\n\n constructor(total: number, onUpdate?: (progress: ProgressUpdate) => void) {\n this.total = total;\n this.startTime = Date.now();\n this.onUpdate = onUpdate;\n }\n\n update(count: number = 1): void {\n this.processed += count;\n \n if (this.onUpdate) {\n this.onUpdate(this.getProgress());\n }\n }\n\n getProgress(): ProgressUpdate {\n const elapsed = Date.now() - this.startTime;\n const rate = this.processed / (elapsed / 1000); // items/second\n const remaining = this.total - this.processed;\n const eta = remaining / rate;\n\n return {\n processed: this.processed,\n total: this.total,\n percentage: (this.processed / this.total) * 100,\n elapsed,\n rate,\n eta: isFinite(eta) ? eta : undefined,\n };\n }\n}\n\nexport interface ProgressUpdate {\n processed: number;\n total: number;\n percentage: number;\n elapsed: number; // milliseconds\n rate: number; // items per second\n eta?: number; // estimated seconds remaining\n}\n","/**\n * React Native Compatibility Layer\n * \n * Ensures the SDK works correctly in React Native environments\n * by detecting and polyfilling missing APIs.\n * \n * Usage:\n * ```typescript\n * import { checkReactNativeCompatibility, setupReactNativePolyfills } from '@memoryintelligence/sdk/react-native';\n * \n * // In your app entry point (App.tsx)\n * const compatibility = checkReactNativeCompatibility();\n * if (!compatibility.compatible) {\n * console.warn('Missing APIs:', compatibility.missing);\n * setupReactNativePolyfills(); // Auto-install available polyfills\n * }\n * ```\n */\n\nexport interface CompatibilityCheck {\n compatible: boolean;\n missing: string[];\n warnings: string[];\n polyfillsAvailable: string[];\n}\n\nexport interface ReactNativeConfig {\n /** Custom fetch implementation */\n fetch?: typeof fetch;\n /** Custom WebSocket implementation */\n WebSocket?: typeof WebSocket;\n /** Custom crypto implementation */\n crypto?: any; // Use 'any' for React Native crypto polyfills\n /** Custom Text encoder implementation */\n TextEncoder?: typeof TextEncoder;\n /** Custom Text decoder implementation */\n TextDecoder?: typeof TextDecoder;\n}\n\n/**\n * Check if the current environment is React Native compatible\n */\nexport function checkReactNativeCompatibility(): CompatibilityCheck {\n const missing: string[] = [];\n const warnings: string[] = [];\n const polyfillsAvailable: string[] = [];\n\n // Check for fetch\n if (typeof global.fetch === 'undefined') {\n missing.push('fetch');\n polyfillsAvailable.push('whatwg-fetch');\n }\n\n // Check for WebSocket\n if (typeof global.WebSocket === 'undefined') {\n missing.push('WebSocket');\n warnings.push('WebSocket not available - drift/compute subscriptions will not work');\n }\n\n // Check for crypto (needed for hash verification)\n if (typeof global.crypto === 'undefined') {\n missing.push('crypto');\n polyfillsAvailable.push('react-native-get-random-values');\n polyfillsAvailable.push('crypto-js');\n }\n\n // Check for TextEncoder/TextDecoder\n if (typeof global.TextEncoder === 'undefined') {\n missing.push('TextEncoder');\n polyfillsAvailable.push('text-encoding');\n }\n\n if (typeof global.TextDecoder === 'undefined') {\n missing.push('TextDecoder');\n polyfillsAvailable.push('text-encoding');\n }\n\n // Check for AbortController (needed for request timeouts)\n if (typeof global.AbortController === 'undefined') {\n missing.push('AbortController');\n polyfillsAvailable.push('abortcontroller-polyfill');\n }\n\n // Check for URL (should be available in modern RN)\n if (typeof global.URL === 'undefined') {\n missing.push('URL');\n warnings.push('URL constructor not available');\n }\n\n return {\n compatible: missing.length === 0,\n missing,\n warnings,\n polyfillsAvailable: [...new Set(polyfillsAvailable)],\n };\n}\n\n/**\n * Automatically setup polyfills for React Native\n * \n * Note: This requires the polyfill packages to be installed:\n * ```bash\n * npm install whatwg-fetch react-native-get-random-values abortcontroller-polyfill text-encoding\n * ```\n */\nexport function setupReactNativePolyfills(): void {\n try {\n // Install fetch polyfill\n if (typeof global.fetch === 'undefined') {\n try {\n require('whatwg-fetch');\n console.log('✓ fetch polyfill loaded');\n } catch {\n console.warn('⚠️ whatwg-fetch not installed. Install with: npm install whatwg-fetch');\n }\n }\n\n // Install crypto polyfill\n if (typeof global.crypto === 'undefined') {\n try {\n const getRandomValues = require('react-native-get-random-values');\n if (typeof global.crypto === 'undefined') {\n global.crypto = {\n getRandomValues: getRandomValues.getRandomValues,\n } as any;\n }\n console.log('✓ crypto polyfill loaded');\n } catch {\n console.warn('⚠️ react-native-get-random-values not installed. Install with: npm install react-native-get-random-values');\n }\n }\n\n // Install TextEncoder/TextDecoder polyfill\n if (typeof global.TextEncoder === 'undefined' || typeof global.TextDecoder === 'undefined') {\n try {\n const encoding = require('text-encoding');\n if (typeof global.TextEncoder === 'undefined') {\n global.TextEncoder = encoding.TextEncoder;\n }\n if (typeof global.TextDecoder === 'undefined') {\n global.TextDecoder = encoding.TextDecoder;\n }\n console.log('✓ TextEncoder/TextDecoder polyfill loaded');\n } catch {\n console.warn('⚠️ text-encoding not installed. Install with: npm install text-encoding');\n }\n }\n\n // Install AbortController polyfill\n if (typeof global.AbortController === 'undefined') {\n try {\n const AbortController = require('abortcontroller-polyfill/dist/cjs-ponyfill').AbortController;\n global.AbortController = AbortController;\n console.log('✓ AbortController polyfill loaded');\n } catch {\n console.warn('⚠️ abortcontroller-polyfill not installed. Install with: npm install abortcontroller-polyfill');\n }\n }\n } catch (error) {\n console.error('Error setting up React Native polyfills:', error);\n }\n}\n\n/**\n * Create a configured MemoryClient for React Native\n */\nexport function createReactNativeClient(\n apiKey: string,\n options: ReactNativeConfig & { baseUrl?: string } = {}\n): any {\n // Import MemoryClient dynamically to avoid circular deps\n const { MemoryClient } = require('./client.js');\n\n // Apply polyfills if provided\n if (options.fetch) {\n global.fetch = options.fetch as any;\n }\n if (options.WebSocket) {\n global.WebSocket = options.WebSocket as any;\n }\n if (options.crypto) {\n global.crypto = options.crypto as any;\n }\n if (options.TextEncoder) {\n global.TextEncoder = options.TextEncoder as any;\n }\n if (options.TextDecoder) {\n global.TextDecoder = options.TextDecoder as any;\n }\n\n // Check compatibility\n const compatibility = checkReactNativeCompatibility();\n if (!compatibility.compatible) {\n console.warn(\n 'Memory Intelligence SDK is not fully compatible with this React Native environment.\\n' +\n 'Missing APIs:', compatibility.missing.join(', ') + '\\n' +\n 'Install polyfills:', compatibility.polyfillsAvailable.join(', ')\n );\n }\n\n if (compatibility.warnings.length > 0) {\n compatibility.warnings.forEach(warning => console.warn('⚠️ ', warning));\n }\n\n return new MemoryClient({\n apiKey,\n baseUrl: options.baseUrl,\n });\n}\n\n/**\n * React Native specific utilities\n */\nexport const ReactNativeUtils = {\n /**\n * Check if running in React Native environment\n */\n isReactNative(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n (navigator as any).product === 'ReactNative'\n );\n },\n\n /**\n * Get recommended polyfill packages for current environment\n */\n getRecommendedPolyfills(): string[] {\n const compatibility = checkReactNativeCompatibility();\n return compatibility.polyfillsAvailable;\n },\n\n /**\n * Generate installation command for missing polyfills\n */\n getInstallCommand(): string | null {\n const polyfills = this.getRecommendedPolyfills();\n if (polyfills.length === 0) return null;\n \n return `npm install ${polyfills.join(' ')}`;\n },\n};\n\n/**\n * Type guard to check if error is a polyfill error\n */\nexport function isPolyfillError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n \n const message = error.message.toLowerCase();\n return (\n message.includes('fetch is not defined') ||\n message.includes('websocket is not defined') ||\n message.includes('crypto is not defined') ||\n message.includes('textencoder is not defined') ||\n message.includes('abortcontroller is not defined')\n );\n}\n\n/**\n * Helper to provide detailed polyfill error messages\n */\nexport function getPolyfillErrorHelp(error: unknown): string | null {\n if (!isPolyfillError(error)) return null;\n\n const compatibility = checkReactNativeCompatibility();\n \n return `\nReact Native Polyfill Required\n==============================\n\nThe Memory Intelligence SDK requires some Web APIs that are not available\nin React Native by default.\n\nMissing APIs: ${compatibility.missing.join(', ')}\n\nTo fix this, install the required polyfills:\n\n ${ReactNativeUtils.getInstallCommand()}\n\nThen in your app entry point (App.tsx):\n\n import 'react-native-get-random-values'; // Must be first\n import 'whatwg-fetch';\n import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';\n import { MemoryClient } from '@memoryintelligence/sdk';\n\n const client = new MemoryClient({ apiKey: 'your-key' });\n\nFor more info: https://docs.memoryintelligence.io/sdk/react-native\n`;\n}\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
var I=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var U=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var u=(s,e)=>()=>(s&&(e=s(s=0)),e);var ie=(s,e)=>{for(var t in e)I(s,t,{get:e[t],enumerable:true});},oe=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ne(e))!se.call(s,r)&&r!==t&&I(s,r,{get:()=>e[r],enumerable:!(n=re(e,r))||n.enumerable});return s};var ae=s=>oe(I({},"__esModule",{value:true}),s);var p,g,d,f,y,b,w=u(()=>{p=class s extends Error{constructor(t,n){super(t);this.code=n;this.name="SDKError",Object.setPrototypeOf(this,s.prototype);}},g=class s extends p{constructor(e){super(e,"CONFIGURATION_ERROR"),this.name="ConfigurationError",Object.setPrototypeOf(this,s.prototype);}},d=class s extends p{constructor(e){super(e,"AUTHENTICATION_ERROR"),this.name="AuthenticationError",Object.setPrototypeOf(this,s.prototype);}},f=class s extends p{constructor(t,n){super(t,"VALIDATION_ERROR");this.field=n;this.name="ValidationError",Object.setPrototypeOf(this,s.prototype);}},y=class s extends p{constructor(t,n,r,i){super(t,"RATE_LIMIT_ERROR");this.retryAfter=n;this.limit=r;this.remaining=i;this.name="RateLimitError",Object.setPrototypeOf(this,s.prototype);}},b=class s extends p{constructor(t,n,r,i){super(t,"API_ERROR");this.statusCode=n;this.requestId=r;this.details=i;this.name="APIError",Object.setPrototypeOf(this,s.prototype);}};});function G(s){if(!s)throw new g("API key is required");if(typeof s!="string")throw new g("API key must be a string");if(!s.startsWith("mi_sk_"))throw new d("Invalid API key format. Must start with mi_sk_");let e=s.split("_");if(e.length<4)throw new d("Invalid API key format. Expected: mi_sk_{env}_{secret}");let t=e[2],n=["beta","test","live"];if(!n.includes(t))throw new d(`Invalid API key environment: ${t}. Must be one of: ${n.join(", ")}`)}function z(s){return s?s.replace(/\/$/,""):typeof process<"u"&&process.env?.MI_API_URL?process.env.MI_API_URL.replace(/\/$/,""):ce}var ce,V=u(()=>{w();ce="https://api.memoryintelligence.io";});var M,_,O,D,N,H=u(()=>{M=(a=>(a.USER="user",a.CLIENT="client",a.PROJECT="project",a.TEAM="team",a.ORGANIZATION="org",a.ALL="all",a))(M||{}),_=(n=>(n.MEANING_ONLY="meaning_only",n.FULL="full",n.SUMMARY_ONLY="summary_only",n))(_||{}),O=(r=>(r.DETECT_ONLY="detect_only",r.EXTRACT_AND_REDACT="extract_and_redact",r.HASH="hash",r.REJECT="reject",r))(O||{}),D=(n=>(n.STANDARD="standard",n.AUTHORSHIP="authorship",n.AUDIT="audit",n))(D||{}),N=(r=>(r.NONE="none",r.HUMAN="human",r.AUDIT="audit",r.FULL="full",r))(N||{});});var E,J=u(()=>{w();E=class{constructor(e){this.apiKey=e.apiKey,this.baseUrl=e.baseUrl,this.timeout=e.timeout||3e4,this.maxRetries=e.maxRetries||3;}async request(e,t={}){let n=`${this.baseUrl}${e}`,r=t.method||"GET",i;for(let a=0;a<this.maxRetries;a++)try{let o=await this.makeRequest(n,r,t),c=this.extractRateLimit(o),l=o.headers.get("x-request-id")||void 0;return o.ok||await this.handleErrorResponse(o,l),{data:await o.json(),rateLimit:c,requestId:l}}catch(o){if(i=o,o instanceof d||o instanceof f||o instanceof y)throw o;if(a<this.maxRetries-1){let c=Math.min(1e3*Math.pow(2,a),1e4);await this.sleep(c);}}throw new b(`Request failed after ${this.maxRetries} attempts: ${i?.message}`,void 0,void 0,i)}async makeRequest(e,t,n){let r={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-MI-SDK-Version":"2.0.0","X-MI-SDK-Language":"typescript",...n.headers},i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout),o=n.signal||i.signal;try{return await fetch(e,{method:t,headers:r,body:n.body?JSON.stringify(n.body):void 0,signal:o})}finally{clearTimeout(a);}}extractRateLimit(e){let t=e.headers.get("x-ratelimit-limit"),n=e.headers.get("x-ratelimit-remaining"),r=e.headers.get("x-ratelimit-reset");if(!(!t&&!n&&!r))return {limit:t?parseInt(t,10):void 0,remaining:n?parseInt(n,10):void 0,reset:r?parseInt(r,10):void 0}}async handleErrorResponse(e,t){let n=e.status,r;try{r=await e.json();}catch{r={detail:e.statusText};}let i=r.detail||r.message||"Unknown error";switch(n){case 401:throw new d(i);case 400:throw new f(i);case 429:{let a=e.headers.get("retry-after"),o=this.extractRateLimit(e);throw new y(i,a?parseInt(a,10):void 0,o?.limit,o?.remaining)}default:throw new b(i,n,t,r)}}sleep(e){return new Promise(t=>setTimeout(t,e))}};});var R,j=u(()=>{w();R=class{constructor(e){this.ws=null;this.reconnectAttempts=0;this.reconnectTimeout=null;this.pingIntervalId=null;this.subscriptions=new Map;this.connectionPromise=null;this.isConnecting=false;this.isClosed=false;this.onConnectHandlers=[];this.onDisconnectHandlers=[];this.onErrorHandlers=[];this.config={url:e.url,apiKey:e.apiKey,orgUlid:e.orgUlid,reconnectDelay:e.reconnectDelay||1e3,maxReconnectAttempts:e.maxReconnectAttempts||5,pingInterval:e.pingInterval||3e4};}async connect(){return this.ws?.readyState===WebSocket.OPEN?Promise.resolve():this.isConnecting&&this.connectionPromise?this.connectionPromise:(this.isConnecting=true,this.connectionPromise=new Promise((e,t)=>{try{let n=new URL(this.config.url);n.searchParams.append("api_key",this.config.apiKey),this.config.orgUlid&&n.searchParams.append("org_ulid",this.config.orgUlid),this.ws=new WebSocket(n.toString()),this.ws.onopen=()=>{this.isConnecting=!1,this.reconnectAttempts=0,this.startPingInterval(),this.onConnectHandlers.forEach(r=>r()),e();},this.ws.onmessage=r=>{try{let i=JSON.parse(r.data);this.handleMessage(i);}catch(i){console.error("Failed to parse WebSocket message:",i);}},this.ws.onerror=()=>{let r=new p("WebSocket connection error");this.onErrorHandlers.forEach(i=>i(r)),this.isConnecting&&(this.isConnecting=!1,t(r));},this.ws.onclose=()=>{this.stopPingInterval(),this.onDisconnectHandlers.forEach(r=>r()),this.isClosed||this.attemptReconnect();};}catch(n){this.isConnecting=false,t(n instanceof Error?n:new p("Failed to connect"));}}),this.connectionPromise)}disconnect(){this.isClosed=true,this.stopPingInterval(),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(),this.ws=null),this.subscriptions.clear();}async subscribe(e,t){await this.connect(),this.subscriptions.set(e.subscription_id,t),this.send(e);}unsubscribe(e){this.subscriptions.delete(e),this.ws?.readyState===WebSocket.OPEN&&this.send({type:"unsubscribe",subscription_id:e,stream:""});}onConnect(e){this.onConnectHandlers.push(e);}onDisconnect(e){this.onDisconnectHandlers.push(e);}onError(e){this.onErrorHandlers.push(e);}isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new p("WebSocket not connected");this.ws.send(JSON.stringify(e));}handleMessage(e){if(e.type!=="pong"&&e.subscription_id){let t=this.subscriptions.get(e.subscription_id);t&&t(e);}}startPingInterval(){this.stopPingInterval(),this.pingIntervalId=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.send({type:"ping"});},this.config.pingInterval);}stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null);}attemptReconnect(){if(this.reconnectAttempts>=this.config.maxReconnectAttempts){let t=new p(`Failed to reconnect after ${this.config.maxReconnectAttempts} attempts`);this.onErrorHandlers.forEach(n=>n(t));return}let e=this.config.reconnectDelay*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.connect().catch(t=>{console.error("Reconnect failed:",t);});},e);}};});var m,P=u(()=>{m=class{constructor(e){this.eventHandlers=new Map;this.isActive=false;this.ws=e,this.subscriptionId=this.generateSubscriptionId();}stop(){this.isActive&&(this.ws.unsubscribe(this.subscriptionId),this.isActive=false,this.emit("disconnected",null));}on(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),this}off(e,t){let n=this.eventHandlers.get(e);if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1);}return this}emit(e,t){let n=this.eventHandlers.get(e);n&&n.forEach(r=>{try{r(t);}catch(i){console.error(`Error in ${e} handler:`,i);}});}generateSubscriptionId(){return `sub_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}isSubscribed(){return this.isActive}};});var v,Y=u(()=>{P();v=class extends m{constructor(e,t={}){super(e),this.options=t;}async start(){let e={};this.options.entityUlids&&(e.entity_ulids=this.options.entityUlids),this.options.orgUlid&&(e.org_ulid=this.options.orgUlid),await this.ws.subscribe({type:"subscribe",subscription_id:this.subscriptionId,stream:"drift_updates",filters:e},t=>this.handleMessage(t)),this.isActive=true;}handleMessage(e){switch(e.type){case "subscribed":this.emit("connected",void 0);break;case "drift_update":let t={entityUlid:e.entity_ulid,canonicalName:e.canonical_name,driftEpoch:e.drift_epoch,driftMagnitude:e.drift_magnitude,meaningStable:e.meaning_stable,updatedAt:e.updated_at,explainHuman:{driftSummary:e.explain_human.drift_summary,whatChanged:{summary:e.explain_human.what_changed.summary,changes:e.explain_human.what_changed.changes},impactOnResults:e.explain_human.impact_on_results,confidenceAssessment:e.explain_human.confidence_assessment},signals:e.signals||[]};this.emit("update",t);break;case "error":this.emit("error",new Error(e.message||"Subscription error"));break}}};});var x,X=u(()=>{P();x=class extends m{constructor(e,t,n={}){super(e),this.functionName=t,this.parameters=n;}async start(){await this.ws.subscribe({type:"subscribe",subscription_id:this.subscriptionId,stream:"compute_result",function_name:this.functionName,parameters:this.parameters},e=>this.handleMessage(e)),this.isActive=true;}handleMessage(e){switch(e.type){case "subscribed":this.emit("connected",void 0);break;case "compute_progress":let t={status:e.status,progressPercent:e.progress_percent,message:e.message};this.emit("progress",t);break;case "compute_result":let n={status:e.status,result:e.result,error:e.error,executionTimeMs:e.execution_time_ms,explainHuman:e.explain_human};this.emit("result",n),this.stop();break;case "error":this.emit("error",new Error(e.message||"Compute error"));break}}};});var L=u(()=>{P();Y();X();});var Z={};ie(Z,{ComputeNamespace:()=>C,DriftNamespace:()=>T,MemoryClient:()=>A,UMONamespace:()=>S});var S,T,C,A,W=u(()=>{V();H();J();j();L();S=class{constructor(e,t){this.client=e;this.http=t;}resolveUserUlid(e){return e||this.client.userUlid}async process(e,t={}){let n=this.resolveUserUlid(t.userUlid),r={content:e,user_ulid:n,org_ulid:this.client.orgUlid,retention_policy:t.retentionPolicy||"meaning_only",pii_handling:t.piiHandling||"extract_and_redact",provenance_mode:t.provenanceMode||"standard",scope:t.scope||"user",scope_id:t.scopeId,source:t.source||"api",metadata:t.metadata||{}};return (await this.http.request("/v1/process",{method:"POST",body:r})).data}async search(e,t={}){let n=this.resolveUserUlid(t.userUlid),r=new URLSearchParams;return r.append("q",e),n&&r.append("user_ulid",n),t.limit&&r.append("limit",t.limit.toString()),t.scope&&r.append("scope",t.scope),t.scopeId&&r.append("scope_id",t.scopeId),t.explain&&r.append("explain",t.explain),(await this.http.request(`/v1/search?${r.toString()}`)).data}async match(e,t,n={}){let r={umo_id_1:e,umo_id_2:t,explain:n.explain||"none"};return (await this.http.request("/v1/match",{method:"POST",body:r})).data}async explain(e,t="full"){return (await this.http.request(`/v1/explain/${e}?level=${t}`)).data}async delete(e={}){let t=this.resolveUserUlid(e.userUlid),n={};return e.umoId&&(n.umo_id=e.umoId),t&&(n.user_ulid=t),e.scope&&(n.scope=e.scope),(await this.http.request("/v1/delete",{method:"DELETE",body:n})).data}async batch(e){let t={items:e.map(r=>({content:r.content,user_ulid:this.resolveUserUlid(r.userUlid),metadata:r.metadata||{}}))};return (await this.http.request("/v1/batch",{method:"POST",body:t})).data}},T=class{constructor(e){this.ws=e;}watch(e={}){return new v(this.ws,e)}},C=class{constructor(e){this.ws=e;}disconnect(){this.ws.disconnect();}watch(e,t={}){return new x(this.ws,e,t)}},A=class s{constructor(e){G(e.apiKey);let t=z(e.baseUrl),n=e.wsUrl||t.replace(/^http/,"ws")+"/v1/ws";this.userUlid=e.userUlid,this.orgUlid=e.orgUlid,this.http=new E({apiKey:e.apiKey,baseUrl:t,timeout:e.timeout,maxRetries:e.maxRetries}),this.ws=new R({url:n,apiKey:e.apiKey,orgUlid:e.orgUlid}),this.umo=new S(this,this.http),this.drift=new T(this.ws),this.compute=new C(this.ws);}forUser(e){return new s({apiKey:this.http.apiKey,baseUrl:this.http.baseUrl,userUlid:e,orgUlid:this.orgUlid,timeout:this.http.timeout,maxRetries:this.http.maxRetries})}async capture(e,t){return this.umo.process(e,{userUlid:t})}async search(e,t){return this.umo.search(e,{limit:t})}async explain(e){return this.umo.explain(e)}async forget(e){return this.umo.delete({umoId:e})}};});W();j();L();H();var q=class{constructor(e){this.client=e;}async*processBatch(e){let{items:t,config:n={}}=e,{chunkSize:r=10,onProgress:i,onChunk:a,concurrency:o=3}=n,c=t.length,l=0;for(let h=0;h<t.length;h+=r){let B=t.slice(h,h+r),F=await this.processChunk(B,o);l+=B.length,i&&i(l,c),a&&a(F,Math.floor(h/r));for(let te of F)yield te;h+r<t.length&&await this.sleep(100);}}async processChunk(e,t){let n=[];for(let r=0;r<e.length;r+=t){let a=e.slice(r,r+t).map(c=>this.client.umo.process(c.content,{source:c.type||"text/plain",metadata:c.metadata})),o=await Promise.all(a);n.push(...o);}return n}async*searchBatch(e){let{queries:t,searchOptions:n={},config:r={}}=e,{onProgress:i}=r,a=t.length;for(let o=0;o<t.length;o++){let c=t[o],l=await this.client.umo.search(c,{limit:n.limit||10});i&&i(o+1,a),yield {query:c,results:l.results},o<t.length-1&&await this.sleep(50);}}sleep(e){return new Promise(t=>setTimeout(t,e))}};async function*le(s){let{source:e,chunkSize:t,processor:n,onProgress:r}=s,i=[],a=0;if(Array.isArray(e))for(let o=0;o<e.length;o++)i.push(e[o]),(i.length>=t||o===e.length-1)&&(await n(i),yield i,a+=i.length,r&&r(a),i=[]);else {for await(let o of e)i.push(o),i.length>=t&&(await n(i),yield i,a+=i.length,r&&r(a),i=[]);i.length>0&&(await n(i),yield i,a+=i.length,r&&r(a));}}var K=class{constructor(e){this.client=e;}async*paginate(e,t={}){let{pageSize:n=20,maxResults:r=100}=t,i=0,a=0;for(;a<r;){let o=Math.min(n,r-a),l=(await this.client.umo.search(e,{limit:o})).results;if(l.length===0||(yield l,a+=l.length,i+=l.length,l.length<o))break}}},$=class{constructor(e,t){this.processed=0;this.total=e,this.startTime=Date.now(),this.onUpdate=t;}update(e=1){this.processed+=e,this.onUpdate&&this.onUpdate(this.getProgress());}getProgress(){let e=Date.now()-this.startTime,t=this.processed/(e/1e3),r=(this.total-this.processed)/t;return {processed:this.processed,total:this.total,percentage:this.processed/this.total*100,elapsed:e,rate:t,eta:isFinite(r)?r:void 0}}};function k(){let s=[],e=[],t=[];return typeof global.fetch>"u"&&(s.push("fetch"),t.push("whatwg-fetch")),typeof global.WebSocket>"u"&&(s.push("WebSocket"),e.push("WebSocket not available - drift/compute subscriptions will not work")),typeof global.crypto>"u"&&(s.push("crypto"),t.push("react-native-get-random-values"),t.push("crypto-js")),typeof global.TextEncoder>"u"&&(s.push("TextEncoder"),t.push("text-encoding")),typeof global.TextDecoder>"u"&&(s.push("TextDecoder"),t.push("text-encoding")),typeof global.AbortController>"u"&&(s.push("AbortController"),t.push("abortcontroller-polyfill")),typeof global.URL>"u"&&(s.push("URL"),e.push("URL constructor not available")),{compatible:s.length===0,missing:s,warnings:e,polyfillsAvailable:[...new Set(t)]}}function pe(){try{if(typeof global.fetch>"u")try{U("whatwg-fetch"),console.log("\u2713 fetch polyfill loaded");}catch{console.warn("\u26A0\uFE0F whatwg-fetch not installed. Install with: npm install whatwg-fetch");}if(typeof global.crypto>"u")try{let s=U("react-native-get-random-values");typeof global.crypto>"u"&&(global.crypto={getRandomValues:s.getRandomValues}),console.log("\u2713 crypto polyfill loaded");}catch{console.warn("\u26A0\uFE0F react-native-get-random-values not installed. Install with: npm install react-native-get-random-values");}if(typeof global.TextEncoder>"u"||typeof global.TextDecoder>"u")try{let s=U("text-encoding");typeof global.TextEncoder>"u"&&(global.TextEncoder=s.TextEncoder),typeof global.TextDecoder>"u"&&(global.TextDecoder=s.TextDecoder),console.log("\u2713 TextEncoder/TextDecoder polyfill loaded");}catch{console.warn("\u26A0\uFE0F text-encoding not installed. Install with: npm install text-encoding");}if(typeof global.AbortController>"u")try{let s=U("abortcontroller-polyfill/dist/cjs-ponyfill").AbortController;global.AbortController=s,console.log("\u2713 AbortController polyfill loaded");}catch{console.warn("\u26A0\uFE0F abortcontroller-polyfill not installed. Install with: npm install abortcontroller-polyfill");}}catch(s){console.error("Error setting up React Native polyfills:",s);}}function ue(s,e={}){let{MemoryClient:t}=(W(),ae(Z));e.fetch&&(global.fetch=e.fetch),e.WebSocket&&(global.WebSocket=e.WebSocket),e.crypto&&(global.crypto=e.crypto),e.TextEncoder&&(global.TextEncoder=e.TextEncoder),e.TextDecoder&&(global.TextDecoder=e.TextDecoder);let n=k();return n.compatible||console.warn(`Memory Intelligence SDK is not fully compatible with this React Native environment.
|
|
2
|
+
Missing APIs:`,n.missing.join(", ")+`
|
|
3
|
+
Install polyfills:`,n.polyfillsAvailable.join(", ")),n.warnings.length>0&&n.warnings.forEach(r=>console.warn("\u26A0\uFE0F ",r)),new t({apiKey:s,baseUrl:e.baseUrl})}var Q={isReactNative(){return typeof navigator<"u"&&navigator.product==="ReactNative"},getRecommendedPolyfills(){return k().polyfillsAvailable},getInstallCommand(){let s=this.getRecommendedPolyfills();return s.length===0?null:`npm install ${s.join(" ")}`}};function ee(s){if(!(s instanceof Error))return false;let e=s.message.toLowerCase();return e.includes("fetch is not defined")||e.includes("websocket is not defined")||e.includes("crypto is not defined")||e.includes("textencoder is not defined")||e.includes("abortcontroller is not defined")}function de(s){return ee(s)?`
|
|
4
|
+
React Native Polyfill Required
|
|
5
|
+
==============================
|
|
6
|
+
|
|
7
|
+
The Memory Intelligence SDK requires some Web APIs that are not available
|
|
8
|
+
in React Native by default.
|
|
9
|
+
|
|
10
|
+
Missing APIs: ${k().missing.join(", ")}
|
|
11
|
+
|
|
12
|
+
To fix this, install the required polyfills:
|
|
13
|
+
|
|
14
|
+
${Q.getInstallCommand()}
|
|
15
|
+
|
|
16
|
+
Then in your app entry point (App.tsx):
|
|
17
|
+
|
|
18
|
+
import 'react-native-get-random-values'; // Must be first
|
|
19
|
+
import 'whatwg-fetch';
|
|
20
|
+
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
|
|
21
|
+
import { MemoryClient } from '@memoryintelligence/sdk';
|
|
22
|
+
|
|
23
|
+
const client = new MemoryClient({ apiKey: 'your-key' });
|
|
24
|
+
|
|
25
|
+
For more info: https://docs.memoryintelligence.io/sdk/react-native
|
|
26
|
+
`:null}w();var je="2.0.0";export{b as APIError,d as AuthenticationError,m as BaseSubscription,C as ComputeNamespace,x as ComputeSubscription,g as ConfigurationError,T as DriftNamespace,v as DriftSubscription,N as ExplainLevel,A as MemoryClient,O as PIIHandling,$ as ProgressTracker,D as ProvenanceMode,y as RateLimitError,Q as ReactNativeUtils,_ as RetentionPolicy,p as SDKError,M as Scope,K as SearchResultStream,S as UMONamespace,q as UMOStreamProcessor,je as VERSION,f as ValidationError,R as WebSocketManager,k as checkReactNativeCompatibility,ue as createReactNativeClient,de as getPolyfillErrorHelp,ee as isPolyfillError,pe as setupReactNativePolyfills,le as streamLargeDataset};//# sourceMappingURL=index.mjs.map
|
|
27
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/auth.ts","../src/enums.ts","../src/http.ts","../src/websocket.ts","../src/subscriptions/base.ts","../src/subscriptions/drift.ts","../src/subscriptions/compute.ts","../src/subscriptions/index.ts","../src/client.ts","../src/index.ts","../src/streaming.ts","../src/react-native.ts"],"names":["SDKError","ConfigurationError","AuthenticationError","ValidationError","RateLimitError","APIError","init_errors","__esmMin","_SDKError","message","code","_ConfigurationError","_AuthenticationError","_ValidationError","field","_RateLimitError","retryAfter","limit","remaining","_APIError","statusCode","requestId","details","validateApiKey","apiKey","parts","environment","validEnvironments","resolveBaseUrl","providedUrl","DEFAULT_BASE_URL","init_auth","Scope","RetentionPolicy","PIIHandling","ProvenanceMode","ExplainLevel","init_enums","HTTPClient","init_http","config","endpoint","options","url","method","lastError","attempt","response","rateLimit","error","delay","headers","controller","timeoutId","signal","reset","errorData","ms","resolve","WebSocketManager","init_websocket","reject","handler","event","subscriptionId","BaseSubscription","init_base","ws","handlers","index","data","DriftSubscription","init_drift","filters","update","ComputeSubscription","init_compute","functionName","parameters","progress","result","init_subscriptions","client_exports","__export","ComputeNamespace","DriftNamespace","MemoryClient","UMONamespace","init_client","client","http","explicit","content","userUlid","payload","query","params","umoId1","umoId2","umoId","level","items","item","_MemoryClient","baseUrl","wsUrl","UMOStreamProcessor","chunkSize","onProgress","onChunk","concurrency","total","processed","i","chunk","results","promises","batchResults","queries","searchOptions","streamLargeDataset","source","processor","SearchResultStream","pageSize","maxResults","offset","totalRetrieved","ProgressTracker","onUpdate","count","elapsed","rate","eta","checkReactNativeCompatibility","missing","warnings","polyfillsAvailable","setupReactNativePolyfills","getRandomValues","encoding","AbortController","createReactNativeClient","compatibility","warning","ReactNativeUtils","polyfills","isPolyfillError","getPolyfillErrorHelp","VERSION"],"mappings":"usBAAA,IAMaA,CAAAA,CAQAC,EAQAC,CAAAA,CAQAC,CAAAA,CAQAC,EAaAC,CAAAA,CAnDbC,CAAAA,CAAAC,EAAA,IAAA,CAMaP,CAAAA,CAAN,MAAMQ,CAAAA,SAAiB,KAAM,CAClC,WAAA,CAAYC,CAAAA,CAAwBC,EAAe,CACjD,KAAA,CAAMD,CAAO,CAAA,CADqB,IAAA,CAAA,IAAA,CAAAC,EAElC,IAAA,CAAK,IAAA,CAAO,WACZ,MAAA,CAAO,cAAA,CAAe,KAAMF,CAAAA,CAAS,SAAS,EAChD,CACF,CAAA,CAEaP,EAAN,MAAMU,CAAAA,SAA2BX,CAAS,CAC/C,WAAA,CAAYS,EAAiB,CAC3B,KAAA,CAAMA,CAAAA,CAAS,qBAAqB,CAAA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gC,CAErD,CAKO,SAAS2I,EAAAA,CAAqBnG,CAAAA,CAA+B,CAClE,OAAKkG,EAAAA,CAAgBlG,CAAK,CAAA,CAInB;AAAA;AAAA;;AAAA;AAAA;;AAAA,cAAA,EAFeqF,CAAAA,EAA8B,CASxB,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC;;AAAA;;AAAA,EAAA,EAI5CW,CAAAA,CAAiB,mBAAmB;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA,CAAA,CAfF,IA4BtC,CF1MA3I,CAAAA,EAAAA,CAUO,IAAM+I,EAAAA,CAAU","file":"index.mjs","sourcesContent":["/**\n * Error classes for Memory Intelligence SDK\n * \n * All errors extend SDKError for consistency with Python SDK patterns.\n */\n\nexport class SDKError extends Error {\n constructor(message: string, public code?: string) {\n super(message);\n this.name = 'SDKError';\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n\nexport class ConfigurationError extends SDKError {\n constructor(message: string) {\n super(message, 'CONFIGURATION_ERROR');\n this.name = 'ConfigurationError';\n Object.setPrototypeOf(this, ConfigurationError.prototype);\n }\n}\n\nexport class AuthenticationError extends SDKError {\n constructor(message: string) {\n super(message, 'AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\nexport class ValidationError extends SDKError {\n constructor(message: string, public field?: string) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class RateLimitError extends SDKError {\n constructor(\n message: string,\n public retryAfter?: number,\n public limit?: number,\n public remaining?: number\n ) {\n super(message, 'RATE_LIMIT_ERROR');\n this.name = 'RateLimitError';\n Object.setPrototypeOf(this, RateLimitError.prototype);\n }\n}\n\nexport class APIError extends SDKError {\n constructor(\n message: string,\n public statusCode?: number,\n public requestId?: string,\n public details?: unknown\n ) {\n super(message, 'API_ERROR');\n this.name = 'APIError';\n Object.setPrototypeOf(this, APIError.prototype);\n }\n}\n","/**\n * Authentication utilities for Memory Intelligence SDK\n */\n\nimport { AuthenticationError, ConfigurationError } from './errors.js';\n\nconst DEFAULT_BASE_URL = 'https://api.memoryintelligence.io';\n\n/**\n * Validate API key format.\n * Keys should be in format: mi_sk_beta_<secret> or mi_sk_live_<secret>\n */\nexport function validateApiKey(apiKey: string): void {\n if (!apiKey) {\n throw new ConfigurationError('API key is required');\n }\n\n if (typeof apiKey !== 'string') {\n throw new ConfigurationError('API key must be a string');\n }\n\n if (!apiKey.startsWith('mi_sk_')) {\n throw new AuthenticationError(\n 'Invalid API key format. Must start with mi_sk_'\n );\n }\n\n const parts = apiKey.split('_');\n if (parts.length < 4) {\n throw new AuthenticationError(\n 'Invalid API key format. Expected: mi_sk_{env}_{secret}'\n );\n }\n\n const environment = parts[2];\n const validEnvironments = ['beta', 'test', 'live'];\n if (!validEnvironments.includes(environment)) {\n throw new AuthenticationError(\n `Invalid API key environment: ${environment}. Must be one of: ${validEnvironments.join(', ')}`\n );\n }\n}\n\n/**\n * Resolve base URL from environment or use default.\n */\nexport function resolveBaseUrl(providedUrl?: string): string {\n // Explicit URL takes precedence\n if (providedUrl) {\n return providedUrl.replace(/\\/$/, ''); // Remove trailing slash\n }\n\n // Check environment variable\n if (typeof process !== 'undefined' && process.env?.MI_API_URL) {\n return process.env.MI_API_URL.replace(/\\/$/, '');\n }\n\n // Use default\n return DEFAULT_BASE_URL;\n}\n\n/**\n * Extract key prefix (e.g., \"mi_sk_beta\", \"mi_sk_test\", \"mi_sk_live\").\n */\nexport function getKeyPrefix(apiKey: string): string {\n const parts = apiKey.split('_');\n if (parts.length >= 3) {\n return `${parts[0]}_${parts[1]}_${parts[2]}`;\n }\n return apiKey.substring(0, 20); // Fallback for malformed keys\n}\n\n/**\n * Get key environment (beta/test/production).\n */\nexport function getKeyEnvironment(apiKey: string): string {\n const parts = apiKey.split('_');\n const env = parts[2] || 'unknown';\n \n // Map 'live' to 'production' for consistency\n if (env === 'live') {\n return 'production';\n }\n \n return env;\n}\n","/**\n * Enumerations for Memory Intelligence SDK\n * \n * These enums match the Python SDK exactly to ensure API compatibility.\n */\n\n/**\n * Governance scope for memory isolation.\n * Scopes are cryptographic boundaries—data in one scope is\n * technically inaccessible from another.\n */\nexport enum Scope {\n USER = 'user',\n CLIENT = 'client',\n PROJECT = 'project',\n TEAM = 'team',\n ORGANIZATION = 'org',\n ALL = 'all',\n}\n\n/**\n * What to retain after processing.\n * Privacy by design: MEANING_ONLY is the default.\n */\nexport enum RetentionPolicy {\n MEANING_ONLY = 'meaning_only',\n FULL = 'full',\n SUMMARY_ONLY = 'summary_only',\n}\n\n/**\n * How to handle detected PII.\n */\nexport enum PIIHandling {\n DETECT_ONLY = 'detect_only',\n EXTRACT_AND_REDACT = 'extract_and_redact',\n HASH = 'hash',\n REJECT = 'reject',\n}\n\n/**\n * Provenance tracking level.\n */\nexport enum ProvenanceMode {\n STANDARD = 'standard',\n AUTHORSHIP = 'authorship',\n AUDIT = 'audit',\n}\n\n/**\n * Level of explanation to include in responses.\n */\nexport enum ExplainLevel {\n NONE = 'none',\n HUMAN = 'human',\n AUDIT = 'audit',\n FULL = 'full',\n}\n","/**\n * HTTP client for Memory Intelligence SDK\n * \n * Provides fetch wrapper with:\n * - Automatic retries\n * - Rate limit handling\n * - Error mapping\n * - Request ID tracking\n */\n\nimport {\n APIError,\n AuthenticationError,\n RateLimitError,\n ValidationError,\n} from './errors.js';\nimport type { RateLimit, SDKResponse } from './models.js';\n\nexport interface HTTPClientConfig {\n apiKey: string;\n baseUrl: string;\n timeout?: number;\n maxRetries?: number;\n}\n\nexport interface RequestOptions {\n method?: string;\n body?: unknown;\n signal?: AbortSignal;\n headers?: Record<string, string>;\n}\n\n/**\n * HTTP client with retry logic and error handling.\n */\nexport class HTTPClient {\n private apiKey: string;\n private baseUrl: string;\n private timeout: number;\n private maxRetries: number;\n\n constructor(config: HTTPClientConfig) {\n this.apiKey = config.apiKey;\n this.baseUrl = config.baseUrl;\n this.timeout = config.timeout || 30000; // 30s default\n this.maxRetries = config.maxRetries || 3;\n }\n\n /**\n * Make HTTP request with retry logic.\n */\n async request<T>(\n endpoint: string,\n options: RequestOptions = {}\n ): Promise<SDKResponse<T>> {\n const url = `${this.baseUrl}${endpoint}`;\n const method = options.method || 'GET';\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt < this.maxRetries; attempt++) {\n try {\n const response = await this.makeRequest(url, method, options);\n const rateLimit = this.extractRateLimit(response);\n const requestId = response.headers.get('x-request-id') || undefined;\n\n // Handle error responses\n if (!response.ok) {\n await this.handleErrorResponse(response, requestId);\n }\n\n const data = await response.json();\n\n return {\n data: data as T,\n rateLimit,\n requestId,\n };\n } catch (error) {\n lastError = error as Error;\n\n // Don't retry on auth errors or validation errors\n if (\n error instanceof AuthenticationError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n\n // Don't retry on rate limit errors (should wait)\n if (error instanceof RateLimitError) {\n throw error;\n }\n\n // Wait before retry (exponential backoff)\n if (attempt < this.maxRetries - 1) {\n const delay = Math.min(1000 * Math.pow(2, attempt), 10000);\n await this.sleep(delay);\n }\n }\n }\n\n // All retries failed\n throw new APIError(\n `Request failed after ${this.maxRetries} attempts: ${lastError?.message}`,\n undefined,\n undefined,\n lastError\n );\n }\n\n /**\n * Make single HTTP request.\n */\n private async makeRequest(\n url: string,\n method: string,\n options: RequestOptions\n ): Promise<Response> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n 'X-MI-SDK-Version': '2.0.0',\n 'X-MI-SDK-Language': 'typescript',\n ...options.headers,\n };\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Combine user signal with timeout signal\n const signal = options.signal || controller.signal;\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal,\n });\n\n return response;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Extract rate limit information from response headers.\n */\n private extractRateLimit(response: Response): RateLimit | undefined {\n const limit = response.headers.get('x-ratelimit-limit');\n const remaining = response.headers.get('x-ratelimit-remaining');\n const reset = response.headers.get('x-ratelimit-reset');\n\n if (!limit && !remaining && !reset) {\n return undefined;\n }\n\n return {\n limit: limit ? parseInt(limit, 10) : undefined,\n remaining: remaining ? parseInt(remaining, 10) : undefined,\n reset: reset ? parseInt(reset, 10) : undefined,\n };\n }\n\n /**\n * Handle error responses from API.\n */\n private async handleErrorResponse(\n response: Response,\n requestId?: string\n ): Promise<never> {\n const statusCode = response.status;\n let errorData: any;\n\n try {\n errorData = await response.json();\n } catch {\n errorData = { detail: response.statusText };\n }\n\n const message = errorData.detail || errorData.message || 'Unknown error';\n\n // Map status codes to error types\n switch (statusCode) {\n case 401:\n throw new AuthenticationError(message);\n\n case 400:\n throw new ValidationError(message);\n\n case 429: {\n const retryAfter = response.headers.get('retry-after');\n const rateLimit = this.extractRateLimit(response);\n throw new RateLimitError(\n message,\n retryAfter ? parseInt(retryAfter, 10) : undefined,\n rateLimit?.limit,\n rateLimit?.remaining\n );\n }\n\n default:\n throw new APIError(message, statusCode, requestId, errorData);\n }\n }\n\n /**\n * Sleep utility for retry backoff.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * WebSocket connection manager for Memory Intelligence SDK\n * \n * Handles persistent connections, auto-reconnect, and subscription routing.\n */\n\nimport { SDKError } from './errors.js';\n\nexport interface WebSocketConfig {\n url: string;\n apiKey: string;\n orgUlid?: string;\n reconnectDelay?: number;\n maxReconnectAttempts?: number;\n pingInterval?: number;\n}\n\ninterface ResolvedWebSocketConfig {\n url: string;\n apiKey: string;\n orgUlid?: string;\n reconnectDelay: number;\n maxReconnectAttempts: number;\n pingInterval: number;\n}\n\nexport interface SubscriptionMessage {\n type: 'subscribe' | 'unsubscribe';\n subscription_id: string;\n stream: string;\n filters?: Record<string, any>;\n function_name?: string;\n parameters?: Record<string, any>;\n}\n\nexport interface ServerMessage {\n type: string;\n subscription_id?: string;\n [key: string]: any;\n}\n\nexport type MessageHandler = (message: ServerMessage) => void;\n\n/**\n * WebSocket connection manager with auto-reconnect and subscription routing.\n */\nexport class WebSocketManager {\n private ws: WebSocket | null = null;\n private config: ResolvedWebSocketConfig;\n private reconnectAttempts = 0;\n private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;\n private pingIntervalId: ReturnType<typeof setInterval> | null = null;\n private subscriptions = new Map<string, MessageHandler>();\n private connectionPromise: Promise<void> | null = null;\n private isConnecting = false;\n private isClosed = false;\n\n // Event handlers\n private onConnectHandlers: Array<() => void> = [];\n private onDisconnectHandlers: Array<() => void> = [];\n private onErrorHandlers: Array<(error: Error) => void> = [];\n\n constructor(config: WebSocketConfig) {\n this.config = {\n url: config.url,\n apiKey: config.apiKey,\n orgUlid: config.orgUlid,\n reconnectDelay: config.reconnectDelay || 1000,\n maxReconnectAttempts: config.maxReconnectAttempts || 5,\n pingInterval: config.pingInterval || 30000,\n };\n }\n\n /**\n * Connect to WebSocket server.\n */\n async connect(): Promise<void> {\n if (this.ws?.readyState === WebSocket.OPEN) {\n return Promise.resolve();\n }\n\n if (this.isConnecting && this.connectionPromise) {\n return this.connectionPromise;\n }\n\n this.isConnecting = true;\n this.connectionPromise = new Promise((resolve, reject) => {\n try {\n // Build WebSocket URL with auth\n const url = new URL(this.config.url);\n url.searchParams.append('api_key', this.config.apiKey);\n if (this.config.orgUlid) {\n url.searchParams.append('org_ulid', this.config.orgUlid);\n }\n\n this.ws = new WebSocket(url.toString());\n\n this.ws.onopen = () => {\n this.isConnecting = false;\n this.reconnectAttempts = 0;\n this.startPingInterval();\n this.onConnectHandlers.forEach((handler) => handler());\n resolve();\n };\n\n this.ws.onmessage = (event) => {\n try {\n const message: ServerMessage = JSON.parse(event.data);\n this.handleMessage(message);\n } catch (error) {\n console.error('Failed to parse WebSocket message:', error);\n }\n };\n\n this.ws.onerror = () => {\n const error = new SDKError('WebSocket connection error');\n this.onErrorHandlers.forEach((handler) => handler(error));\n \n if (this.isConnecting) {\n this.isConnecting = false;\n reject(error);\n }\n };\n\n this.ws.onclose = () => {\n this.stopPingInterval();\n this.onDisconnectHandlers.forEach((handler) => handler());\n\n if (!this.isClosed) {\n this.attemptReconnect();\n }\n };\n } catch (error) {\n this.isConnecting = false;\n reject(error instanceof Error ? error : new SDKError('Failed to connect'));\n }\n });\n\n return this.connectionPromise;\n }\n\n /**\n * Disconnect from WebSocket server.\n */\n disconnect(): void {\n this.isClosed = true;\n this.stopPingInterval();\n \n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n\n this.subscriptions.clear();\n }\n\n /**\n * Subscribe to a stream.\n */\n async subscribe(message: SubscriptionMessage, handler: MessageHandler): Promise<void> {\n await this.connect();\n\n this.subscriptions.set(message.subscription_id, handler);\n this.send(message);\n }\n\n /**\n * Unsubscribe from a stream.\n */\n unsubscribe(subscriptionId: string): void {\n this.subscriptions.delete(subscriptionId);\n \n if (this.ws?.readyState === WebSocket.OPEN) {\n this.send({\n type: 'unsubscribe',\n subscription_id: subscriptionId,\n stream: '', // Required by API but not used for unsubscribe\n });\n }\n }\n\n /**\n * Register connect event handler.\n */\n onConnect(handler: () => void): void {\n this.onConnectHandlers.push(handler);\n }\n\n /**\n * Register disconnect event handler.\n */\n onDisconnect(handler: () => void): void {\n this.onDisconnectHandlers.push(handler);\n }\n\n /**\n * Register error event handler.\n */\n onError(handler: (error: Error) => void): void {\n this.onErrorHandlers.push(handler);\n }\n\n /**\n * Check if connected.\n */\n isConnected(): boolean {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n /**\n * Send message to server.\n */\n private send(message: any): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new SDKError('WebSocket not connected');\n }\n\n this.ws.send(JSON.stringify(message));\n }\n\n /**\n * Handle incoming message from server.\n */\n private handleMessage(message: ServerMessage): void {\n // Handle pong\n if (message.type === 'pong') {\n return;\n }\n\n // Route to subscription handler\n if (message.subscription_id) {\n const handler = this.subscriptions.get(message.subscription_id);\n if (handler) {\n handler(message);\n }\n }\n }\n\n /**\n * Start ping interval to keep connection alive.\n */\n private startPingInterval(): void {\n this.stopPingInterval();\n \n this.pingIntervalId = setInterval(() => {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.send({ type: 'ping' });\n }\n }, this.config.pingInterval);\n }\n\n /**\n * Stop ping interval.\n */\n private stopPingInterval(): void {\n if (this.pingIntervalId) {\n clearInterval(this.pingIntervalId);\n this.pingIntervalId = null;\n }\n }\n\n /**\n * Attempt to reconnect with exponential backoff.\n */\n private attemptReconnect(): void {\n if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {\n const error = new SDKError(\n `Failed to reconnect after ${this.config.maxReconnectAttempts} attempts`\n );\n this.onErrorHandlers.forEach((handler) => handler(error));\n return;\n }\n\n const delay = this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts);\n this.reconnectAttempts++;\n\n this.reconnectTimeout = setTimeout(() => {\n this.connect().catch((error) => {\n console.error('Reconnect failed:', error);\n });\n }, delay);\n }\n}\n","/**\n * Base subscription class for all WebSocket subscriptions.\n */\n\nimport type { WebSocketManager, ServerMessage } from '../websocket.js';\n\nexport type EventHandler<T = any> = (data: T) => void;\n\n/**\n * Base class for WebSocket subscriptions.\n */\nexport abstract class BaseSubscription<T = any> {\n protected subscriptionId: string;\n protected ws: WebSocketManager;\n protected eventHandlers = new Map<string, EventHandler<T>[]>();\n protected isActive = false;\n\n constructor(ws: WebSocketManager) {\n this.ws = ws;\n this.subscriptionId = this.generateSubscriptionId();\n }\n\n /**\n * Start the subscription.\n */\n abstract start(): Promise<void>;\n\n /**\n * Stop the subscription.\n */\n stop(): void {\n if (this.isActive) {\n this.ws.unsubscribe(this.subscriptionId);\n this.isActive = false;\n this.emit('disconnected', null as any);\n }\n }\n\n /**\n * Register an event handler.\n */\n on(event: string, handler: EventHandler<T>): this {\n if (!this.eventHandlers.has(event)) {\n this.eventHandlers.set(event, []);\n }\n this.eventHandlers.get(event)!.push(handler);\n return this;\n }\n\n /**\n * Remove an event handler.\n */\n off(event: string, handler: EventHandler<T>): this {\n const handlers = this.eventHandlers.get(event);\n if (handlers) {\n const index = handlers.indexOf(handler);\n if (index !== -1) {\n handlers.splice(index, 1);\n }\n }\n return this;\n }\n\n /**\n * Emit an event to all registered handlers.\n */\n protected emit(event: string, data: T): void {\n const handlers = this.eventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n console.error(`Error in ${event} handler:`, error);\n }\n });\n }\n }\n\n /**\n * Handle incoming message from server.\n */\n protected abstract handleMessage(message: ServerMessage): void;\n\n /**\n * Generate unique subscription ID.\n */\n protected generateSubscriptionId(): string {\n return `sub_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n }\n\n /**\n * Check if subscription is active.\n */\n isSubscribed(): boolean {\n return this.isActive;\n }\n}\n","/**\n * Drift subscription for real-time entity meaning change notifications.\n */\n\nimport { BaseSubscription } from './base.js';\nimport type { WebSocketManager, ServerMessage } from '../websocket.js';\n\nexport interface DriftUpdate {\n entityUlid: string;\n canonicalName: string;\n driftEpoch: number;\n driftMagnitude: number;\n meaningStable: boolean;\n updatedAt: string;\n explainHuman: {\n driftSummary: string;\n whatChanged: {\n summary: string;\n changes: string[];\n };\n impactOnResults: string;\n confidenceAssessment: string;\n };\n signals: Array<{\n signal: string;\n magnitude: number;\n isAnomalous: boolean;\n }>;\n}\n\nexport interface DriftSubscriptionOptions {\n entityUlids?: string[];\n orgUlid?: string;\n}\n\n/**\n * Subscription for drift updates on entities.\n * \n * Events:\n * - 'update': (update: DriftUpdate) => void - New drift update received\n * - 'connected': () => void - Subscription established\n * - 'disconnected': () => void - Subscription closed\n * - 'error': (error: Error) => void - Error occurred\n */\nexport class DriftSubscription extends BaseSubscription<DriftUpdate> {\n private options: DriftSubscriptionOptions;\n\n constructor(ws: WebSocketManager, options: DriftSubscriptionOptions = {}) {\n super(ws);\n this.options = options;\n }\n\n /**\n * Start the drift subscription.\n */\n async start(): Promise<void> {\n const filters: Record<string, any> = {};\n \n if (this.options.entityUlids) {\n filters.entity_ulids = this.options.entityUlids;\n }\n \n if (this.options.orgUlid) {\n filters.org_ulid = this.options.orgUlid;\n }\n\n await this.ws.subscribe(\n {\n type: 'subscribe',\n subscription_id: this.subscriptionId,\n stream: 'drift_updates',\n filters,\n },\n (message) => this.handleMessage(message)\n );\n\n this.isActive = true;\n }\n\n /**\n * Handle incoming drift update message.\n */\n protected handleMessage(message: ServerMessage): void {\n switch (message.type) {\n case 'subscribed':\n this.emit('connected', undefined as any);\n break;\n\n case 'drift_update':\n const update: DriftUpdate = {\n entityUlid: message.entity_ulid,\n canonicalName: message.canonical_name,\n driftEpoch: message.drift_epoch,\n driftMagnitude: message.drift_magnitude,\n meaningStable: message.meaning_stable,\n updatedAt: message.updated_at,\n explainHuman: {\n driftSummary: message.explain_human.drift_summary,\n whatChanged: {\n summary: message.explain_human.what_changed.summary,\n changes: message.explain_human.what_changed.changes,\n },\n impactOnResults: message.explain_human.impact_on_results,\n confidenceAssessment: message.explain_human.confidence_assessment,\n },\n signals: message.signals || [],\n };\n this.emit('update', update);\n break;\n\n case 'error':\n this.emit('error', new Error(message.message || 'Subscription error') as any);\n break;\n }\n }\n}\n","/**\n * Compute subscription for long-running operation progress and results.\n */\n\nimport { BaseSubscription } from './base.js';\nimport type { WebSocketManager, ServerMessage } from '../websocket.js';\n\nexport interface ComputeProgress {\n status: 'analyzing' | 'processing' | 'finalizing';\n progressPercent: number;\n message: string;\n}\n\nexport interface ComputeResult<T = any> {\n status: 'complete' | 'failed';\n result?: T;\n error?: string;\n executionTimeMs: number;\n explainHuman?: {\n summary: string;\n [key: string]: any;\n };\n}\n\nexport type ComputeUpdate<T = any> = ComputeProgress | ComputeResult<T>;\n\n/**\n * Subscription for long-running compute operations.\n * \n * Events:\n * - 'progress': (progress: ComputeProgress) => void - Progress update\n * - 'result': (result: ComputeResult) => void - Final result\n * - 'connected': () => void - Subscription established\n * - 'disconnected': () => void - Subscription closed\n * - 'error': (error: Error) => void - Error occurred\n */\nexport class ComputeSubscription<T = any> extends BaseSubscription<ComputeUpdate<T>> {\n private functionName: string;\n private parameters: Record<string, any>;\n\n constructor(\n ws: WebSocketManager,\n functionName: string,\n parameters: Record<string, any> = {}\n ) {\n super(ws);\n this.functionName = functionName;\n this.parameters = parameters;\n }\n\n /**\n * Start the compute subscription.\n */\n async start(): Promise<void> {\n await this.ws.subscribe(\n {\n type: 'subscribe',\n subscription_id: this.subscriptionId,\n stream: 'compute_result',\n function_name: this.functionName,\n parameters: this.parameters,\n },\n (message) => this.handleMessage(message)\n );\n\n this.isActive = true;\n }\n\n /**\n * Handle incoming compute message.\n */\n protected handleMessage(message: ServerMessage): void {\n switch (message.type) {\n case 'subscribed':\n this.emit('connected', undefined as any);\n break;\n\n case 'compute_progress':\n const progress: ComputeProgress = {\n status: message.status,\n progressPercent: message.progress_percent,\n message: message.message,\n };\n this.emit('progress', progress as any);\n break;\n\n case 'compute_result':\n const result: ComputeResult<T> = {\n status: message.status,\n result: message.result,\n error: message.error,\n executionTimeMs: message.execution_time_ms,\n explainHuman: message.explain_human,\n };\n this.emit('result', result as any);\n \n // Auto-unsubscribe after result\n this.stop();\n break;\n\n case 'error':\n this.emit('error', new Error(message.message || 'Compute error') as any);\n break;\n }\n }\n}\n","/**\n * Subscription exports for WebSocket streaming.\n */\n\nexport { BaseSubscription } from './base.js';\nexport { DriftSubscription } from './drift.js';\nexport { ComputeSubscription } from './compute.js';\n\nexport type { EventHandler } from './base.js';\nexport type { DriftUpdate, DriftSubscriptionOptions } from './drift.js';\nexport type { ComputeProgress, ComputeResult, ComputeUpdate } from './compute.js';\n","/**\n * Main client for Memory Intelligence SDK\n * \n * Provides the MemoryClient class and UMONamespace for all memory operations.\n */\n\nimport { validateApiKey, resolveBaseUrl } from './auth.js';\nimport {\n ExplainLevel,\n PIIHandling,\n ProvenanceMode,\n RetentionPolicy,\n Scope,\n} from './enums.js';\nimport { HTTPClient } from './http.js';\nimport { WebSocketManager } from './websocket.js';\nimport {\n DriftSubscription,\n ComputeSubscription,\n type DriftSubscriptionOptions,\n} from './subscriptions/index.js';\nimport type {\n BatchResult,\n DeleteResult,\n Explanation,\n MatchResult,\n MeaningObject,\n SearchResponse,\n} from './models.js';\n\nexport interface MemoryClientConfig {\n apiKey: string;\n baseUrl?: string;\n wsUrl?: string;\n userUlid?: string;\n orgUlid?: string;\n timeout?: number;\n maxRetries?: number;\n}\n\n/**\n * UMO Namespace - All memory operations under `mi.umo.*`\n */\nexport class UMONamespace {\n constructor(private client: MemoryClient, private http: HTTPClient) {}\n\n /**\n * Resolve user_ulid from explicit argument or client default.\n */\n private resolveUserUlid(explicit?: string): string | undefined {\n return explicit || this.client.userUlid;\n }\n\n /**\n * Process content into a Meaning Object.\n * \n * @param content - Raw text content to process\n * @param options - Processing options\n * @returns Meaning Object with entities, topics, embedding\n */\n async process(\n content: string,\n options: {\n userUlid?: string;\n retentionPolicy?: RetentionPolicy;\n piiHandling?: PIIHandling;\n provenanceMode?: ProvenanceMode;\n scope?: Scope;\n scopeId?: string;\n source?: string;\n metadata?: Record<string, unknown>;\n } = {}\n ): Promise<MeaningObject> {\n const userUlid = this.resolveUserUlid(options.userUlid);\n\n const payload = {\n content,\n user_ulid: userUlid,\n org_ulid: this.client.orgUlid,\n retention_policy: options.retentionPolicy || RetentionPolicy.MEANING_ONLY,\n pii_handling: options.piiHandling || PIIHandling.EXTRACT_AND_REDACT,\n provenance_mode: options.provenanceMode || ProvenanceMode.STANDARD,\n scope: options.scope || Scope.USER,\n scope_id: options.scopeId,\n source: options.source || 'api',\n metadata: options.metadata || {},\n };\n\n const response = await this.http.request<MeaningObject>('/v1/process', {\n method: 'POST',\n body: payload,\n });\n\n return response.data;\n }\n\n /**\n * Search memories semantically.\n * \n * @param query - Natural language query\n * @param options - Search options\n * @returns Search results with relevance scores\n */\n async search(\n query: string,\n options: {\n userUlid?: string;\n limit?: number;\n scope?: Scope;\n scopeId?: string;\n explain?: ExplainLevel;\n } = {}\n ): Promise<SearchResponse> {\n const userUlid = this.resolveUserUlid(options.userUlid);\n\n const params = new URLSearchParams();\n params.append('q', query);\n if (userUlid) params.append('user_ulid', userUlid);\n if (options.limit) params.append('limit', options.limit.toString());\n if (options.scope) params.append('scope', options.scope);\n if (options.scopeId) params.append('scope_id', options.scopeId);\n if (options.explain) params.append('explain', options.explain);\n\n const response = await this.http.request<SearchResponse>(\n `/v1/search?${params.toString()}`\n );\n\n return response.data;\n }\n\n /**\n * Match two memories for relevance.\n * \n * @param umoId1 - First meaning object ID\n * @param umoId2 - Second meaning object ID\n * @param options - Match options\n * @returns Match score and breakdown\n */\n async match(\n umoId1: string,\n umoId2: string,\n options: {\n explain?: ExplainLevel;\n } = {}\n ): Promise<MatchResult> {\n const payload = {\n umo_id_1: umoId1,\n umo_id_2: umoId2,\n explain: options.explain || ExplainLevel.NONE,\n };\n\n const response = await this.http.request<MatchResult>('/v1/match', {\n method: 'POST',\n body: payload,\n });\n\n return response.data;\n }\n\n /**\n * Get explanation for a memory.\n * \n * @param umoId - Meaning object ID\n * @param level - Explanation detail level\n * @returns Explanation with human and/or audit details\n */\n async explain(\n umoId: string,\n level: ExplainLevel = ExplainLevel.FULL\n ): Promise<Explanation> {\n const response = await this.http.request<Explanation>(\n `/v1/explain/${umoId}?level=${level}`\n );\n\n return response.data;\n }\n\n /**\n * Delete memories.\n * \n * @param options - Deletion options\n * @returns Number of memories deleted\n */\n async delete(\n options: {\n umoId?: string;\n userUlid?: string;\n scope?: Scope;\n } = {}\n ): Promise<DeleteResult> {\n const userUlid = this.resolveUserUlid(options.userUlid);\n\n const payload: any = {};\n if (options.umoId) payload.umo_id = options.umoId;\n if (userUlid) payload.user_ulid = userUlid;\n if (options.scope) payload.scope = options.scope;\n\n const response = await this.http.request<DeleteResult>('/v1/delete', {\n method: 'DELETE',\n body: payload,\n });\n\n return response.data;\n }\n\n /**\n * Batch process multiple items.\n * \n * @param items - Array of items to process\n * @returns Batch results with success/failure per item\n */\n async batch(\n items: Array<{\n content: string;\n userUlid?: string;\n metadata?: Record<string, unknown>;\n }>\n ): Promise<BatchResult> {\n const payload = {\n items: items.map((item) => ({\n content: item.content,\n user_ulid: this.resolveUserUlid(item.userUlid),\n metadata: item.metadata || {},\n })),\n };\n\n const response = await this.http.request<BatchResult>('/v1/batch', {\n method: 'POST',\n body: payload,\n });\n\n return response.data;\n }\n}\n\n/**\n * Drift Namespace - Real-time entity meaning change subscriptions\n */\nexport class DriftNamespace {\n constructor(private ws: WebSocketManager) {}\n\n /**\n * Watch for drift updates on specific entities.\n * \n * @param options - Subscription options (entity ULIDs, org filter)\n * @returns DriftSubscription instance\n * \n * @example\n * ```typescript\n * const subscription = mi.drift.watch({\n * entityUlids: ['01ARZ3NDEV5ARZ3ND']\n * });\n * \n * subscription.on('update', (update) => {\n * if (!update.meaningStable) {\n * console.log('Meaning changed:', update.explainHuman.driftSummary);\n * }\n * });\n * \n * await subscription.start();\n * ```\n */\n watch(options: DriftSubscriptionOptions = {}): DriftSubscription {\n return new DriftSubscription(this.ws, options);\n }\n}\n\n/**\n * Compute Namespace - Long-running operation progress tracking\n */\nexport class ComputeNamespace {\n constructor(private ws: WebSocketManager) {}\n\n /**\n * Watch progress of a long-running compute operation.\n * \n * @param functionName - Name of compute function\n * @param parameters - Function parameters\n * @returns ComputeSubscription instance\n * \n * Disconnect WebSocket connections.\n * Call this when shutting down the client.\n */\n disconnect(): void {\n this.ws.disconnect();\n }\n\n /**\n * @example\n * ```typescript\n * const subscription = mi.compute.watch('analyze_decision_process', {\n * narrative_ulid: '01ARZ3NDFQ69G5FAVSV4RRFF'\n * });\n * \n * subscription.on('progress', (progress) => {\n * console.log(`${progress.progressPercent}%: ${progress.message}`);\n * });\n * \n * subscription.on('result', (result) => {\n * console.log('Complete:', result.result);\n * });\n * \n * await subscription.start();\n * ```\n */\n watch<T = any>(\n functionName: string,\n parameters: Record<string, any> = {}\n ): ComputeSubscription<T> {\n return new ComputeSubscription<T>(this.ws, functionName, parameters);\n }\n}\n\n/**\n * Main Memory Intelligence Client\n * \n * Usage:\n * ```typescript\n * const mi = new MemoryClient({ apiKey: 'mi_sk_beta_...' });\n * \n * // Search\n * const results = await mi.umo.search('project planning');\n * \n * // Process\n * const umo = await mi.umo.process('Important meeting notes');\n * \n * // Watch drift\n * const driftSub = mi.drift.watch({ entityUlids: ['01ARZ...'] });\n * await driftSub.start();\n * ```\n */\nexport class MemoryClient {\n public readonly userUlid?: string;\n public readonly orgUlid?: string;\n public readonly umo: UMONamespace;\n public readonly drift: DriftNamespace;\n public readonly compute: ComputeNamespace;\n\n private http: HTTPClient;\n private ws: WebSocketManager;\n\n constructor(config: MemoryClientConfig) {\n // Validate API key\n validateApiKey(config.apiKey);\n\n // Resolve base URL\n const baseUrl = resolveBaseUrl(config.baseUrl);\n\n // Resolve WebSocket URL\n const wsUrl = config.wsUrl || baseUrl.replace(/^http/, 'ws') + '/v1/ws';\n\n // Store config\n this.userUlid = config.userUlid;\n this.orgUlid = config.orgUlid;\n\n // Initialize HTTP client\n this.http = new HTTPClient({\n apiKey: config.apiKey,\n baseUrl,\n timeout: config.timeout,\n maxRetries: config.maxRetries,\n });\n\n // Initialize WebSocket manager\n this.ws = new WebSocketManager({\n url: wsUrl,\n apiKey: config.apiKey,\n orgUlid: config.orgUlid,\n });\n\n // Initialize namespaces\n this.umo = new UMONamespace(this, this.http);\n this.drift = new DriftNamespace(this.ws);\n this.compute = new ComputeNamespace(this.ws);\n }\n\n /**\n * Create a new client instance with a different user context.\n * Useful for multi-user scenarios.\n * \n * @param userUlid - User ULID for the new context\n * @returns New MemoryClient instance\n */\n forUser(userUlid: string): MemoryClient {\n return new MemoryClient({\n apiKey: (this.http as any).apiKey, // Access private apiKey\n baseUrl: (this.http as any).baseUrl,\n userUlid,\n orgUlid: this.orgUlid,\n timeout: (this.http as any).timeout,\n maxRetries: (this.http as any).maxRetries,\n });\n }\n\n /**\n * Convenience alias for process (Batch 4.2)\n */\n async capture(content: string, userUlid?: string): Promise<MeaningObject> {\n return this.umo.process(content, { userUlid });\n }\n\n /**\n * Convenience alias for search (Batch 4.2)\n */\n async search(query: string, limit?: number): Promise<SearchResponse> {\n return this.umo.search(query, { limit });\n }\n\n /**\n * Convenience alias for explain (Batch 4.2)\n */\n async explain(umoId: string): Promise<Explanation> {\n return this.umo.explain(umoId);\n }\n\n /**\n * Convenience alias for delete (Batch 4.2)\n */\n async forget(umoId: string): Promise<DeleteResult> {\n return this.umo.delete({ umoId });\n }\n}\n","/**\n * Memory Intelligence JavaScript/TypeScript SDK\n * \n * Official SDK for building web apps, Node.js services, and edge functions\n * powered by Memory Intelligence.\n * \n * @packageDocumentation\n */\n\n// Main client\nexport { MemoryClient, UMONamespace, DriftNamespace, ComputeNamespace } from './client.js';\nexport type { MemoryClientConfig } from './client.js';\n\n// WebSocket\nexport { WebSocketManager } from './websocket.js';\nexport type { WebSocketConfig, SubscriptionMessage, ServerMessage } from './websocket.js';\n\n// Subscriptions\nexport {\n BaseSubscription,\n DriftSubscription,\n ComputeSubscription,\n} from './subscriptions/index.js';\nexport type {\n EventHandler,\n DriftUpdate,\n DriftSubscriptionOptions,\n ComputeProgress,\n ComputeResult,\n ComputeUpdate,\n} from './subscriptions/index.js';\n\n// Enums\nexport {\n Scope,\n RetentionPolicy,\n PIIHandling,\n ProvenanceMode,\n ExplainLevel,\n} from './enums.js';\n\n// Types\nexport type {\n Entity,\n Topic,\n Embedding,\n Provenance,\n MeaningObject,\n SearchResult,\n SearchResponse,\n MatchResult,\n Explanation,\n DeleteResult,\n BatchItemResult,\n BatchResult,\n RateLimit,\n SDKResponse,\n} from './models.js';\n\n// Streaming utilities\nexport {\n UMOStreamProcessor,\n SearchResultStream,\n ProgressTracker,\n streamLargeDataset,\n} from './streaming.js';\nexport type {\n StreamConfig,\n BatchProcessOptions,\n BatchSearchOptions,\n StreamIteratorOptions,\n ProgressUpdate,\n} from './streaming.js';\n\n// React Native compatibility\nexport {\n checkReactNativeCompatibility,\n setupReactNativePolyfills,\n createReactNativeClient,\n ReactNativeUtils,\n isPolyfillError,\n getPolyfillErrorHelp,\n} from './react-native.js';\nexport type {\n CompatibilityCheck,\n ReactNativeConfig,\n} from './react-native.js';\n\n// Errors\nexport {\n SDKError,\n ConfigurationError,\n AuthenticationError,\n ValidationError,\n RateLimitError,\n APIError,\n} from './errors.js';\n\n// Version\nexport const VERSION = '2.0.0';\n","/**\n * Streaming utilities for handling large datasets\n * \n * Provides:\n * - Chunked response processing\n * - Batch UMO processing\n * - Memory-efficient iteration\n * - Progress tracking\n */\n\nimport type { MeaningObject, SearchResult } from './models.js';\nimport type { MemoryClient } from './client.js';\n\nexport interface StreamConfig {\n /** Chunk size for batch operations */\n chunkSize?: number;\n /** Callback for progress updates */\n onProgress?: (processed: number, total: number) => void;\n /** Callback for chunk completion */\n onChunk?: (chunk: any[], chunkIndex: number) => void;\n /** Maximum concurrent operations */\n concurrency?: number;\n}\n\nexport interface BatchProcessOptions {\n /** Content items to process */\n items: Array<{ content: string; type?: string; metadata?: Record<string, any> }>;\n /** Streaming configuration */\n config?: StreamConfig;\n}\n\nexport interface BatchSearchOptions {\n /** Search queries to execute */\n queries: string[];\n /** Search options for each query */\n searchOptions?: {\n limit?: number;\n filters?: Record<string, any>;\n };\n /** Streaming configuration */\n config?: StreamConfig;\n}\n\nexport interface StreamIteratorOptions<T> {\n /** Data source (array or async generator) */\n source: T[] | AsyncGenerator<T>;\n /** Chunk size for processing */\n chunkSize: number;\n /** Processing function for each chunk */\n processor: (chunk: T[]) => Promise<void>;\n /** Progress callback */\n onProgress?: (processed: number) => void;\n}\n\n/**\n * Streaming helper for batch UMO processing\n */\nexport class UMOStreamProcessor {\n private client: MemoryClient;\n\n constructor(client: MemoryClient) {\n this.client = client;\n }\n\n /**\n * Process multiple content items in batches\n * to avoid overwhelming the API or memory.\n */\n async *processBatch(\n options: BatchProcessOptions\n ): AsyncGenerator<MeaningObject, void, unknown> {\n const { items, config = {} } = options;\n const { chunkSize = 10, onProgress, onChunk, concurrency = 3 } = config;\n\n const total = items.length;\n let processed = 0;\n\n // Process in chunks\n for (let i = 0; i < items.length; i += chunkSize) {\n const chunk = items.slice(i, i + chunkSize);\n \n // Process chunk with controlled concurrency\n const results = await this.processChunk(chunk, concurrency);\n \n processed += chunk.length;\n \n if (onProgress) {\n onProgress(processed, total);\n }\n\n if (onChunk) {\n onChunk(results, Math.floor(i / chunkSize));\n }\n\n // Yield each result\n for (const result of results) {\n yield result;\n }\n\n // Small delay to avoid rate limiting\n if (i + chunkSize < items.length) {\n await this.sleep(100);\n }\n }\n }\n\n /**\n * Process a chunk of items with concurrency control\n */\n private async processChunk(\n items: Array<{ content: string; type?: string; metadata?: Record<string, any> }>,\n concurrency: number\n ): Promise<MeaningObject[]> {\n const results: MeaningObject[] = [];\n \n // Process with concurrency limit\n for (let i = 0; i < items.length; i += concurrency) {\n const batch = items.slice(i, i + concurrency);\n const promises = batch.map(item =>\n this.client.umo.process(item.content, {\n source: item.type || 'text/plain',\n metadata: item.metadata,\n })\n );\n\n const batchResults = await Promise.all(promises);\n results.push(...batchResults);\n }\n\n return results;\n }\n\n /**\n * Execute multiple search queries in sequence\n */\n async *searchBatch(\n options: BatchSearchOptions\n ): AsyncGenerator<{ query: string; results: SearchResult[] }, void, unknown> {\n const { queries, searchOptions = {}, config = {} } = options;\n const { onProgress } = config;\n\n const total = queries.length;\n\n for (let i = 0; i < queries.length; i++) {\n const query = queries[i];\n \n const response = await this.client.umo.search(query, {\n limit: searchOptions.limit || 10,\n });\n\n if (onProgress) {\n onProgress(i + 1, total);\n }\n\n yield {\n query,\n results: response.results,\n };\n\n // Rate limit protection\n if (i < queries.length - 1) {\n await this.sleep(50);\n }\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Generic streaming iterator for large datasets\n */\nexport async function* streamLargeDataset<T>(\n options: StreamIteratorOptions<T>\n): AsyncGenerator<T[], void, unknown> {\n const { source, chunkSize, processor, onProgress } = options;\n let chunk: T[] = [];\n let processed = 0;\n\n if (Array.isArray(source)) {\n // Handle array source\n for (let i = 0; i < source.length; i++) {\n chunk.push(source[i]);\n\n if (chunk.length >= chunkSize || i === source.length - 1) {\n await processor(chunk);\n yield chunk;\n \n processed += chunk.length;\n if (onProgress) {\n onProgress(processed);\n }\n\n chunk = [];\n }\n }\n } else {\n // Handle async generator source\n for await (const item of source) {\n chunk.push(item);\n\n if (chunk.length >= chunkSize) {\n await processor(chunk);\n yield chunk;\n \n processed += chunk.length;\n if (onProgress) {\n onProgress(processed);\n }\n\n chunk = [];\n }\n }\n\n // Process remaining items\n if (chunk.length > 0) {\n await processor(chunk);\n yield chunk;\n \n processed += chunk.length;\n if (onProgress) {\n onProgress(processed);\n }\n }\n }\n}\n\n/**\n * Helper for processing search results in streaming fashion\n */\nexport class SearchResultStream {\n private client: MemoryClient;\n\n constructor(client: MemoryClient) {\n this.client = client;\n }\n\n /**\n * Stream search results with pagination\n */\n async *paginate(\n query: string,\n options: {\n pageSize?: number;\n maxResults?: number;\n filters?: Record<string, any>;\n } = {}\n ): AsyncGenerator<SearchResult[], void, unknown> {\n const { pageSize = 20, maxResults = 100 } = options;\n \n let offset = 0;\n let totalRetrieved = 0;\n\n while (totalRetrieved < maxResults) {\n const limit = Math.min(pageSize, maxResults - totalRetrieved);\n \n // Note: The search method doesn't support offset currently\n // This is a placeholder for when pagination is fully supported\n const response = await this.client.umo.search(query, {\n limit,\n });\n\n const results = response.results;\n \n if (results.length === 0) {\n break; // No more results\n }\n\n yield results;\n \n totalRetrieved += results.length;\n offset += results.length;\n\n // If we got fewer results than requested, we've reached the end\n if (results.length < limit) {\n break;\n }\n }\n }\n}\n\n/**\n * Progress tracker for streaming operations\n */\nexport class ProgressTracker {\n private total: number;\n private processed: number = 0;\n private startTime: number;\n private onUpdate?: (progress: ProgressUpdate) => void;\n\n constructor(total: number, onUpdate?: (progress: ProgressUpdate) => void) {\n this.total = total;\n this.startTime = Date.now();\n this.onUpdate = onUpdate;\n }\n\n update(count: number = 1): void {\n this.processed += count;\n \n if (this.onUpdate) {\n this.onUpdate(this.getProgress());\n }\n }\n\n getProgress(): ProgressUpdate {\n const elapsed = Date.now() - this.startTime;\n const rate = this.processed / (elapsed / 1000); // items/second\n const remaining = this.total - this.processed;\n const eta = remaining / rate;\n\n return {\n processed: this.processed,\n total: this.total,\n percentage: (this.processed / this.total) * 100,\n elapsed,\n rate,\n eta: isFinite(eta) ? eta : undefined,\n };\n }\n}\n\nexport interface ProgressUpdate {\n processed: number;\n total: number;\n percentage: number;\n elapsed: number; // milliseconds\n rate: number; // items per second\n eta?: number; // estimated seconds remaining\n}\n","/**\n * React Native Compatibility Layer\n * \n * Ensures the SDK works correctly in React Native environments\n * by detecting and polyfilling missing APIs.\n * \n * Usage:\n * ```typescript\n * import { checkReactNativeCompatibility, setupReactNativePolyfills } from '@memoryintelligence/sdk/react-native';\n * \n * // In your app entry point (App.tsx)\n * const compatibility = checkReactNativeCompatibility();\n * if (!compatibility.compatible) {\n * console.warn('Missing APIs:', compatibility.missing);\n * setupReactNativePolyfills(); // Auto-install available polyfills\n * }\n * ```\n */\n\nexport interface CompatibilityCheck {\n compatible: boolean;\n missing: string[];\n warnings: string[];\n polyfillsAvailable: string[];\n}\n\nexport interface ReactNativeConfig {\n /** Custom fetch implementation */\n fetch?: typeof fetch;\n /** Custom WebSocket implementation */\n WebSocket?: typeof WebSocket;\n /** Custom crypto implementation */\n crypto?: any; // Use 'any' for React Native crypto polyfills\n /** Custom Text encoder implementation */\n TextEncoder?: typeof TextEncoder;\n /** Custom Text decoder implementation */\n TextDecoder?: typeof TextDecoder;\n}\n\n/**\n * Check if the current environment is React Native compatible\n */\nexport function checkReactNativeCompatibility(): CompatibilityCheck {\n const missing: string[] = [];\n const warnings: string[] = [];\n const polyfillsAvailable: string[] = [];\n\n // Check for fetch\n if (typeof global.fetch === 'undefined') {\n missing.push('fetch');\n polyfillsAvailable.push('whatwg-fetch');\n }\n\n // Check for WebSocket\n if (typeof global.WebSocket === 'undefined') {\n missing.push('WebSocket');\n warnings.push('WebSocket not available - drift/compute subscriptions will not work');\n }\n\n // Check for crypto (needed for hash verification)\n if (typeof global.crypto === 'undefined') {\n missing.push('crypto');\n polyfillsAvailable.push('react-native-get-random-values');\n polyfillsAvailable.push('crypto-js');\n }\n\n // Check for TextEncoder/TextDecoder\n if (typeof global.TextEncoder === 'undefined') {\n missing.push('TextEncoder');\n polyfillsAvailable.push('text-encoding');\n }\n\n if (typeof global.TextDecoder === 'undefined') {\n missing.push('TextDecoder');\n polyfillsAvailable.push('text-encoding');\n }\n\n // Check for AbortController (needed for request timeouts)\n if (typeof global.AbortController === 'undefined') {\n missing.push('AbortController');\n polyfillsAvailable.push('abortcontroller-polyfill');\n }\n\n // Check for URL (should be available in modern RN)\n if (typeof global.URL === 'undefined') {\n missing.push('URL');\n warnings.push('URL constructor not available');\n }\n\n return {\n compatible: missing.length === 0,\n missing,\n warnings,\n polyfillsAvailable: [...new Set(polyfillsAvailable)],\n };\n}\n\n/**\n * Automatically setup polyfills for React Native\n * \n * Note: This requires the polyfill packages to be installed:\n * ```bash\n * npm install whatwg-fetch react-native-get-random-values abortcontroller-polyfill text-encoding\n * ```\n */\nexport function setupReactNativePolyfills(): void {\n try {\n // Install fetch polyfill\n if (typeof global.fetch === 'undefined') {\n try {\n require('whatwg-fetch');\n console.log('✓ fetch polyfill loaded');\n } catch {\n console.warn('⚠️ whatwg-fetch not installed. Install with: npm install whatwg-fetch');\n }\n }\n\n // Install crypto polyfill\n if (typeof global.crypto === 'undefined') {\n try {\n const getRandomValues = require('react-native-get-random-values');\n if (typeof global.crypto === 'undefined') {\n global.crypto = {\n getRandomValues: getRandomValues.getRandomValues,\n } as any;\n }\n console.log('✓ crypto polyfill loaded');\n } catch {\n console.warn('⚠️ react-native-get-random-values not installed. Install with: npm install react-native-get-random-values');\n }\n }\n\n // Install TextEncoder/TextDecoder polyfill\n if (typeof global.TextEncoder === 'undefined' || typeof global.TextDecoder === 'undefined') {\n try {\n const encoding = require('text-encoding');\n if (typeof global.TextEncoder === 'undefined') {\n global.TextEncoder = encoding.TextEncoder;\n }\n if (typeof global.TextDecoder === 'undefined') {\n global.TextDecoder = encoding.TextDecoder;\n }\n console.log('✓ TextEncoder/TextDecoder polyfill loaded');\n } catch {\n console.warn('⚠️ text-encoding not installed. Install with: npm install text-encoding');\n }\n }\n\n // Install AbortController polyfill\n if (typeof global.AbortController === 'undefined') {\n try {\n const AbortController = require('abortcontroller-polyfill/dist/cjs-ponyfill').AbortController;\n global.AbortController = AbortController;\n console.log('✓ AbortController polyfill loaded');\n } catch {\n console.warn('⚠️ abortcontroller-polyfill not installed. Install with: npm install abortcontroller-polyfill');\n }\n }\n } catch (error) {\n console.error('Error setting up React Native polyfills:', error);\n }\n}\n\n/**\n * Create a configured MemoryClient for React Native\n */\nexport function createReactNativeClient(\n apiKey: string,\n options: ReactNativeConfig & { baseUrl?: string } = {}\n): any {\n // Import MemoryClient dynamically to avoid circular deps\n const { MemoryClient } = require('./client.js');\n\n // Apply polyfills if provided\n if (options.fetch) {\n global.fetch = options.fetch as any;\n }\n if (options.WebSocket) {\n global.WebSocket = options.WebSocket as any;\n }\n if (options.crypto) {\n global.crypto = options.crypto as any;\n }\n if (options.TextEncoder) {\n global.TextEncoder = options.TextEncoder as any;\n }\n if (options.TextDecoder) {\n global.TextDecoder = options.TextDecoder as any;\n }\n\n // Check compatibility\n const compatibility = checkReactNativeCompatibility();\n if (!compatibility.compatible) {\n console.warn(\n 'Memory Intelligence SDK is not fully compatible with this React Native environment.\\n' +\n 'Missing APIs:', compatibility.missing.join(', ') + '\\n' +\n 'Install polyfills:', compatibility.polyfillsAvailable.join(', ')\n );\n }\n\n if (compatibility.warnings.length > 0) {\n compatibility.warnings.forEach(warning => console.warn('⚠️ ', warning));\n }\n\n return new MemoryClient({\n apiKey,\n baseUrl: options.baseUrl,\n });\n}\n\n/**\n * React Native specific utilities\n */\nexport const ReactNativeUtils = {\n /**\n * Check if running in React Native environment\n */\n isReactNative(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n (navigator as any).product === 'ReactNative'\n );\n },\n\n /**\n * Get recommended polyfill packages for current environment\n */\n getRecommendedPolyfills(): string[] {\n const compatibility = checkReactNativeCompatibility();\n return compatibility.polyfillsAvailable;\n },\n\n /**\n * Generate installation command for missing polyfills\n */\n getInstallCommand(): string | null {\n const polyfills = this.getRecommendedPolyfills();\n if (polyfills.length === 0) return null;\n \n return `npm install ${polyfills.join(' ')}`;\n },\n};\n\n/**\n * Type guard to check if error is a polyfill error\n */\nexport function isPolyfillError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n \n const message = error.message.toLowerCase();\n return (\n message.includes('fetch is not defined') ||\n message.includes('websocket is not defined') ||\n message.includes('crypto is not defined') ||\n message.includes('textencoder is not defined') ||\n message.includes('abortcontroller is not defined')\n );\n}\n\n/**\n * Helper to provide detailed polyfill error messages\n */\nexport function getPolyfillErrorHelp(error: unknown): string | null {\n if (!isPolyfillError(error)) return null;\n\n const compatibility = checkReactNativeCompatibility();\n \n return `\nReact Native Polyfill Required\n==============================\n\nThe Memory Intelligence SDK requires some Web APIs that are not available\nin React Native by default.\n\nMissing APIs: ${compatibility.missing.join(', ')}\n\nTo fix this, install the required polyfills:\n\n ${ReactNativeUtils.getInstallCommand()}\n\nThen in your app entry point (App.tsx):\n\n import 'react-native-get-random-values'; // Must be first\n import 'whatwg-fetch';\n import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';\n import { MemoryClient } from '@memoryintelligence/sdk';\n\n const client = new MemoryClient({ apiKey: 'your-key' });\n\nFor more info: https://docs.memoryintelligence.io/sdk/react-native\n`;\n}\n"]}
|