foundation-sdk 0.2.6 → 0.2.7

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/dist/index.d.ts CHANGED
@@ -1,203 +1,5 @@
1
- interface User {
2
- id: string;
3
- email: string;
4
- name?: string;
5
- picture?: string;
6
- [key: string]: unknown;
7
- }
8
- interface FileMetadata {
9
- id: string;
10
- name: string;
11
- type: string;
12
- size: number;
13
- url: string;
14
- folder?: string;
15
- metadata?: Record<string, unknown>;
16
- createdAt: string;
17
- }
18
- interface EntityChangeEvent {
19
- changeType: string;
20
- entityId?: string;
21
- id?: string;
22
- namespace?: string;
23
- timestamp?: number;
24
- }
25
- interface FoundationConfig {
26
- /** Backend config endpoint URL. If omitted, reads from /foundation-env.json */
27
- configUrl?: string;
28
- tenantId?: string;
29
- appId?: string;
30
- /** Override API base URL (e.g. '/api' when using a dev proxy) */
31
- baseUrl?: string;
32
- auth?: AuthClient;
33
- }
34
- interface FullConfig {
35
- readonly app: {
36
- id: string;
37
- name: string;
38
- version: string;
39
- environment: string;
40
- [key: string]: unknown;
41
- };
42
- readonly features: Record<string, unknown>;
43
- readonly plans: unknown[];
44
- readonly theme: {
45
- colors: Record<string, string>;
46
- dark: Record<string, string>;
47
- defaultColorScheme?: string;
48
- };
49
- readonly connectors: Record<string, unknown>;
50
- readonly resources: Record<string, string>;
51
- readonly auth: {
52
- provider: string;
53
- [key: string]: unknown;
54
- };
55
- readonly raw: Record<string, unknown>;
56
- }
57
- interface AuthClient {
58
- login(options?: Record<string, unknown>): Promise<void>;
59
- logout(options?: Record<string, unknown>): void | Promise<void>;
60
- getUser(): Promise<User | undefined>;
61
- getTokenSilently(options?: Record<string, unknown>): Promise<string>;
62
- isAuthenticated(): Promise<boolean>;
63
- signIn?(email: string, password: string): Promise<void>;
64
- signUp?(email: string, password: string, metadata?: Record<string, unknown>): Promise<void>;
65
- forgotPassword?(email: string): Promise<void>;
66
- resetPassword?(code: string, newPassword: string): Promise<void>;
67
- }
68
- interface AuthService {
69
- readonly user: User | null;
70
- readonly isAuthenticated: boolean;
71
- getToken(): Promise<string>;
72
- /** Redirect-based login (Auth0 Universal Login / Cognito Hosted UI) */
73
- login(options?: Record<string, unknown>): Promise<void>;
74
- logout(options?: Record<string, unknown>): Promise<void>;
75
- /** Direct sign in with credentials (for custom login forms) */
76
- signIn(email: string, password: string): Promise<void>;
77
- /** Direct sign up (for custom registration forms) */
78
- signUp(email: string, password: string, metadata?: Record<string, unknown>): Promise<void>;
79
- /** Initiate password reset */
80
- forgotPassword(email: string): Promise<void>;
81
- /** Complete password reset with code */
82
- resetPassword(code: string, newPassword: string): Promise<void>;
83
- onChange(callback: (user: User | null) => void): () => void;
84
- }
85
- interface DbService {
86
- list<T = unknown>(entity: string, options?: {
87
- filters?: Record<string, unknown>;
88
- limit?: number;
89
- cursor?: string;
90
- orderBy?: string;
91
- orderDir?: 'asc' | 'desc';
92
- }): Promise<{
93
- items: T[];
94
- nextCursor?: string;
95
- }>;
96
- get<T = unknown>(entity: string, id: string): Promise<T>;
97
- create<T = unknown>(entity: string, data: Partial<T>): Promise<T>;
98
- update<T = unknown>(entity: string, id: string, updates: Partial<T>): Promise<T>;
99
- save<T = unknown>(entity: string, data: Partial<T>): Promise<T>;
100
- delete(entity: string, id: string): Promise<void>;
101
- }
102
- interface FilesService {
103
- initiate(options: {
104
- name: string;
105
- contentType: string;
106
- contentLength: number;
107
- metadata?: Record<string, unknown>;
108
- sha256: string;
109
- }): Promise<{
110
- id: string;
111
- name: string;
112
- signedUrl: string;
113
- signedData: Record<string, string>;
114
- }>;
115
- upload(options: {
116
- name: string;
117
- contentType: string;
118
- file: ArrayBuffer | Blob | File;
119
- sha256: string;
120
- }): Promise<{
121
- id: string;
122
- name: string;
123
- status: string;
124
- s3UploadComplete: boolean;
125
- }>;
126
- get(fileId: string): Promise<FileMetadata>;
127
- delete(fileId: string): Promise<void>;
128
- list(options?: {
129
- limit?: number;
130
- cursor?: string;
131
- }): Promise<{
132
- items: FileMetadata[];
133
- nextCursor?: string;
134
- }>;
135
- }
136
- interface AccountService {
137
- get<TUser = User, TAccount = Record<string, unknown>>(): Promise<{
138
- user: TUser;
139
- account: TAccount;
140
- }>;
141
- update(data: Record<string, unknown>): Promise<void>;
142
- usage(): Promise<Record<string, unknown>>;
143
- resendVerification(): Promise<void>;
144
- }
145
- interface Integration {
146
- id: string;
147
- name: string;
148
- description?: string;
149
- icon?: string;
150
- authType?: string;
151
- [key: string]: unknown;
152
- }
153
- interface IntegrationConnection {
154
- id: string;
155
- source: string;
156
- connected: boolean;
157
- [key: string]: unknown;
158
- }
159
- interface IntegrationDetail extends Integration {
160
- connections: IntegrationConnection[];
161
- connected: boolean;
162
- connectionCount: number;
163
- }
164
- interface IntegrationService {
165
- list(): Promise<Integration[]>;
166
- connections(): Promise<IntegrationConnection[]>;
167
- all(): Promise<IntegrationDetail[]>;
168
- status(source: string): Promise<{
169
- connected: boolean;
170
- connections: IntegrationConnection[];
171
- }>;
172
- connect(source: string): Promise<{
173
- success: boolean;
174
- configuration?: unknown;
175
- message?: string;
176
- }>;
177
- disconnect(source: string, configurationId: string): Promise<void>;
178
- }
179
- interface OpenApiService {
180
- get(): Promise<Record<string, unknown>>;
181
- }
182
- interface LogService {
183
- info(message: string, context?: Record<string, unknown>): void;
184
- warn(message: string, context?: Record<string, unknown>): void;
185
- error(message: string, context?: Record<string, unknown>): void;
186
- event(event: string, data?: Record<string, unknown>): void;
187
- }
188
- interface Foundation {
189
- readonly ready: Promise<void>;
190
- readonly isReady: boolean;
191
- auth: AuthService;
192
- db: DbService;
193
- files: FilesService;
194
- integration: IntegrationService;
195
- account: AccountService;
196
- config: FullConfig;
197
- openapi: OpenApiService;
198
- log: LogService;
199
- on(event: string, callback: (event: EntityChangeEvent) => void): () => void;
200
- }
1
+ import { F as FoundationConfig, a as Foundation, A as AuthClient } from './types-HdCjnyCt.js';
2
+ export { g as AccountService, d as AuthProvider, e as AuthService, D as DbService, E as EntityChangeEvent, c as FileMetadata, f as FilesService, b as FullConfig, h as Integration, i as IntegrationConnection, j as IntegrationDetail, I as IntegrationService, L as LogService, O as OpenApiService, U as User } from './types-HdCjnyCt.js';
201
3
 
202
4
  /**
203
5
  * Foundation SDK — typed API client for the Foundation platform.
@@ -208,4 +10,11 @@ interface Foundation {
208
10
 
209
11
  declare function createFoundation(options: FoundationConfig): Promise<Foundation>;
210
12
 
211
- export { type AccountService, type AuthClient, type AuthService, type DbService, type EntityChangeEvent, type FileMetadata, type FilesService, type Foundation, type FoundationConfig, type FullConfig, type Integration, type IntegrationConnection, type IntegrationDetail, type IntegrationService, type LogService, type OpenApiService, type User, createFoundation };
13
+ /**
14
+ * Auth core — provider registry and AuthService wrapper.
15
+ * Provider implementations live in auth-auth0.ts and auth-cognito.ts.
16
+ */
17
+
18
+ declare function registerAuthProvider(name: string, factory: (config: Record<string, unknown>) => Promise<AuthClient>): void;
19
+
20
+ export { AuthClient, Foundation, FoundationConfig, createFoundation, registerAuthProvider };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- function _(e){return e?.response!==void 0?e.response:e?.data!==void 0?e.data:e}function B(e,t){let i=t?.error;if(i){let o=i.message||"Unknown error",n=i.details;if(n?.length){let s=n.map(a=>a.field?`${a.field}: ${a.message}`:a.message).join(", ");o=o?`${o} ${s}`:s}return Object.assign(new Error(o),{code:i.code,type:i.code,details:n,status:e})}let r=t?.data?.message||t?.message;return r?Object.assign(new Error(r),{status:e}):Object.assign(new Error(`HTTP ${e}`),{status:e})}function T(e){function t(o){return{"X-Foundation-Mvp-Application-Id":e.appId,"X-Foundation-Mvp-Tenant-Id":e.tenantId,"X-Foundation-Mvp-Application-Version":e.version,"Content-Type":"application/json",Authorization:`Bearer ${o}`}}async function i(o,n,s,a={}){let g=await e.getToken(),u=t(g),f=`${o}${n}`;if(a.params){let w=new URLSearchParams;for(let[S,y]of Object.entries(a.params))y!=null&&w.set(S,String(y));let h=w.toString();h&&(f+=`?${h}`)}let l={method:s,headers:u};a.body!==void 0&&(l.body=JSON.stringify(a.body));let d=await fetch(f,l);if(!d.ok){let w={};try{w=await d.json()}catch{}throw B(d.status,w)}if(d.status===204)return null;let m=await d.json();return _(m)}async function r(o,n={}){return fetch(o,n)}return{request:i,rawFetch:r,headers:t}}var E=new Map;function j(e,t){E.set(e,t)}j("none",async()=>({login:async()=>{},logout:async()=>{},getUser:async()=>{},getTokenSilently:async()=>"none",isAuthenticated:async()=>!0}));async function b(e){let t=E.get(e.provider);if(!t)throw new Error(`Auth provider "${e.provider}" not registered. Import "foundation-sdk/${e.provider}" to register it.`);return t(e)}function I(e){let t=null,i=[];function r(){i.forEach(n=>{try{n(t)}catch{}})}async function o(){let n=await e.getUser();t=n?{id:n.id,email:n.email,name:n.name,picture:n.picture}:null}return{get user(){return t},get isAuthenticated(){return!!t},async getToken(){return e.getTokenSilently()},async login(n){await e.login(n),await o(),r()},async logout(n){await e.logout(n),t=null,r()},async signIn(n,s){if(!e.signIn)throw new Error("signIn not supported by this auth provider");await e.signIn(n,s),await o(),r()},async signUp(n,s,a){if(!e.signUp)throw new Error("signUp not supported by this auth provider");await e.signUp(n,s,a)},async forgotPassword(n){if(!e.forgotPassword)throw new Error("forgotPassword not supported by this auth provider");await e.forgotPassword(n)},async resetPassword(n,s){if(!e.resetPassword)throw new Error("resetPassword not supported by this auth provider");await e.resetPassword(n,s)},onChange(n){return i.length>=100?(console.warn("[Foundation SDK] Auth listener limit reached."),()=>{}):(i.push(n),()=>{let s=i.indexOf(n);s>-1&&i.splice(s,1)})},async _initUser(){await e.isAuthenticated()&&await o()}}}function P(e){if(!e)throw new Error("Token parsing failed: Missing auth token");try{let[t,i]=e.split("?"),r=t.split(".");if(r.length!==3)throw new Error("Invalid JWT format");let o=atob(r[1]),n=JSON.parse(o);i&&new URLSearchParams(i).forEach((f,l)=>{n[l]=f});let s=n["BaseApplication/apiBaseUrl"];if(!s)throw new Error("Token missing apiBaseUrl");let a=n["BaseApplication/websocketBaseUrl"]||"",g=n["BaseApplication/accountBaseUrl"]||s;return{sub:n.sub||"",apiBaseUrl:s,accountBaseUrl:g,websocketBaseUrl:a,userId:n["BaseApplication/userId"]||"",namespace:n["BaseApplication/namespace"]}}catch(t){if(t instanceof Error&&t.message.startsWith("Token"))throw t;let i=t instanceof Error?t.message:"Failed to parse token";throw new Error(`Token parsing failed: ${i}`)}}async function H(e){let t=e.configUrl,i=e.appId,r=e.tenantId;try{let c=await fetch("/foundation-env.json");if(c.ok){let p=await c.json();p.configUrl&&(t=p.configUrl,i=p.applicationId||i,r=p.applicationTenant||r)}}catch{}if(!t)throw new Error("No configUrl provided and /foundation-env.json not found");let o={Accept:"application/json","Cache-Control":"no-cache"};i&&(o["X-Foundation-Mvp-Application-Id"]=i),r&&(o["X-Foundation-Mvp-Tenant-Id"]=r);let n=await fetch(t,{headers:o});if(!n.ok)throw new Error(`Failed to fetch config: ${n.statusText}`);let s=await n.json(),a=s.data??s,g=a.auth||{provider:"none"},u=e.auth||await b(g),l=I(u);await l._initUser();let d,m;if(e.baseUrl)d=e.baseUrl,m=e.baseUrl;else if(g.apiUrls?.apiBaseUrl){let c=g.apiUrls;d=c.apiBaseUrl,m=c.accountBaseUrl||d}else{let c=await u.getTokenSilently(),p=P(c);d=p.apiBaseUrl,m=p.accountBaseUrl}let w=i||a.app?.id||a.tenant?.identifier||"",h=r||a.tenant?.identifier||"",S=a.app?.version||a.core?.version||"0.0.0",y=T({appId:w,tenantId:h,version:S,getToken:()=>u.getTokenSilently()}),U={};try{U=await y.request(d,"/api/v1/config/init","GET")||{}}catch(c){console.warn("[Foundation SDK] Backend config fetch failed:",c)}let v={...a,...U},C="";try{let c=await u.getTokenSilently();c&&c!=="none"&&(C=P(c).namespace||"")}catch{}let R={get app(){let c=v.app||{};return{id:c.id||w,name:c.name||"",version:c.version||S,environment:c.environment||"",...c}},get features(){return v.features||{}},get plans(){return v.plans||[]},get theme(){let c=v.theme||{};return{colors:c.colors||{},dark:c.dark||{},defaultColorScheme:c.defaultColorScheme}},get connectors(){return v.connectors||{}},get resources(){return v.resources||{}},get auth(){let{provider:c,...p}=g;return{provider:c,...p}},get raw(){return v}},F=L(y,d),q=M(y,d,C),$=G(y,m),x=J(y,d,m,C),O=X(y,d),D=N(),A=[];return{get ready(){return Promise.resolve()},get isReady(){return!0},auth:l,db:F,files:q,integration:x,account:$,config:R,openapi:O,log:D,on(c,p){return c==="entity.changed"?(A.push(p),()=>{let k=A.indexOf(p);k>-1&&A.splice(k,1)}):()=>{}}}}function L(e,t){return{async list(i,r={}){let{filters:o,limit:n,cursor:s,orderBy:a,orderDir:g}=r,u={...o};return n&&(u.limit=n),s&&(u.next=s),a&&(u.orderBy=a),g&&(u.orderDir=g),e.request(t,`/api/v1/core/${i}`,"GET",{params:u})},async get(i,r){return e.request(t,`/api/v1/core/${i}`,"GET",{params:{id:r}})},async create(i,r){return e.request(t,`/api/v1/core/${i}`,"POST",{body:r})},async update(i,r,o){return e.request(t,`/api/v1/core/${i}`,"PUT",{body:{id:r,...o}})},async save(i,r){try{return await e.request(t,`/api/v1/core/${i}`,"PUT",{body:r})}catch{return e.request(t,`/api/v1/core/${i}`,"POST",{body:r})}},async delete(i,r){await e.request(t,`/api/v1/core/${i}`,"DELETE",{body:{id:r}})}}}function M(e,t,i){return{async initiate(r){return e.request(t,"/api/v1/core/upload","POST",{body:{...r,__namespace:i}})},async upload(r){let o;r.file instanceof ArrayBuffer?o=r.file:o=await r.file.arrayBuffer();let n=await e.request(t,"/api/v1/core/upload","POST",{body:{name:r.name,contentType:r.contentType,contentLength:o.byteLength,sha256:r.sha256,__namespace:i}});if(!n.signedUrl||!n.signedData)throw new Error("Missing signedUrl or signedData in response");let s=new FormData;Object.entries(n.signedData).forEach(([g,u])=>{s.append(g,u)}),s.append("file",new Blob([o],{type:r.contentType}),r.name);let a=await fetch(n.signedUrl,{method:"POST",body:s});if(a.status!==204)throw new Error(`S3 upload failed: ${a.status}`);return{id:n.id,name:n.name,status:"uploaded",s3UploadComplete:!0}},async get(r){return e.request(t,"/api/v1/core/files","GET",{params:{id:r,__namespace:i}})},async delete(r){await e.request(t,`/api/v1/core/files/${r}`,"DELETE")},async list(r={}){let o={__namespace:i};r.limit&&(o.limit=r.limit),r.cursor&&(o.cursor=r.cursor);let n=await e.request(t,"/api/v1/core/files","GET",{params:o});return{items:n?.items||[],nextCursor:n?.next}}}}function G(e,t){return{async get(){return e.request(t,"/api/v1/accounts/account","GET")},async update(i){await e.request(t,"/api/v1/accounts/account","PUT",{body:{user:i}})},async usage(){return e.request(t,"/api/v1/accounts/account/usage","GET")},async resendVerification(){await e.request(t,"/api/v1/accounts/account/resend-verification","POST")}}}function J(e,t,i,r){let o={async list(){return e.request(t,"/api/v1/config/connectors","GET")},async connections(){return e.request(t,"/api/v1/core/integrations","GET",{params:{query:"default",__namespace:r}})},async all(){let[n,s]=await Promise.all([o.list(),o.connections()]),a=Array.isArray(n)?n:n?.items||[],g=Array.isArray(s)?s:s?.items||[],u=new Map;for(let f of g){let l=f.source||f.id;u.has(l)||u.set(l,[]),u.get(l).push(f)}return a.map(f=>{let l=u.get(f.id)||[];return{...f,connections:l,connected:l.some(d=>d.connected),connectionCount:l.filter(d=>d.connected).length}})},async status(n){let s=await o.connections(),g=(Array.isArray(s)?s:s?.items||[]).filter(u=>u.source===n&&u.connected);return{connected:g.length>0,connections:g}},async connect(n){return e.request(i,`/api/v1/accounts/integrations/${n}/initialize`,"POST",{body:{__namespace:r}})},async disconnect(n,s){await e.request(i,`/api/v1/accounts/integrations/${n}/remove`,"POST",{body:{configurationId:s}})}};return o}function X(e,t){return{async get(){return e.request(t,"/api/v1/config/openapi","GET")}}}function N(){return{info:(e,t)=>console.log(`[Foundation] ${e}`,t??""),warn:(e,t)=>console.warn(`[Foundation] ${e}`,t??""),error:(e,t)=>console.error(`[Foundation] ${e}`,t??""),event:(e,t)=>console.log(`[Foundation Event] ${e}`,t??"")}}export{H as createFoundation};
1
+ function B(e){return e?.response!==void 0?e.response:e?.data!==void 0?e.data:e}function j(e,t){let i=t?.error;if(i){let o=i.message||"Unknown error",n=i.details;if(n?.length){let s=n.map(a=>a.field?`${a.field}: ${a.message}`:a.message).join(", ");o=o?`${o} ${s}`:s}return Object.assign(new Error(o),{code:i.code,type:i.code,details:n,status:e})}let r=t?.data?.message||t?.message;return r?Object.assign(new Error(r),{status:e}):Object.assign(new Error(`HTTP ${e}`),{status:e})}function T(e){function t(o){return{"X-Foundation-Mvp-Application-Id":e.appId,"X-Foundation-Mvp-Tenant-Id":e.tenantId,"X-Foundation-Mvp-Application-Version":e.version,"Content-Type":"application/json",Authorization:`Bearer ${o}`}}async function i(o,n,s,a={}){let d=await e.getToken(),u=t(d),f=`${o}${n}`;if(a.params){let w=new URLSearchParams;for(let[S,y]of Object.entries(a.params))y!=null&&w.set(S,String(y));let h=w.toString();h&&(f+=`?${h}`)}let l={method:s,headers:u};a.body!==void 0&&(l.body=JSON.stringify(a.body));let g=await fetch(f,l);if(!g.ok){let w={};try{w=await g.json()}catch{}throw j(g.status,w)}if(g.status===204)return null;let m=await g.json();return B(m)}async function r(o,n={}){return fetch(o,n)}return{request:i,rawFetch:r,headers:t}}var E=new Map;function b(e,t){E.set(e,t)}b("none",async()=>({login:async()=>{},logout:async()=>{},getUser:async()=>{},getTokenSilently:async()=>"none",isAuthenticated:async()=>!0}));async function I(e){let t=E.get(e.provider);if(!t)throw new Error(`Auth provider "${e.provider}" not registered. Import "foundation-sdk/${e.provider}" to register it.`);return t(e)}function R(e){let t=null,i=[];function r(){i.forEach(n=>{try{n(t)}catch{}})}async function o(){let n=await e.getUser();t=n?{id:n.id,email:n.email,name:n.name,picture:n.picture}:null}return{get user(){return t},get isAuthenticated(){return!!t},async getToken(){return e.getTokenSilently()},async login(n){await e.login(n),await o(),r()},async logout(n){await e.logout(n),t=null,r()},async signIn(n,s){if(!e.signIn)throw new Error("signIn not supported by this auth provider");await e.signIn(n,s),await o(),r()},async signUp(n,s,a){if(!e.signUp)throw new Error("signUp not supported by this auth provider");await e.signUp(n,s,a)},async forgotPassword(n){if(!e.forgotPassword)throw new Error("forgotPassword not supported by this auth provider");await e.forgotPassword(n)},async resetPassword(n,s){if(!e.resetPassword)throw new Error("resetPassword not supported by this auth provider");await e.resetPassword(n,s)},onChange(n){return i.length>=100?(console.warn("[Foundation SDK] Auth listener limit reached."),()=>{}):(i.push(n),()=>{let s=i.indexOf(n);s>-1&&i.splice(s,1)})},async _initUser(){await e.isAuthenticated()&&await o()}}}function P(e){if(!e)throw new Error("Token parsing failed: Missing auth token");try{let[t,i]=e.split("?"),r=t.split(".");if(r.length!==3)throw new Error("Invalid JWT format");let o=atob(r[1]),n=JSON.parse(o);i&&new URLSearchParams(i).forEach((f,l)=>{n[l]=f});let s=n["BaseApplication/apiBaseUrl"];if(!s)throw new Error("Token missing apiBaseUrl");let a=n["BaseApplication/websocketBaseUrl"]||"",d=n["BaseApplication/accountBaseUrl"]||s;return{sub:n.sub||"",apiBaseUrl:s,accountBaseUrl:d,websocketBaseUrl:a,userId:n["BaseApplication/userId"]||"",namespace:n["BaseApplication/namespace"]}}catch(t){if(t instanceof Error&&t.message.startsWith("Token"))throw t;let i=t instanceof Error?t.message:"Failed to parse token";throw new Error(`Token parsing failed: ${i}`)}}async function H(e){let t=e.configUrl,i=e.appId,r=e.tenantId;try{let c=await fetch("/foundation-env.json");if(c.ok){let p=await c.json();p.configUrl&&(t=p.configUrl,i=p.applicationId||i,r=p.applicationTenant||r)}}catch{}if(!t)throw new Error("No configUrl provided and /foundation-env.json not found");let o={Accept:"application/json","Cache-Control":"no-cache"};i&&(o["X-Foundation-Mvp-Application-Id"]=i),r&&(o["X-Foundation-Mvp-Tenant-Id"]=r);let n=await fetch(t,{headers:o});if(!n.ok)throw new Error(`Failed to fetch config: ${n.statusText}`);let s=await n.json(),a=s.data??s,d=a.auth||{provider:"none"},u;e.auth&&typeof e.auth=="function"?u=await e.auth(d):e.auth?u=e.auth:u=await I(d);let l=R(u);await l._initUser();let g,m;if(e.baseUrl)g=e.baseUrl,m=e.baseUrl;else if(d.apiUrls?.apiBaseUrl){let c=d.apiUrls;g=c.apiBaseUrl,m=c.accountBaseUrl||g}else{let c=await u.getTokenSilently(),p=P(c);g=p.apiBaseUrl,m=p.accountBaseUrl}let w=i||a.app?.id||a.tenant?.identifier||"",h=r||a.tenant?.identifier||"",S=a.app?.version||a.core?.version||"0.0.0",y=T({appId:w,tenantId:h,version:S,getToken:()=>u.getTokenSilently()}),U={};try{U=await y.request(g,"/api/v1/config/init","GET")||{}}catch(c){console.warn("[Foundation SDK] Backend config fetch failed:",c)}let v={...a,...U},C="";try{let c=await u.getTokenSilently();c&&c!=="none"&&(C=P(c).namespace||"")}catch{}let F={get app(){let c=v.app||{};return{id:c.id||w,name:c.name||"",version:c.version||S,environment:c.environment||"",...c}},get features(){return v.features||{}},get plans(){return v.plans||[]},get theme(){let c=v.theme||{};return{colors:c.colors||{},dark:c.dark||{},defaultColorScheme:c.defaultColorScheme}},get connectors(){return v.connectors||{}},get resources(){return v.resources||{}},get auth(){let{provider:c,...p}=d;return{provider:c,...p}},get raw(){return v}},q=L(y,g),$=M(y,g,C),x=G(y,m),O=J(y,g,m,C),D=X(y,g),_=N(),A=[];return{get ready(){return Promise.resolve()},get isReady(){return!0},auth:l,db:q,files:$,integration:O,account:x,config:F,openapi:D,log:_,on(c,p){return c==="entity.changed"?(A.push(p),()=>{let k=A.indexOf(p);k>-1&&A.splice(k,1)}):()=>{}}}}function L(e,t){return{async list(i,r={}){let{filters:o,limit:n,cursor:s,orderBy:a,orderDir:d}=r,u={...o};return n&&(u.limit=n),s&&(u.next=s),a&&(u.orderBy=a),d&&(u.orderDir=d),e.request(t,`/api/v1/core/${i}`,"GET",{params:u})},async get(i,r){return e.request(t,`/api/v1/core/${i}`,"GET",{params:{id:r}})},async create(i,r){return e.request(t,`/api/v1/core/${i}`,"POST",{body:r})},async update(i,r,o){return e.request(t,`/api/v1/core/${i}`,"PUT",{body:{id:r,...o}})},async save(i,r){try{return await e.request(t,`/api/v1/core/${i}`,"PUT",{body:r})}catch{return e.request(t,`/api/v1/core/${i}`,"POST",{body:r})}},async delete(i,r){await e.request(t,`/api/v1/core/${i}`,"DELETE",{body:{id:r}})}}}function M(e,t,i){return{async initiate(r){return e.request(t,"/api/v1/core/upload","POST",{body:{...r,__namespace:i}})},async upload(r){let o;r.file instanceof ArrayBuffer?o=r.file:o=await r.file.arrayBuffer();let n=await e.request(t,"/api/v1/core/upload","POST",{body:{name:r.name,contentType:r.contentType,contentLength:o.byteLength,sha256:r.sha256,__namespace:i}});if(!n.signedUrl||!n.signedData)throw new Error("Missing signedUrl or signedData in response");let s=new FormData;Object.entries(n.signedData).forEach(([d,u])=>{s.append(d,u)}),s.append("file",new Blob([o],{type:r.contentType}),r.name);let a=await fetch(n.signedUrl,{method:"POST",body:s});if(a.status!==204)throw new Error(`S3 upload failed: ${a.status}`);return{id:n.id,name:n.name,status:"uploaded",s3UploadComplete:!0}},async get(r){return e.request(t,"/api/v1/core/files","GET",{params:{id:r,__namespace:i}})},async delete(r){await e.request(t,`/api/v1/core/files/${r}`,"DELETE")},async list(r={}){let o={__namespace:i};r.limit&&(o.limit=r.limit),r.cursor&&(o.cursor=r.cursor);let n=await e.request(t,"/api/v1/core/files","GET",{params:o});return{items:n?.items||[],nextCursor:n?.next}}}}function G(e,t){return{async get(){return e.request(t,"/api/v1/accounts/account","GET")},async update(i){await e.request(t,"/api/v1/accounts/account","PUT",{body:{user:i}})},async usage(){return e.request(t,"/api/v1/accounts/account/usage","GET")},async resendVerification(){await e.request(t,"/api/v1/accounts/account/resend-verification","POST")}}}function J(e,t,i,r){let o={async list(){return e.request(t,"/api/v1/config/connectors","GET")},async connections(){return e.request(t,"/api/v1/core/integrations","GET",{params:{query:"default",__namespace:r}})},async all(){let[n,s]=await Promise.all([o.list(),o.connections()]),a=Array.isArray(n)?n:n?.items||[],d=Array.isArray(s)?s:s?.items||[],u=new Map;for(let f of d){let l=f.source||f.id;u.has(l)||u.set(l,[]),u.get(l).push(f)}return a.map(f=>{let l=u.get(f.id)||[];return{...f,connections:l,connected:l.some(g=>g.connected),connectionCount:l.filter(g=>g.connected).length}})},async status(n){let s=await o.connections(),d=(Array.isArray(s)?s:s?.items||[]).filter(u=>u.source===n&&u.connected);return{connected:d.length>0,connections:d}},async connect(n){return e.request(i,`/api/v1/accounts/integrations/${n}/initialize`,"POST",{body:{__namespace:r}})},async disconnect(n,s){await e.request(i,`/api/v1/accounts/integrations/${n}/remove`,"POST",{body:{configurationId:s}})}};return o}function X(e,t){return{async get(){return e.request(t,"/api/v1/config/openapi","GET")}}}function N(){return{info:(e,t)=>console.log(`[Foundation] ${e}`,t??""),warn:(e,t)=>console.warn(`[Foundation] ${e}`,t??""),error:(e,t)=>console.error(`[Foundation] ${e}`,t??""),event:(e,t)=>console.log(`[Foundation Event] ${e}`,t??"")}}export{H as createFoundation,b as registerAuthProvider};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/http.ts","../src/auth.ts","../src/jwt.ts","../src/foundation.ts"],"sourcesContent":["/**\n * HTTP layer for Foundation API calls.\n * Handles request construction, response unwrapping, and error extraction.\n */\n\n/**\n * Unwrap backend response envelope.\n * The API wraps responses in { response: ... } or { data: ... }.\n */\nexport function unwrapResponse(json: Record<string, unknown>): unknown {\n if (json?.response !== undefined) return json.response\n if (json?.data !== undefined) return json.data\n return json\n}\n\n/**\n * Extract a meaningful error from a failed API response.\n */\nexport function extractError(status: number, body: Record<string, unknown>): Error {\n const errorObj = body?.error as Record<string, unknown> | undefined\n\n if (errorObj) {\n let message = errorObj.message as string || 'Unknown error'\n const details = errorObj.details as Array<{ field?: string; message?: string }> | undefined\n if (details?.length) {\n const detailMessages = details\n .map(d => d.field ? `${d.field}: ${d.message}` : d.message)\n .join(', ')\n message = message ? `${message} ${detailMessages}` : detailMessages\n }\n return Object.assign(new Error(message), {\n code: errorObj.code,\n type: errorObj.code,\n details,\n status\n })\n }\n\n const customMessage = (body?.data as Record<string, unknown>)?.message || body?.message\n if (customMessage) {\n return Object.assign(new Error(customMessage as string), { status })\n }\n\n return Object.assign(new Error(`HTTP ${status}`), { status })\n}\n\nexport interface HttpClientConfig {\n appId: string\n tenantId: string\n version: string\n getToken: () => Promise<string>\n}\n\nexport function createHttpClient(config: HttpClientConfig) {\n function headers(token: string): Record<string, string> {\n return {\n 'X-Foundation-Mvp-Application-Id': config.appId,\n 'X-Foundation-Mvp-Tenant-Id': config.tenantId,\n 'X-Foundation-Mvp-Application-Version': config.version,\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n }\n }\n\n async function request(\n baseUrl: string,\n path: string,\n method: string,\n options: { params?: Record<string, unknown>; body?: unknown } = {}\n ): Promise<unknown> {\n const token = await config.getToken()\n const hdrs = headers(token)\n\n let url = `${baseUrl}${path}`\n if (options.params) {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(options.params)) {\n if (value !== undefined && value !== null) {\n searchParams.set(key, String(value))\n }\n }\n const qs = searchParams.toString()\n if (qs) url += `?${qs}`\n }\n\n const fetchOptions: RequestInit = { method, headers: hdrs }\n if (options.body !== undefined) {\n fetchOptions.body = JSON.stringify(options.body)\n }\n\n const response = await fetch(url, fetchOptions)\n\n if (!response.ok) {\n let body: Record<string, unknown> = {}\n try { body = await response.json() } catch { /* no json body */ }\n throw extractError(response.status, body)\n }\n\n if (response.status === 204) return null\n\n const json = await response.json()\n return unwrapResponse(json as Record<string, unknown>)\n }\n\n /** Raw fetch with auth headers but no unwrapping (for S3 uploads etc.) */\n async function rawFetch(url: string, options: RequestInit = {}): Promise<Response> {\n return fetch(url, options)\n }\n\n return { request, rawFetch, headers }\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","/**\n * Auth core — provider registry and AuthService wrapper.\n * Provider implementations live in auth-auth0.ts and auth-cognito.ts.\n */\nimport type { AuthClient, AuthService, User } from './types'\n\nconst MAX_LISTENERS = 100\n\n// --- Provider registry ---\n\nconst providers = new Map<string, (config: Record<string, unknown>) => Promise<AuthClient>>()\n\nexport function registerAuthProvider(name: string, factory: (config: Record<string, unknown>) => Promise<AuthClient>) {\n providers.set(name, factory)\n}\n\n// Built-in \"none\" provider\nregisterAuthProvider('none', async () => ({\n login: async () => {},\n logout: async () => {},\n getUser: async () => undefined,\n getTokenSilently: async () => 'none',\n isAuthenticated: async () => true\n}))\n\nexport interface AuthProviderConfig {\n provider: string\n [key: string]: unknown\n}\n\nexport async function createAuthClient(config: AuthProviderConfig): Promise<AuthClient> {\n const factory = providers.get(config.provider)\n if (!factory) {\n throw new Error(\n `Auth provider \"${config.provider}\" not registered. ` +\n `Import \"foundation-sdk/${config.provider}\" to register it.`\n )\n }\n return factory(config)\n}\n\n// --- AuthService wrapper ---\n\nexport function createAuthService(client: AuthClient): AuthService & { _initUser(): Promise<void> } {\n let user: User | null = null\n const listeners: Array<(user: User | null) => void> = []\n\n function notifyListeners() {\n listeners.forEach(fn => { try { fn(user) } catch { /* */ } })\n }\n\n async function refreshUser() {\n const authUser = await client.getUser()\n user = authUser ? { id: authUser.id, email: authUser.email, name: authUser.name, picture: authUser.picture } : null\n }\n\n return {\n get user() { return user },\n get isAuthenticated() { return !!user },\n\n async getToken() {\n return client.getTokenSilently()\n },\n\n async login(options) {\n await client.login(options)\n await refreshUser()\n notifyListeners()\n },\n\n async logout(options) {\n await client.logout(options)\n user = null\n notifyListeners()\n },\n\n async signIn(email, password) {\n if (!client.signIn) throw new Error('signIn not supported by this auth provider')\n await client.signIn(email, password)\n await refreshUser()\n notifyListeners()\n },\n\n async signUp(email, password, metadata) {\n if (!client.signUp) throw new Error('signUp not supported by this auth provider')\n await client.signUp(email, password, metadata)\n },\n\n async forgotPassword(email) {\n if (!client.forgotPassword) throw new Error('forgotPassword not supported by this auth provider')\n await client.forgotPassword(email)\n },\n\n async resetPassword(code, newPassword) {\n if (!client.resetPassword) throw new Error('resetPassword not supported by this auth provider')\n await client.resetPassword(code, newPassword)\n },\n\n onChange(callback) {\n if (listeners.length >= MAX_LISTENERS) {\n console.warn('[Foundation SDK] Auth listener limit reached.')\n return () => {}\n }\n listeners.push(callback)\n return () => {\n const idx = listeners.indexOf(callback)\n if (idx > -1) listeners.splice(idx, 1)\n }\n },\n\n async _initUser() {\n const authenticated = await client.isAuthenticated()\n if (authenticated) await refreshUser()\n }\n }\n}\n","export interface JwtClaims {\n sub: string\n apiBaseUrl: string\n accountBaseUrl: string\n websocketBaseUrl: string\n userId: string\n namespace?: string\n}\n\nexport function parseJwt(token: string): JwtClaims {\n if (!token) {\n throw new Error('Token parsing failed: Missing auth token')\n }\n\n try {\n // Auth0 tokens can have query params appended: \"jwt?param=value\"\n const [jwtPart, queryPart] = token.split('?')\n\n const parts = jwtPart.split('.')\n if (parts.length !== 3) {\n throw new Error('Invalid JWT format')\n }\n\n const payloadStr = atob(parts[1])\n const jwtPayload = JSON.parse(payloadStr)\n\n // Merge query params if present\n if (queryPart) {\n const params = new URLSearchParams(queryPart)\n params.forEach((value, key) => {\n jwtPayload[key] = value\n })\n }\n\n const apiBaseUrl = jwtPayload['BaseApplication/apiBaseUrl']\n if (!apiBaseUrl) {\n throw new Error('Token missing apiBaseUrl')\n }\n\n const websocketBaseUrl = jwtPayload['BaseApplication/websocketBaseUrl'] || ''\n const accountBaseUrl = jwtPayload['BaseApplication/accountBaseUrl'] || apiBaseUrl\n\n return {\n sub: jwtPayload.sub || '',\n apiBaseUrl,\n accountBaseUrl,\n websocketBaseUrl,\n userId: jwtPayload['BaseApplication/userId'] || '',\n namespace: jwtPayload['BaseApplication/namespace']\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('Token')) {\n throw err\n }\n const message = err instanceof Error ? err.message : 'Failed to parse token'\n throw new Error(`Token parsing failed: ${message}`)\n }\n}\n","/**\n * Foundation SDK — typed API client for the Foundation platform.\n *\n * One input: a config URL. The SDK fetches it, discovers auth, API URLs,\n * features, plans, theme, connectors — everything. Self-configuring.\n */\nimport type {\n Foundation,\n FoundationConfig,\n FullConfig,\n AuthService,\n DbService,\n FilesService,\n AccountService,\n IntegrationService,\n Integration,\n IntegrationConnection,\n IntegrationDetail,\n OpenApiService,\n LogService,\n EntityChangeEvent,\n User\n} from './types'\nimport { createHttpClient, unwrapResponse, type HttpClient } from './http'\nimport { createAuthClient, createAuthService, type AuthProviderConfig } from './auth'\nimport { parseJwt } from './jwt'\n\nexport async function createFoundation(options: FoundationConfig): Promise<Foundation> {\n // 1. Resolve config URL — foundation-env.json wins if it exists (deployed env)\n let configUrl = options.configUrl\n let resolvedAppId = options.appId\n let resolvedTenantId = options.tenantId\n\n try {\n const envResponse = await fetch('/foundation-env.json')\n if (envResponse.ok) {\n const env = await envResponse.json()\n if (env.configUrl) {\n configUrl = env.configUrl\n resolvedAppId = env.applicationId || resolvedAppId\n resolvedTenantId = env.applicationTenant || resolvedTenantId\n }\n }\n } catch { /* no env file — use passed options */ }\n\n if (!configUrl) {\n throw new Error('No configUrl provided and /foundation-env.json not found')\n }\n\n // 2. Fetch public config\n const configHeaders: Record<string, string> = { 'Accept': 'application/json', 'Cache-Control': 'no-cache' }\n if (resolvedAppId) configHeaders['X-Foundation-Mvp-Application-Id'] = resolvedAppId\n if (resolvedTenantId) configHeaders['X-Foundation-Mvp-Tenant-Id'] = resolvedTenantId\n\n const publicConfigResponse = await fetch(configUrl, { headers: configHeaders })\n if (!publicConfigResponse.ok) {\n throw new Error(`Failed to fetch config: ${publicConfigResponse.statusText}`)\n }\n const rawPublicConfig = await publicConfigResponse.json()\n const publicConfig = rawPublicConfig.data ?? rawPublicConfig\n\n // 2. Set up auth\n const authConfig: AuthProviderConfig = publicConfig.auth || { provider: 'none' }\n const authClient = options.auth || await createAuthClient(authConfig)\n const authServiceRaw = createAuthService(authClient)\n const authService = authServiceRaw as AuthService & { _initUser(): Promise<void> }\n await authService._initUser()\n\n // 3. Determine API URLs\n let apiBaseUrl: string\n let accountBaseUrl: string\n\n if (options.baseUrl) {\n // Explicit override (e.g. '/api' with a dev proxy)\n apiBaseUrl = options.baseUrl\n accountBaseUrl = options.baseUrl\n } else if ((authConfig as Record<string, any>).apiUrls?.apiBaseUrl) {\n // API URLs from public config (no-auth mode or explicit)\n const apiUrls = (authConfig as Record<string, any>).apiUrls\n apiBaseUrl = apiUrls.apiBaseUrl\n accountBaseUrl = apiUrls.accountBaseUrl || apiBaseUrl\n } else {\n // API URLs from JWT token\n const token = await authClient.getTokenSilently()\n const claims = parseJwt(token)\n apiBaseUrl = claims.apiBaseUrl\n accountBaseUrl = claims.accountBaseUrl\n }\n\n // 4. Create HTTP client\n const appId = resolvedAppId || publicConfig.app?.id || publicConfig.tenant?.identifier || ''\n const tenantId = resolvedTenantId || publicConfig.tenant?.identifier || ''\n const version = publicConfig.app?.version || publicConfig.core?.version || '0.0.0'\n\n const http = createHttpClient({\n appId,\n tenantId,\n version,\n getToken: () => authClient.getTokenSilently()\n })\n\n // 5. Fetch backend config (authenticated)\n let backendConfig: Record<string, unknown> = {}\n try {\n const cfg = await http.request(apiBaseUrl, '/api/v1/config/init', 'GET')\n backendConfig = (cfg || {}) as Record<string, unknown>\n } catch (err) {\n console.warn('[Foundation SDK] Backend config fetch failed:', err)\n }\n\n // 6. Merge configs\n const mergedConfig = { ...publicConfig, ...backendConfig }\n\n // Determine namespace from JWT if available\n let namespace = ''\n try {\n const token = await authClient.getTokenSilently()\n if (token && token !== 'none') {\n const claims = parseJwt(token)\n namespace = claims.namespace || ''\n }\n } catch { /* no token yet */ }\n\n // 7. Build config service\n const config: FullConfig = {\n get app() {\n const app = mergedConfig.app as Record<string, unknown> || {}\n return {\n id: (app.id || appId) as string,\n name: (app.name || '') as string,\n version: (app.version || version) as string,\n environment: (app.environment || '') as string,\n ...app\n }\n },\n get features() { return (mergedConfig.features || {}) as Record<string, unknown> },\n get plans() { return (mergedConfig.plans || []) as unknown[] },\n get theme() {\n const theme = mergedConfig.theme as Record<string, unknown> || {}\n return {\n colors: (theme.colors || {}) as Record<string, string>,\n dark: (theme.dark || {}) as Record<string, string>,\n defaultColorScheme: theme.defaultColorScheme as string | undefined\n }\n },\n get connectors() { return (mergedConfig.connectors || {}) as Record<string, unknown> },\n get resources() { return (mergedConfig.resources || {}) as Record<string, string> },\n get auth() {\n const { provider, ...rest } = authConfig\n return { provider, ...rest } as { provider: string; [key: string]: unknown }\n },\n get raw() { return mergedConfig }\n }\n\n // 8. Build services\n const db = createDbService(http, apiBaseUrl)\n const files = createFilesService(http, apiBaseUrl, namespace)\n const account = createAccountService(http, accountBaseUrl)\n const integration = createIntegrationService(http, apiBaseUrl, accountBaseUrl, namespace)\n const openapi = createOpenApiService(http, apiBaseUrl)\n const log = createLogService()\n\n // Entity change listeners (WebSocket support is future)\n const entityListeners: Array<(event: EntityChangeEvent) => void> = []\n\n const foundation: Foundation = {\n get ready() { return Promise.resolve() },\n get isReady() { return true },\n auth: authService,\n db,\n files,\n integration,\n account,\n config,\n openapi,\n log,\n on(event, callback) {\n if (event === 'entity.changed') {\n entityListeners.push(callback)\n return () => {\n const idx = entityListeners.indexOf(callback)\n if (idx > -1) entityListeners.splice(idx, 1)\n }\n }\n return () => {}\n }\n }\n\n return foundation\n}\n\n// --- Service factories ---\n\nfunction createDbService(http: HttpClient, apiBase: string): DbService {\n return {\n async list(entity, options = {}) {\n const { filters, limit, cursor, orderBy, orderDir } = options\n const params: Record<string, unknown> = { ...filters }\n if (limit) params.limit = limit\n if (cursor) params.next = cursor\n if (orderBy) params.orderBy = orderBy\n if (orderDir) params.orderDir = orderDir\n return http.request(apiBase, `/api/v1/core/${entity}`, 'GET', { params }) as Promise<any>\n },\n async get(entity, id) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'GET', { params: { id } }) as Promise<any>\n },\n async create(entity, data) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'POST', { body: data }) as Promise<any>\n },\n async update(entity, id, updates) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'PUT', { body: { id, ...updates } }) as Promise<any>\n },\n async save(entity, data) {\n try {\n return await http.request(apiBase, `/api/v1/core/${entity}`, 'PUT', { body: data }) as Promise<any>\n } catch {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'POST', { body: data }) as Promise<any>\n }\n },\n async delete(entity, id) {\n await http.request(apiBase, `/api/v1/core/${entity}`, 'DELETE', { body: { id } })\n }\n }\n}\n\nfunction createFilesService(http: HttpClient, apiBase: string, namespace: string): FilesService {\n return {\n async initiate(options) {\n return http.request(apiBase, '/api/v1/core/upload', 'POST', {\n body: { ...options, __namespace: namespace }\n }) as Promise<any>\n },\n async upload(options) {\n let fileData: ArrayBuffer\n if (options.file instanceof ArrayBuffer) {\n fileData = options.file\n } else {\n fileData = await options.file.arrayBuffer()\n }\n\n const uploadData = await http.request(apiBase, '/api/v1/core/upload', 'POST', {\n body: { name: options.name, contentType: options.contentType, contentLength: fileData.byteLength, sha256: options.sha256, __namespace: namespace }\n }) as { id: string; name: string; signedUrl: string; signedData: Record<string, string> }\n\n if (!uploadData.signedUrl || !uploadData.signedData) {\n throw new Error('Missing signedUrl or signedData in response')\n }\n\n const formData = new FormData()\n Object.entries(uploadData.signedData).forEach(([key, value]) => {\n formData.append(key, value)\n })\n formData.append('file', new Blob([fileData], { type: options.contentType }), options.name)\n\n const s3Response = await fetch(uploadData.signedUrl, { method: 'POST', body: formData })\n if (s3Response.status !== 204) {\n throw new Error(`S3 upload failed: ${s3Response.status}`)\n }\n\n return { id: uploadData.id, name: uploadData.name, status: 'uploaded', s3UploadComplete: true }\n },\n async get(fileId) {\n return http.request(apiBase, '/api/v1/core/files', 'GET', {\n params: { id: fileId, __namespace: namespace }\n }) as Promise<any>\n },\n async delete(fileId) {\n await http.request(apiBase, `/api/v1/core/files/${fileId}`, 'DELETE')\n },\n async list(options = {}) {\n const params: Record<string, unknown> = { __namespace: namespace }\n if (options.limit) params.limit = options.limit\n if (options.cursor) params.cursor = options.cursor\n const result = await http.request(apiBase, '/api/v1/core/files', 'GET', { params }) as {\n items?: unknown[]; next?: string\n }\n return { items: result?.items || [], nextCursor: result?.next } as any\n }\n }\n}\n\nfunction createAccountService(http: HttpClient, accountBase: string): AccountService {\n return {\n async get() {\n return http.request(accountBase, '/api/v1/accounts/account', 'GET') as Promise<any>\n },\n async update(data) {\n await http.request(accountBase, '/api/v1/accounts/account', 'PUT', { body: { user: data } })\n },\n async usage() {\n return http.request(accountBase, '/api/v1/accounts/account/usage', 'GET') as Promise<any>\n },\n async resendVerification() {\n await http.request(accountBase, '/api/v1/accounts/account/resend-verification', 'POST')\n }\n }\n}\n\nfunction createIntegrationService(http: HttpClient, apiBase: string, accountBase: string, namespace: string): IntegrationService {\n const service: IntegrationService = {\n async list() {\n return http.request(apiBase, '/api/v1/config/connectors', 'GET') as Promise<any>\n },\n async connections() {\n return http.request(apiBase, '/api/v1/core/integrations', 'GET', {\n params: { query: 'default', __namespace: namespace }\n }) as Promise<any>\n },\n async all() {\n const [rawCatalog, rawConnections] = await Promise.all([\n service.list(),\n service.connections()\n ])\n\n const catalog = (Array.isArray(rawCatalog) ? rawCatalog : (rawCatalog as any)?.items || []) as Integration[]\n const connections = (Array.isArray(rawConnections) ? rawConnections : (rawConnections as any)?.items || []) as IntegrationConnection[]\n\n const bySource = new Map<string, IntegrationConnection[]>()\n for (const conn of connections) {\n const source = conn.source || conn.id\n if (!bySource.has(source)) bySource.set(source, [])\n bySource.get(source)!.push(conn)\n }\n\n return catalog.map(item => {\n const conns = bySource.get(item.id) || []\n return {\n ...item,\n connections: conns,\n connected: conns.some(c => c.connected),\n connectionCount: conns.filter(c => c.connected).length\n } as IntegrationDetail\n })\n },\n async status(source) {\n const conns = await service.connections()\n const items = (Array.isArray(conns) ? conns : (conns as any)?.items || []) as IntegrationConnection[]\n const filtered = items.filter(c => c.source === source && c.connected)\n return { connected: filtered.length > 0, connections: filtered }\n },\n async connect(source) {\n return http.request(accountBase, `/api/v1/accounts/integrations/${source}/initialize`, 'POST', {\n body: { __namespace: namespace }\n }) as Promise<any>\n },\n async disconnect(source, configurationId) {\n await http.request(accountBase, `/api/v1/accounts/integrations/${source}/remove`, 'POST', {\n body: { configurationId }\n })\n }\n }\n return service\n}\n\nfunction createOpenApiService(http: HttpClient, apiBase: string): OpenApiService {\n return {\n async get() {\n return http.request(apiBase, '/api/v1/config/openapi', 'GET') as Promise<any>\n }\n }\n}\n\nfunction createLogService(): LogService {\n return {\n info: (message, context) => console.log(`[Foundation] ${message}`, context ?? ''),\n warn: (message, context) => console.warn(`[Foundation] ${message}`, context ?? ''),\n error: (message, context) => console.error(`[Foundation] ${message}`, context ?? ''),\n event: (event, data) => console.log(`[Foundation Event] ${event}`, data ?? '')\n }\n}\n"],"mappings":"AASO,SAASA,EAAeC,EAAwC,CACrE,OAAIA,GAAM,WAAa,OAAkBA,EAAK,SAC1CA,GAAM,OAAS,OAAkBA,EAAK,KACnCA,CACT,CAKO,SAASC,EAAaC,EAAgBC,EAAsC,CACjF,IAAMC,EAAWD,GAAM,MAEvB,GAAIC,EAAU,CACZ,IAAIC,EAAUD,EAAS,SAAqB,gBACtCE,EAAUF,EAAS,QACzB,GAAIE,GAAS,OAAQ,CACnB,IAAMC,EAAiBD,EACpB,IAAIE,GAAKA,EAAE,MAAQ,GAAGA,EAAE,KAAK,KAAKA,EAAE,OAAO,GAAKA,EAAE,OAAO,EACzD,KAAK,IAAI,EACZH,EAAUA,EAAU,GAAGA,CAAO,IAAIE,CAAc,GAAKA,CACvD,CACA,OAAO,OAAO,OAAO,IAAI,MAAMF,CAAO,EAAG,CACvC,KAAMD,EAAS,KACf,KAAMA,EAAS,KACf,QAAAE,EACA,OAAAJ,CACF,CAAC,CACH,CAEA,IAAMO,EAAiBN,GAAM,MAAkC,SAAWA,GAAM,QAChF,OAAIM,EACK,OAAO,OAAO,IAAI,MAAMA,CAAuB,EAAG,CAAE,OAAAP,CAAO,CAAC,EAG9D,OAAO,OAAO,IAAI,MAAM,QAAQA,CAAM,EAAE,EAAG,CAAE,OAAAA,CAAO,CAAC,CAC9D,CASO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M,WAAWiD,EAAQK,EAAiB,CACxC,MAAM3D,EAAK,QAAQ8C,EAAa,iCAAiCQ,CAAM,UAAW,OAAQ,CACxF,KAAM,CAAE,gBAAAK,CAAgB,CAC1B,CAAC,CACH,CACF,EACA,OAAOZ,CACT,CAEA,SAAS3B,EAAqBpB,EAAkB2B,EAAiC,CAC/E,MAAO,CACL,MAAM,KAAM,CACV,OAAO3B,EAAK,QAAQ2B,EAAS,yBAA0B,KAAK,CAC9D,CACF,CACF,CAEA,SAASL,GAA+B,CACtC,MAAO,CACL,KAAM,CAACsC,EAASC,IAAY,QAAQ,IAAI,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EAChF,KAAM,CAACD,EAASC,IAAY,QAAQ,KAAK,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EACjF,MAAO,CAACD,EAASC,IAAY,QAAQ,MAAM,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EACnF,MAAO,CAACrC,EAAOY,IAAS,QAAQ,IAAI,sBAAsBZ,CAAK,GAAIY,GAAQ,EAAE,CAC/E,CACF","names":["unwrapResponse","json","extractError","status","body","errorObj","message","details","detailMessages","d","customMessage","createHttpClient","config","headers","token","request","baseUrl","path","method","options","hdrs","url","searchParams","key","value","qs","fetchOptions","response","rawFetch","providers","registerAuthProvider","name","factory","createAuthClient","config","createAuthService","client","user","listeners","notifyListeners","fn","refreshUser","authUser","options","email","password","metadata","code","newPassword","callback","idx","parseJwt","token","jwtPart","queryPart","parts","payloadStr","jwtPayload","value","key","apiBaseUrl","websocketBaseUrl","accountBaseUrl","err","message","createFoundation","options","configUrl","resolvedAppId","resolvedTenantId","envResponse","env","configHeaders","publicConfigResponse","rawPublicConfig","publicConfig","authConfig","authClient","createAuthClient","authService","createAuthService","apiBaseUrl","accountBaseUrl","apiUrls","token","claims","parseJwt","appId","tenantId","version","http","createHttpClient","backendConfig","err","mergedConfig","namespace","config","app","theme","provider","rest","db","createDbService","files","createFilesService","account","createAccountService","integration","createIntegrationService","openapi","createOpenApiService","log","createLogService","entityListeners","event","callback","idx","apiBase","entity","filters","limit","cursor","orderBy","orderDir","params","id","data","updates","fileData","uploadData","formData","key","value","s3Response","fileId","result","accountBase","service","rawCatalog","rawConnections","catalog","connections","bySource","conn","source","item","conns","c","filtered","configurationId","message","context"]}
1
+ {"version":3,"sources":["../src/http.ts","../src/auth.ts","../src/jwt.ts","../src/foundation.ts"],"sourcesContent":["/**\n * HTTP layer for Foundation API calls.\n * Handles request construction, response unwrapping, and error extraction.\n */\n\n/**\n * Unwrap backend response envelope.\n * The API wraps responses in { response: ... } or { data: ... }.\n */\nexport function unwrapResponse(json: Record<string, unknown>): unknown {\n if (json?.response !== undefined) return json.response\n if (json?.data !== undefined) return json.data\n return json\n}\n\n/**\n * Extract a meaningful error from a failed API response.\n */\nexport function extractError(status: number, body: Record<string, unknown>): Error {\n const errorObj = body?.error as Record<string, unknown> | undefined\n\n if (errorObj) {\n let message = errorObj.message as string || 'Unknown error'\n const details = errorObj.details as Array<{ field?: string; message?: string }> | undefined\n if (details?.length) {\n const detailMessages = details\n .map(d => d.field ? `${d.field}: ${d.message}` : d.message)\n .join(', ')\n message = message ? `${message} ${detailMessages}` : detailMessages\n }\n return Object.assign(new Error(message), {\n code: errorObj.code,\n type: errorObj.code,\n details,\n status\n })\n }\n\n const customMessage = (body?.data as Record<string, unknown>)?.message || body?.message\n if (customMessage) {\n return Object.assign(new Error(customMessage as string), { status })\n }\n\n return Object.assign(new Error(`HTTP ${status}`), { status })\n}\n\nexport interface HttpClientConfig {\n appId: string\n tenantId: string\n version: string\n getToken: () => Promise<string>\n}\n\nexport function createHttpClient(config: HttpClientConfig) {\n function headers(token: string): Record<string, string> {\n return {\n 'X-Foundation-Mvp-Application-Id': config.appId,\n 'X-Foundation-Mvp-Tenant-Id': config.tenantId,\n 'X-Foundation-Mvp-Application-Version': config.version,\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n }\n }\n\n async function request(\n baseUrl: string,\n path: string,\n method: string,\n options: { params?: Record<string, unknown>; body?: unknown } = {}\n ): Promise<unknown> {\n const token = await config.getToken()\n const hdrs = headers(token)\n\n let url = `${baseUrl}${path}`\n if (options.params) {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(options.params)) {\n if (value !== undefined && value !== null) {\n searchParams.set(key, String(value))\n }\n }\n const qs = searchParams.toString()\n if (qs) url += `?${qs}`\n }\n\n const fetchOptions: RequestInit = { method, headers: hdrs }\n if (options.body !== undefined) {\n fetchOptions.body = JSON.stringify(options.body)\n }\n\n const response = await fetch(url, fetchOptions)\n\n if (!response.ok) {\n let body: Record<string, unknown> = {}\n try { body = await response.json() } catch { /* no json body */ }\n throw extractError(response.status, body)\n }\n\n if (response.status === 204) return null\n\n const json = await response.json()\n return unwrapResponse(json as Record<string, unknown>)\n }\n\n /** Raw fetch with auth headers but no unwrapping (for S3 uploads etc.) */\n async function rawFetch(url: string, options: RequestInit = {}): Promise<Response> {\n return fetch(url, options)\n }\n\n return { request, rawFetch, headers }\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","/**\n * Auth core — provider registry and AuthService wrapper.\n * Provider implementations live in auth-auth0.ts and auth-cognito.ts.\n */\nimport type { AuthClient, AuthService, User } from './types'\n\nconst MAX_LISTENERS = 100\n\n// --- Provider registry ---\n\nconst providers = new Map<string, (config: Record<string, unknown>) => Promise<AuthClient>>()\n\nexport function registerAuthProvider(name: string, factory: (config: Record<string, unknown>) => Promise<AuthClient>) {\n providers.set(name, factory)\n}\n\n// Built-in \"none\" provider\nregisterAuthProvider('none', async () => ({\n login: async () => {},\n logout: async () => {},\n getUser: async () => undefined,\n getTokenSilently: async () => 'none',\n isAuthenticated: async () => true\n}))\n\nexport interface AuthProviderConfig {\n provider: string\n [key: string]: unknown\n}\n\nexport async function createAuthClient(config: AuthProviderConfig): Promise<AuthClient> {\n const factory = providers.get(config.provider)\n if (!factory) {\n throw new Error(\n `Auth provider \"${config.provider}\" not registered. ` +\n `Import \"foundation-sdk/${config.provider}\" to register it.`\n )\n }\n return factory(config)\n}\n\n// --- AuthService wrapper ---\n\nexport function createAuthService(client: AuthClient): AuthService & { _initUser(): Promise<void> } {\n let user: User | null = null\n const listeners: Array<(user: User | null) => void> = []\n\n function notifyListeners() {\n listeners.forEach(fn => { try { fn(user) } catch { /* */ } })\n }\n\n async function refreshUser() {\n const authUser = await client.getUser()\n user = authUser ? { id: authUser.id, email: authUser.email, name: authUser.name, picture: authUser.picture } : null\n }\n\n return {\n get user() { return user },\n get isAuthenticated() { return !!user },\n\n async getToken() {\n return client.getTokenSilently()\n },\n\n async login(options) {\n await client.login(options)\n await refreshUser()\n notifyListeners()\n },\n\n async logout(options) {\n await client.logout(options)\n user = null\n notifyListeners()\n },\n\n async signIn(email, password) {\n if (!client.signIn) throw new Error('signIn not supported by this auth provider')\n await client.signIn(email, password)\n await refreshUser()\n notifyListeners()\n },\n\n async signUp(email, password, metadata) {\n if (!client.signUp) throw new Error('signUp not supported by this auth provider')\n await client.signUp(email, password, metadata)\n },\n\n async forgotPassword(email) {\n if (!client.forgotPassword) throw new Error('forgotPassword not supported by this auth provider')\n await client.forgotPassword(email)\n },\n\n async resetPassword(code, newPassword) {\n if (!client.resetPassword) throw new Error('resetPassword not supported by this auth provider')\n await client.resetPassword(code, newPassword)\n },\n\n onChange(callback) {\n if (listeners.length >= MAX_LISTENERS) {\n console.warn('[Foundation SDK] Auth listener limit reached.')\n return () => {}\n }\n listeners.push(callback)\n return () => {\n const idx = listeners.indexOf(callback)\n if (idx > -1) listeners.splice(idx, 1)\n }\n },\n\n async _initUser() {\n const authenticated = await client.isAuthenticated()\n if (authenticated) await refreshUser()\n }\n }\n}\n","export interface JwtClaims {\n sub: string\n apiBaseUrl: string\n accountBaseUrl: string\n websocketBaseUrl: string\n userId: string\n namespace?: string\n}\n\nexport function parseJwt(token: string): JwtClaims {\n if (!token) {\n throw new Error('Token parsing failed: Missing auth token')\n }\n\n try {\n // Auth0 tokens can have query params appended: \"jwt?param=value\"\n const [jwtPart, queryPart] = token.split('?')\n\n const parts = jwtPart.split('.')\n if (parts.length !== 3) {\n throw new Error('Invalid JWT format')\n }\n\n const payloadStr = atob(parts[1])\n const jwtPayload = JSON.parse(payloadStr)\n\n // Merge query params if present\n if (queryPart) {\n const params = new URLSearchParams(queryPart)\n params.forEach((value, key) => {\n jwtPayload[key] = value\n })\n }\n\n const apiBaseUrl = jwtPayload['BaseApplication/apiBaseUrl']\n if (!apiBaseUrl) {\n throw new Error('Token missing apiBaseUrl')\n }\n\n const websocketBaseUrl = jwtPayload['BaseApplication/websocketBaseUrl'] || ''\n const accountBaseUrl = jwtPayload['BaseApplication/accountBaseUrl'] || apiBaseUrl\n\n return {\n sub: jwtPayload.sub || '',\n apiBaseUrl,\n accountBaseUrl,\n websocketBaseUrl,\n userId: jwtPayload['BaseApplication/userId'] || '',\n namespace: jwtPayload['BaseApplication/namespace']\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('Token')) {\n throw err\n }\n const message = err instanceof Error ? err.message : 'Failed to parse token'\n throw new Error(`Token parsing failed: ${message}`)\n }\n}\n","/**\n * Foundation SDK — typed API client for the Foundation platform.\n *\n * One input: a config URL. The SDK fetches it, discovers auth, API URLs,\n * features, plans, theme, connectors — everything. Self-configuring.\n */\nimport type {\n Foundation,\n FoundationConfig,\n FullConfig,\n AuthService,\n DbService,\n FilesService,\n AccountService,\n IntegrationService,\n Integration,\n IntegrationConnection,\n IntegrationDetail,\n OpenApiService,\n LogService,\n EntityChangeEvent,\n User\n} from './types'\nimport { createHttpClient, unwrapResponse, type HttpClient } from './http'\nimport { createAuthClient, createAuthService, type AuthProviderConfig } from './auth'\nimport { parseJwt } from './jwt'\n\nexport async function createFoundation(options: FoundationConfig): Promise<Foundation> {\n // 1. Resolve config URL — foundation-env.json wins if it exists (deployed env)\n let configUrl = options.configUrl\n let resolvedAppId = options.appId\n let resolvedTenantId = options.tenantId\n\n try {\n const envResponse = await fetch('/foundation-env.json')\n if (envResponse.ok) {\n const env = await envResponse.json()\n if (env.configUrl) {\n configUrl = env.configUrl\n resolvedAppId = env.applicationId || resolvedAppId\n resolvedTenantId = env.applicationTenant || resolvedTenantId\n }\n }\n } catch { /* no env file — use passed options */ }\n\n if (!configUrl) {\n throw new Error('No configUrl provided and /foundation-env.json not found')\n }\n\n // 2. Fetch public config\n const configHeaders: Record<string, string> = { 'Accept': 'application/json', 'Cache-Control': 'no-cache' }\n if (resolvedAppId) configHeaders['X-Foundation-Mvp-Application-Id'] = resolvedAppId\n if (resolvedTenantId) configHeaders['X-Foundation-Mvp-Tenant-Id'] = resolvedTenantId\n\n const publicConfigResponse = await fetch(configUrl, { headers: configHeaders })\n if (!publicConfigResponse.ok) {\n throw new Error(`Failed to fetch config: ${publicConfigResponse.statusText}`)\n }\n const rawPublicConfig = await publicConfigResponse.json()\n const publicConfig = rawPublicConfig.data ?? rawPublicConfig\n\n // 2. Set up auth\n const authConfig: AuthProviderConfig = publicConfig.auth || { provider: 'none' }\n let authClient: import('./types').AuthClient\n\n if (options.auth && typeof options.auth === 'function') {\n // Provider factory passed directly (e.g. cognitoAuth from foundation-sdk/cognito)\n authClient = await options.auth(authConfig)\n } else if (options.auth) {\n // Pre-built auth client instance\n authClient = options.auth as import('./types').AuthClient\n } else {\n // Auto-detect from config (requires provider to be registered via import)\n authClient = await createAuthClient(authConfig)\n }\n const authServiceRaw = createAuthService(authClient)\n const authService = authServiceRaw as AuthService & { _initUser(): Promise<void> }\n await authService._initUser()\n\n // 3. Determine API URLs\n let apiBaseUrl: string\n let accountBaseUrl: string\n\n if (options.baseUrl) {\n // Explicit override (e.g. '/api' with a dev proxy)\n apiBaseUrl = options.baseUrl\n accountBaseUrl = options.baseUrl\n } else if ((authConfig as Record<string, any>).apiUrls?.apiBaseUrl) {\n // API URLs from public config (no-auth mode or explicit)\n const apiUrls = (authConfig as Record<string, any>).apiUrls\n apiBaseUrl = apiUrls.apiBaseUrl\n accountBaseUrl = apiUrls.accountBaseUrl || apiBaseUrl\n } else {\n // API URLs from JWT token\n const token = await authClient.getTokenSilently()\n const claims = parseJwt(token)\n apiBaseUrl = claims.apiBaseUrl\n accountBaseUrl = claims.accountBaseUrl\n }\n\n // 4. Create HTTP client\n const appId = resolvedAppId || publicConfig.app?.id || publicConfig.tenant?.identifier || ''\n const tenantId = resolvedTenantId || publicConfig.tenant?.identifier || ''\n const version = publicConfig.app?.version || publicConfig.core?.version || '0.0.0'\n\n const http = createHttpClient({\n appId,\n tenantId,\n version,\n getToken: () => authClient.getTokenSilently()\n })\n\n // 5. Fetch backend config (authenticated)\n let backendConfig: Record<string, unknown> = {}\n try {\n const cfg = await http.request(apiBaseUrl, '/api/v1/config/init', 'GET')\n backendConfig = (cfg || {}) as Record<string, unknown>\n } catch (err) {\n console.warn('[Foundation SDK] Backend config fetch failed:', err)\n }\n\n // 6. Merge configs\n const mergedConfig = { ...publicConfig, ...backendConfig }\n\n // Determine namespace from JWT if available\n let namespace = ''\n try {\n const token = await authClient.getTokenSilently()\n if (token && token !== 'none') {\n const claims = parseJwt(token)\n namespace = claims.namespace || ''\n }\n } catch { /* no token yet */ }\n\n // 7. Build config service\n const config: FullConfig = {\n get app() {\n const app = mergedConfig.app as Record<string, unknown> || {}\n return {\n id: (app.id || appId) as string,\n name: (app.name || '') as string,\n version: (app.version || version) as string,\n environment: (app.environment || '') as string,\n ...app\n }\n },\n get features() { return (mergedConfig.features || {}) as Record<string, unknown> },\n get plans() { return (mergedConfig.plans || []) as unknown[] },\n get theme() {\n const theme = mergedConfig.theme as Record<string, unknown> || {}\n return {\n colors: (theme.colors || {}) as Record<string, string>,\n dark: (theme.dark || {}) as Record<string, string>,\n defaultColorScheme: theme.defaultColorScheme as string | undefined\n }\n },\n get connectors() { return (mergedConfig.connectors || {}) as Record<string, unknown> },\n get resources() { return (mergedConfig.resources || {}) as Record<string, string> },\n get auth() {\n const { provider, ...rest } = authConfig\n return { provider, ...rest } as { provider: string; [key: string]: unknown }\n },\n get raw() { return mergedConfig }\n }\n\n // 8. Build services\n const db = createDbService(http, apiBaseUrl)\n const files = createFilesService(http, apiBaseUrl, namespace)\n const account = createAccountService(http, accountBaseUrl)\n const integration = createIntegrationService(http, apiBaseUrl, accountBaseUrl, namespace)\n const openapi = createOpenApiService(http, apiBaseUrl)\n const log = createLogService()\n\n // Entity change listeners (WebSocket support is future)\n const entityListeners: Array<(event: EntityChangeEvent) => void> = []\n\n const foundation: Foundation = {\n get ready() { return Promise.resolve() },\n get isReady() { return true },\n auth: authService,\n db,\n files,\n integration,\n account,\n config,\n openapi,\n log,\n on(event, callback) {\n if (event === 'entity.changed') {\n entityListeners.push(callback)\n return () => {\n const idx = entityListeners.indexOf(callback)\n if (idx > -1) entityListeners.splice(idx, 1)\n }\n }\n return () => {}\n }\n }\n\n return foundation\n}\n\n// --- Service factories ---\n\nfunction createDbService(http: HttpClient, apiBase: string): DbService {\n return {\n async list(entity, options = {}) {\n const { filters, limit, cursor, orderBy, orderDir } = options\n const params: Record<string, unknown> = { ...filters }\n if (limit) params.limit = limit\n if (cursor) params.next = cursor\n if (orderBy) params.orderBy = orderBy\n if (orderDir) params.orderDir = orderDir\n return http.request(apiBase, `/api/v1/core/${entity}`, 'GET', { params }) as Promise<any>\n },\n async get(entity, id) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'GET', { params: { id } }) as Promise<any>\n },\n async create(entity, data) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'POST', { body: data }) as Promise<any>\n },\n async update(entity, id, updates) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'PUT', { body: { id, ...updates } }) as Promise<any>\n },\n async save(entity, data) {\n try {\n return await http.request(apiBase, `/api/v1/core/${entity}`, 'PUT', { body: data }) as Promise<any>\n } catch {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'POST', { body: data }) as Promise<any>\n }\n },\n async delete(entity, id) {\n await http.request(apiBase, `/api/v1/core/${entity}`, 'DELETE', { body: { id } })\n }\n }\n}\n\nfunction createFilesService(http: HttpClient, apiBase: string, namespace: string): FilesService {\n return {\n async initiate(options) {\n return http.request(apiBase, '/api/v1/core/upload', 'POST', {\n body: { ...options, __namespace: namespace }\n }) as Promise<any>\n },\n async upload(options) {\n let fileData: ArrayBuffer\n if (options.file instanceof ArrayBuffer) {\n fileData = options.file\n } else {\n fileData = await options.file.arrayBuffer()\n }\n\n const uploadData = await http.request(apiBase, '/api/v1/core/upload', 'POST', {\n body: { name: options.name, contentType: options.contentType, contentLength: fileData.byteLength, sha256: options.sha256, __namespace: namespace }\n }) as { id: string; name: string; signedUrl: string; signedData: Record<string, string> }\n\n if (!uploadData.signedUrl || !uploadData.signedData) {\n throw new Error('Missing signedUrl or signedData in response')\n }\n\n const formData = new FormData()\n Object.entries(uploadData.signedData).forEach(([key, value]) => {\n formData.append(key, value)\n })\n formData.append('file', new Blob([fileData], { type: options.contentType }), options.name)\n\n const s3Response = await fetch(uploadData.signedUrl, { method: 'POST', body: formData })\n if (s3Response.status !== 204) {\n throw new Error(`S3 upload failed: ${s3Response.status}`)\n }\n\n return { id: uploadData.id, name: uploadData.name, status: 'uploaded', s3UploadComplete: true }\n },\n async get(fileId) {\n return http.request(apiBase, '/api/v1/core/files', 'GET', {\n params: { id: fileId, __namespace: namespace }\n }) as Promise<any>\n },\n async delete(fileId) {\n await http.request(apiBase, `/api/v1/core/files/${fileId}`, 'DELETE')\n },\n async list(options = {}) {\n const params: Record<string, unknown> = { __namespace: namespace }\n if (options.limit) params.limit = options.limit\n if (options.cursor) params.cursor = options.cursor\n const result = await http.request(apiBase, '/api/v1/core/files', 'GET', { params }) as {\n items?: unknown[]; next?: string\n }\n return { items: result?.items || [], nextCursor: result?.next } as any\n }\n }\n}\n\nfunction createAccountService(http: HttpClient, accountBase: string): AccountService {\n return {\n async get() {\n return http.request(accountBase, '/api/v1/accounts/account', 'GET') as Promise<any>\n },\n async update(data) {\n await http.request(accountBase, '/api/v1/accounts/account', 'PUT', { body: { user: data } })\n },\n async usage() {\n return http.request(accountBase, '/api/v1/accounts/account/usage', 'GET') as Promise<any>\n },\n async resendVerification() {\n await http.request(accountBase, '/api/v1/accounts/account/resend-verification', 'POST')\n }\n }\n}\n\nfunction createIntegrationService(http: HttpClient, apiBase: string, accountBase: string, namespace: string): IntegrationService {\n const service: IntegrationService = {\n async list() {\n return http.request(apiBase, '/api/v1/config/connectors', 'GET') as Promise<any>\n },\n async connections() {\n return http.request(apiBase, '/api/v1/core/integrations', 'GET', {\n params: { query: 'default', __namespace: namespace }\n }) as Promise<any>\n },\n async all() {\n const [rawCatalog, rawConnections] = await Promise.all([\n service.list(),\n service.connections()\n ])\n\n const catalog = (Array.isArray(rawCatalog) ? rawCatalog : (rawCatalog as any)?.items || []) as Integration[]\n const connections = (Array.isArray(rawConnections) ? rawConnections : (rawConnections as any)?.items || []) as IntegrationConnection[]\n\n const bySource = new Map<string, IntegrationConnection[]>()\n for (const conn of connections) {\n const source = conn.source || conn.id\n if (!bySource.has(source)) bySource.set(source, [])\n bySource.get(source)!.push(conn)\n }\n\n return catalog.map(item => {\n const conns = bySource.get(item.id) || []\n return {\n ...item,\n connections: conns,\n connected: conns.some(c => c.connected),\n connectionCount: conns.filter(c => c.connected).length\n } as IntegrationDetail\n })\n },\n async status(source) {\n const conns = await service.connections()\n const items = (Array.isArray(conns) ? conns : (conns as any)?.items || []) as IntegrationConnection[]\n const filtered = items.filter(c => c.source === source && c.connected)\n return { connected: filtered.length > 0, connections: filtered }\n },\n async connect(source) {\n return http.request(accountBase, `/api/v1/accounts/integrations/${source}/initialize`, 'POST', {\n body: { __namespace: namespace }\n }) as Promise<any>\n },\n async disconnect(source, configurationId) {\n await http.request(accountBase, `/api/v1/accounts/integrations/${source}/remove`, 'POST', {\n body: { configurationId }\n })\n }\n }\n return service\n}\n\nfunction createOpenApiService(http: HttpClient, apiBase: string): OpenApiService {\n return {\n async get() {\n return http.request(apiBase, '/api/v1/config/openapi', 'GET') as Promise<any>\n }\n }\n}\n\nfunction createLogService(): LogService {\n return {\n info: (message, context) => console.log(`[Foundation] ${message}`, context ?? ''),\n warn: (message, context) => console.warn(`[Foundation] ${message}`, context ?? ''),\n error: (message, context) => console.error(`[Foundation] ${message}`, context ?? ''),\n event: (event, data) => console.log(`[Foundation Event] ${event}`, data ?? '')\n }\n}\n"],"mappings":"AASO,SAASA,EAAeC,EAAwC,CACrE,OAAIA,GAAM,WAAa,OAAkBA,EAAK,SAC1CA,GAAM,OAAS,OAAkBA,EAAK,KACnCA,CACT,CAKO,SAASC,EAAaC,EAAgBC,EAAsC,CACjF,IAAMC,EAAWD,GAAM,MAEvB,GAAIC,EAAU,CACZ,IAAIC,EAAUD,EAAS,SAAqB,gBACtCE,EAAUF,EAAS,QACzB,GAAIE,GAAS,OAAQ,CACnB,IAAMC,EAAiBD,EACpB,IAAIE,GAAKA,EAAE,MAAQ,GAAGA,EAAE,KAAK,KAAKA,EAAE,OAAO,GAAKA,EAAE,OAAO,EACzD,KAAK,IAAI,EACZH,EAAUA,EAAU,GAAGA,CAAO,IAAIE,CAAc,GAAKA,CACvD,CACA,OAAO,OAAO,OAAO,IAAI,MAAMF,CAAO,EAAG,CACvC,KAAMD,EAAS,KACf,KAAMA,EAAS,KACf,QAAAE,EACA,OAAAJ,CACF,CAAC,CACH,CAEA,IAAMO,EAAiBN,GAAM,MAAkC,SAAWA,GAAM,QAChF,OAAIM,EACK,OAAO,OAAO,IAAI,MAAMA,CAAuB,EAAG,CAAE,OAAAP,CAAO,CAAC,EAG9D,OAAO,OAAO,IAAI,MAAM,QAAQA,CAAM,EAAE,EAAG,CAAE,OAAAA,CAAO,CAAC,CAC9D,CASO,SAASQ,EAAiBC,EAA0B,CACzD,SAASC,EAAQC,EAAuC,CACtD,MAAO,CACL,kCAAmCF,EAAO,MAC1C,6BAA8BA,EAAO,SACrC,uCAAwCA,EAAO,QAC/C,eAAgB,mBAChB,cAAiB,UAAUE,CAAK,EAClC,CACF,CAEA,eAAeC,EACbC,EACAC,EACAC,EACAC,EAAgE,CAAC,EAC/C,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,CAAgB,CAC1B,CAAC,CACH,CACF,EACA,OAAOZ,CACT,CAEA,SAAS3B,EAAqBpB,EAAkB2B,EAAiC,CAC/E,MAAO,CACL,MAAM,KAAM,CACV,OAAO3B,EAAK,QAAQ2B,EAAS,yBAA0B,KAAK,CAC9D,CACF,CACF,CAEA,SAASL,GAA+B,CACtC,MAAO,CACL,KAAM,CAACsC,EAASC,IAAY,QAAQ,IAAI,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EAChF,KAAM,CAACD,EAASC,IAAY,QAAQ,KAAK,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EACjF,MAAO,CAACD,EAASC,IAAY,QAAQ,MAAM,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EACnF,MAAO,CAACrC,EAAOY,IAAS,QAAQ,IAAI,sBAAsBZ,CAAK,GAAIY,GAAQ,EAAE,CAC/E,CACF","names":["unwrapResponse","json","extractError","status","body","errorObj","message","details","detailMessages","d","customMessage","createHttpClient","config","headers","token","request","baseUrl","path","method","options","hdrs","url","searchParams","key","value","qs","fetchOptions","response","rawFetch","providers","registerAuthProvider","name","factory","createAuthClient","config","createAuthService","client","user","listeners","notifyListeners","fn","refreshUser","authUser","options","email","password","metadata","code","newPassword","callback","idx","parseJwt","token","jwtPart","queryPart","parts","payloadStr","jwtPayload","value","key","apiBaseUrl","websocketBaseUrl","accountBaseUrl","err","message","createFoundation","options","configUrl","resolvedAppId","resolvedTenantId","envResponse","env","configHeaders","publicConfigResponse","rawPublicConfig","publicConfig","authConfig","authClient","createAuthClient","authService","createAuthService","apiBaseUrl","accountBaseUrl","apiUrls","token","claims","parseJwt","appId","tenantId","version","http","createHttpClient","backendConfig","err","mergedConfig","namespace","config","app","theme","provider","rest","db","createDbService","files","createFilesService","account","createAccountService","integration","createIntegrationService","openapi","createOpenApiService","log","createLogService","entityListeners","event","callback","idx","apiBase","entity","filters","limit","cursor","orderBy","orderDir","params","id","data","updates","fileData","uploadData","formData","key","value","s3Response","fileId","result","accountBase","service","rawCatalog","rawConnections","catalog","connections","bySource","conn","source","item","conns","c","filtered","configurationId","message","context"]}