@mitralab.io/platform-sdk 1.0.8 → 1.0.9

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/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ ## Unreleased
6
+
7
+ - Make the SonarCloud job wait for the Quality Gate result.
8
+ - Align the public package metadata and ESM, CommonJS, and TypeScript artifacts.
9
+ - Add package shape checks and public tarball smoke coverage.
10
+ - Correct public imports and required configuration in documentation examples.
11
+ - Add the MIT license.
12
+
13
+ ## 1.0.8
14
+
15
+ - Share environment-neutral API contracts through `@mitralab.io/sdk-core`.
16
+ - Preserve the Platform SDK 1.x browser authentication and entity facade.
17
+ - Validate redirects, API errors, sensitive-value redaction, and package consumers.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mitra Platform
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -3,197 +3,173 @@
3
3
  [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=mitra-platform-sdk&metric=alert_status&token=28d7be14b66d6f88d706347e2418af5ea39ab3e9)](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
4
4
  [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=mitra-platform-sdk&metric=coverage&token=28d7be14b66d6f88d706347e2418af5ea39ab3e9)](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
5
5
 
6
- SDK JavaScript/TypeScript para apps criados na plataforma Mitra. O código gerado pelo Code Studio usa este pacote para autenticar usuários, acessar entidades do Data Manager, executar server functions, rodar custom queries e chamar integrações.
6
+ JavaScript and TypeScript SDK for browser applications built on the Mitra Platform. Applications generated by Code Studio use this package to authenticate users, access Data Manager entities, execute Server Functions and custom queries, and call integrations.
7
7
 
8
- O transporte de browser usa apenas Web APIs padrão (`fetch`, `localStorage`, `URL`, `Proxy`). Os contratos e módulos comuns vêm de `@mitralab.io/sdk-core`, sem trazer autenticação de browser para o core.
8
+ The browser transport uses standard Web APIs only: `fetch`, `localStorage`, `URL`, and `Proxy`. Shared contracts and API modules come from `@mitralab.io/sdk-core`, without bringing browser authentication into the Core package.
9
9
 
10
- ## O Que a SDK Entrega
11
-
12
- - Client único criado por `createClient`.
13
- - Auth com login, cadastro, refresh token, logout e estado em `localStorage`.
14
- - CRUD dinâmico em tabelas via `mitra.entities.<TableName>`.
15
- - Execução de server functions publicadas.
16
- - Execução de custom queries.
17
- - Proxy de integrações e resources com credential injection no servidor.
18
- - Tipos TypeScript exportados para os contratos principais.
19
-
20
- ## Instalação
10
+ ## Installation
21
11
 
22
12
  ```bash
23
13
  npm install @mitralab.io/platform-sdk
24
14
  ```
25
15
 
26
- ## Quick Start
16
+ Node.js 18 or newer is required for development and server-side tooling. The runtime application must provide the browser Web APIs used by the SDK.
17
+
18
+ ## Quick start
27
19
 
28
20
  ```typescript
29
- import { createClient } from '@mitralab.io/platform-sdk';
21
+ import { createClient } from "@mitralab.io/platform-sdk"
30
22
 
31
23
  export const mitra = createClient({
32
24
  appId: import.meta.env.VITE_MITRA_APP_ID,
33
25
  apiUrl: import.meta.env.VITE_MITRA_API_URL,
34
26
  onError: (error) => console.error(error.status, error.code, error.message),
35
- });
27
+ })
36
28
 
37
- await mitra.init();
29
+ await mitra.init()
38
30
  ```
39
31
 
40
- `init()` resolve a configuração pública do app no Code Studio, incluindo `dataSourceId` e `allowSignup`. Chame no boot da aplicação antes de usar `entities`, `queries` ou fluxo de cadastro.
32
+ `init()` resolves the application's public Code Studio configuration, including `dataSourceId` and `allowSignup`. Call it during application startup before using entities, custom queries, or sign-up.
41
33
 
42
- ## Configuração
34
+ ## Configuration
43
35
 
44
- | Campo | Obrigatório | Uso |
45
- | --------- | ----------- | ---------------------------------- |
46
- | `appId` | sim | ID do app publicado no Code Studio |
47
- | `apiUrl` | sim | URL base do Kong/API da plataforma |
48
- | `onError` | não | callback global para erros de API |
36
+ | Field | Required | Description |
37
+ |---|---|---|
38
+ | `appId` | yes | ID of the published Code Studio application. |
39
+ | `apiUrl` | yes | Base URL of the Mitra API gateway. |
40
+ | `onError` | no | Global callback for API errors. |
49
41
 
50
- O client deriva os endpoints dos serviços a partir de `apiUrl`: `/iam`, `/data-manager`, `/functions`, `/integration` e `/code-studio`.
42
+ The client derives service endpoints from `apiUrl`: `/iam`, `/data-manager`, `/functions`, `/integration`, and `/code-studio`.
51
43
 
52
- ## Estrutura de Arquivos
53
-
54
- ```text
55
- src/
56
- ├── client.ts # createClient, composição dos módulos e init
57
- ├── modules/ # auth de browser e fachadas compatíveis com a API 1.x
58
- ├── utils/http-client # fetch wrapper, auth header, retry 401 e MitraApiError
59
- └── index.ts # exports públicos
60
- ```
44
+ ## Boundary
61
45
 
62
- `@mitralab.io/sdk-core` concentra entities, queries, Functions, integration, `auth.me`, paths seguros e validação estrutural de respostas. A Platform SDK continua responsável por login, cadastro, refresh, `localStorage`, listeners e o retry único após refresh em resposta `401`.
46
+ The Platform SDK owns:
63
47
 
64
- ## Módulos
48
+ - browser login, sign-up, logout, and session refresh
49
+ - session persistence in `localStorage`
50
+ - auth-state listeners
51
+ - one retry after a successful token refresh on a `401` response
52
+ - browser HTTP transport and public application initialization
65
53
 
66
- | Módulo | Uso |
67
- | ------------- | --------------------------------------------------------------------------------------- |
68
- | `auth` | `signIn`, `signUp`, `signOut`, `refreshSession`, `me`, `checkAuth`, `onAuthStateChange` |
69
- | `entities` | CRUD dinâmico por tabela, filtro, paginação, bulk create e deleteMany |
70
- | `functions` | disparo de server function por ID com a semântica assíncrona da API 1.x |
71
- | `queries` | execução de custom query por ID com parâmetros |
72
- | `integration` | execução de integration resource ou proxy direto por config |
54
+ `@mitralab.io/sdk-core` owns the shared entities, custom queries, Functions, integrations, `auth.me`, safe paths, and structural response validation. Server Function code should use `@mitralab.io/functions-sdk` instead of this browser SDK.
73
55
 
74
- ## Auth
56
+ ## Authentication
75
57
 
76
58
  ```typescript
77
59
  const user = await mitra.auth.signIn({
78
- email: 'user@example.com',
79
- password: 'password123',
80
- });
60
+ email: "user@example.com",
61
+ password: "password123",
62
+ })
81
63
 
82
64
  const unsubscribe = mitra.auth.onAuthStateChange((currentUser) => {
83
- console.log(currentUser?.email);
84
- });
65
+ console.log(currentUser?.email)
66
+ })
85
67
 
86
- mitra.auth.signOut('/login');
87
- unsubscribe();
68
+ mitra.auth.signOut("/login")
69
+ unsubscribe()
88
70
  ```
89
71
 
90
- Estado de auth é persistido no `localStorage` com chave `mitra_auth_{appId}`. Em resposta `401`, o SDK tenta `refreshSession()` uma vez e repete a request.
72
+ Authentication state is stored under `mitra_auth_{appId}`. When an API request returns `401`, the SDK attempts `refreshSession()` once and repeats the request only when refresh succeeds.
91
73
 
92
74
  ## Entities
93
75
 
94
76
  ```typescript
95
77
  type Task = {
96
- id: string;
97
- title: string;
98
- status: 'pending' | 'done';
99
- };
78
+ id: string
79
+ title: string
80
+ status: "pending" | "done"
81
+ }
100
82
 
101
- const tasks = await mitra.entities.getTable<Task>('Task').list({
102
- sort: '-created_at',
83
+ const tasks = await mitra.entities.getTable<Task>("Task").list({
84
+ sort: "-created_at",
103
85
  limit: 10,
104
- fields: ['id', 'title', 'status'],
105
- });
86
+ fields: ["id", "title", "status"],
87
+ })
106
88
 
107
- const pending = await mitra.entities.Task.filter({ status: 'pending' });
108
- const created = await mitra.entities.Task.create({ title: 'New task' });
109
- await mitra.entities.Task.update(created.id, { status: 'done' });
110
- await mitra.entities.Task.delete(created.id);
89
+ const pending = await mitra.entities.Task.filter({ status: "pending" })
90
+ const created = await mitra.entities.Task.create({ title: "New task" })
91
+ await mitra.entities.Task.update(created.id, { status: "done" })
92
+ await mitra.entities.Task.delete(created.id)
111
93
  ```
112
94
 
113
- Table names são case-sensitive e precisam bater com o nome da tabela no Data Manager.
114
-
115
- Records usam `/api/v1/tables/{table}/records`. O app e o tenant vêm do contexto autenticado, não do `dataSourceId` no path.
95
+ Table names are case-sensitive and must match the Data Manager table name. Record operations use `/api/v1/tables/{table}/records`. Application and tenant scope come from the authenticated context, not from a data source in the path.
116
96
 
117
- ## Functions
97
+ ## Server Functions
118
98
 
119
99
  ```typescript
120
- const execution = await mitra.functions.execute('function-id', {
121
- orderId: 'order-123',
122
- });
100
+ const execution = await mitra.functions.execute("function-id", {
101
+ orderId: "order-123",
102
+ })
123
103
 
124
- console.log(execution.id, execution.status);
104
+ console.log(execution.id, execution.status)
125
105
  ```
126
106
 
127
- Na API 1.x, `execute` não envia `X-Invocation-Type`. O serviço usa o default assíncrono e devolve a execução criada, normalmente com status `PENDING`; a chamada não espera a Function terminar.
107
+ The Platform SDK 1.x `execute` method keeps the existing asynchronous API behavior. It does not send `X-Invocation-Type`, so the Functions service applies its default and returns the created execution, normally with `PENDING` status.
128
108
 
129
- ## Queries
109
+ ## Custom queries
130
110
 
131
111
  ```typescript
132
- const result = await mitra.queries.execute('query-id', {
133
- status: 'active',
134
- });
112
+ const result = await mitra.queries.execute("query-id", {
113
+ status: "active",
114
+ })
135
115
 
136
- console.log(result.rows, result.affectedRows);
116
+ console.log(result.rows, result.affectedRows)
137
117
  ```
138
118
 
139
- ## Integration
119
+ ## Integrations
140
120
 
141
- Resource pré-definido:
121
+ Execute a predefined resource:
142
122
 
143
123
  ```typescript
144
- const result = await mitra.integration.executeResource('resource-id', {
145
- descricao: 'Notebook',
124
+ const result = await mitra.integration.executeResource("resource-id", {
125
+ description: "Notebook",
146
126
  limit: 10,
147
- });
127
+ })
148
128
  ```
149
129
 
150
- Proxy direto por config:
130
+ Or execute an integration config directly:
151
131
 
152
132
  ```typescript
153
- const result = await mitra.integration.execute('config-id', {
154
- method: 'GET',
155
- endpoint: '/users',
156
- queryParams: { limit: '10' },
157
- });
133
+ const result = await mitra.integration.execute("config-id", {
134
+ method: "GET",
135
+ endpoint: "/users",
136
+ queryParams: { limit: "10" },
137
+ })
158
138
 
159
- console.log(result.status, result.body);
139
+ console.log(result.status, result.body)
160
140
  ```
161
141
 
162
- ## Erros
142
+ Integration credentials are injected by the Integration service. Do not pass provider credentials through browser input.
163
143
 
164
- Erros de API lançam `MitraApiError`:
144
+ ## Errors and request behavior
145
+
146
+ API failures throw `MitraApiError`:
165
147
 
166
148
  ```typescript
167
- import { MitraApiError } from '@mitralab.io/platform-sdk';
149
+ import { MitraApiError } from "@mitralab.io/platform-sdk"
168
150
 
169
151
  try {
170
- await mitra.entities.Task.get('missing-id');
152
+ await mitra.entities.Task.get("missing-id")
171
153
  } catch (error) {
172
154
  if (error instanceof MitraApiError) {
173
- console.error(error.status, error.code, error.message);
155
+ console.error(error.status, error.code, error.message)
174
156
  }
175
157
  }
176
158
  ```
177
159
 
178
- O transporte não segue redirects HTTP. Respostas 307, 308 ou respostas
179
- marcadas como redirecionadas falham sem replay. A única repetição automática é
180
- a tentativa única após refresh bem-sucedido em resposta 401.
160
+ The transport refuses HTTP redirects. Statuses `307` and `308`, opaque redirects, and responses already marked as redirected fail without replay. The only automatic replay is the single request attempted after a successful session refresh on `401`.
181
161
 
182
- Antes de construir `MitraApiError`, a SDK remove o token usado na tentativa e
183
- qualquer credencial no formato `Bearer` de `message`, `code` e `details`,
184
- percorrendo recursivamente valores, arrays e chaves de objetos.
162
+ Before constructing `MitraApiError`, the SDK recursively redacts the token used by the request and credentials in `Bearer` format from the error message, code, details, arrays, values, and object keys.
185
163
 
186
- ## Desenvolvimento
164
+ ## Development
187
165
 
188
166
  ```bash
189
167
  npm install
190
- npm run build
191
- npm run lint
192
- npm test
168
+ npm run check
193
169
  ```
194
170
 
195
- `@mitralab.io/sdk-core@0.1.0` é resolvido pelo registry público do npm e fica
196
- travado por integridade no `package-lock.json`. Não substitua a dependência por
197
- `file:` ou tarball local.
171
+ `@mitralab.io/sdk-core@0.1.0` is resolved from the public npm registry and locked by integrity in `package-lock.json`. Do not replace it with a `file:` dependency or a local tarball.
172
+
173
+ The build produces ESM, CommonJS, `.d.ts`, and `.d.cts` artifacts. Package checks inspect the public tarball with Are The Types Wrong, install it into an isolated consumer, and validate ESM, CommonJS, and TypeScript resolution.
198
174
 
199
- Build gera CommonJS, ESM e tipos TypeScript em `dist/`.
175
+ See [CHANGELOG.md](CHANGELOG.md) for release history and [LICENSE](LICENSE) for license terms.
@@ -1,5 +1,32 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ MitraApiError: () => MitraApiError,
24
+ createClient: () => createClient
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
1
28
  // src/client.ts
2
- import { encodePathSegment, expectObject } from "@mitralab.io/sdk-core";
29
+ var import_sdk_core6 = require("@mitralab.io/sdk-core");
3
30
 
4
31
  // src/utils/http-client.ts
5
32
  var bearerCredentialPattern = /(Bearer\s+)\S+/gi;
@@ -27,6 +54,16 @@ function asErrorPayload(value) {
27
54
  function optionalString(value) {
28
55
  return typeof value === "string" ? value : void 0;
29
56
  }
57
+ function buildRequestUrl(baseUrl, path, params) {
58
+ const url = `${baseUrl}${path}`;
59
+ if (!params) return url;
60
+ const searchParams = new URLSearchParams();
61
+ Object.entries(params).forEach(([key, value]) => {
62
+ if (value !== void 0) searchParams.append(key, String(value));
63
+ });
64
+ const queryString = searchParams.toString();
65
+ return queryString ? `${url}?${queryString}` : url;
66
+ }
30
67
  var HttpClient = class {
31
68
  baseUrl;
32
69
  tokenGetter;
@@ -65,19 +102,7 @@ var HttpClient = class {
65
102
  */
66
103
  async request(path, options = {}) {
67
104
  const { method = "GET", body, headers = {}, params, isRetry } = options;
68
- let url = `${this.baseUrl}${path}`;
69
- if (params) {
70
- const searchParams = new URLSearchParams();
71
- Object.entries(params).forEach(([key, value]) => {
72
- if (value !== void 0) {
73
- searchParams.append(key, String(value));
74
- }
75
- });
76
- const queryString = searchParams.toString();
77
- if (queryString) {
78
- url += `?${queryString}`;
79
- }
80
- }
105
+ const url = buildRequestUrl(this.baseUrl, path, params);
81
106
  const requestHeaders = {
82
107
  "Content-Type": "application/json",
83
108
  ...this.defaultHeaders,
@@ -205,7 +230,7 @@ var coreErrors = {
205
230
  };
206
231
 
207
232
  // src/modules/auth.ts
208
- import { createAuthModule } from "@mitralab.io/sdk-core";
233
+ var import_sdk_core = require("@mitralab.io/sdk-core");
209
234
  var AuthModule = class {
210
235
  appId;
211
236
  _currentUser = null;
@@ -222,7 +247,7 @@ var AuthModule = class {
222
247
  this.storageKey = `mitra_auth_${appId}`;
223
248
  this.publicClient = new HttpClient({ baseUrl: iamBaseUrl, getToken: () => null });
224
249
  this.authedClient = new HttpClient({ baseUrl: iamBaseUrl, getToken: () => this.#accessToken });
225
- this.currentUserApi = createAuthModule(this.authedClient, coreErrors);
250
+ this.currentUserApi = (0, import_sdk_core.createAuthModule)(this.authedClient, coreErrors);
226
251
  this.loadFromStorage();
227
252
  }
228
253
  /** The currently authenticated user, or null. */
@@ -517,14 +542,11 @@ var AuthModule = class {
517
542
  };
518
543
 
519
544
  // src/modules/entities.ts
520
- import {
521
- createEntitiesModule
522
- } from "@mitralab.io/sdk-core";
545
+ var import_sdk_core2 = require("@mitralab.io/sdk-core");
523
546
  var EntitiesModule = class _EntitiesModule {
524
- constructor(httpClient, dataSourceId) {
547
+ constructor(httpClient, _dataSourceId) {
525
548
  this.httpClient = httpClient;
526
- void dataSourceId;
527
- this.core = createEntitiesModule(httpClient, coreErrors);
549
+ this.core = (0, import_sdk_core2.createEntitiesModule)(httpClient, coreErrors);
528
550
  }
529
551
  core;
530
552
  static createProxy(httpClient, dataSourceId) {
@@ -542,9 +564,8 @@ var EntitiesModule = class _EntitiesModule {
542
564
  * Preserved for Platform SDK 1.x compatibility.
543
565
  * Records now resolve the app from authenticated context instead of a data source path.
544
566
  */
545
- setDataSourceId(dataSourceId) {
546
- void dataSourceId;
547
- this.core = createEntitiesModule(this.httpClient, coreErrors);
567
+ setDataSourceId(_dataSourceId) {
568
+ this.core = (0, import_sdk_core2.createEntitiesModule)(this.httpClient, coreErrors);
548
569
  }
549
570
  getTable(tableName) {
550
571
  return this.core.getTable(tableName);
@@ -552,13 +573,11 @@ var EntitiesModule = class _EntitiesModule {
552
573
  };
553
574
 
554
575
  // src/modules/functions.ts
555
- import {
556
- createFunctionsModule
557
- } from "@mitralab.io/sdk-core";
576
+ var import_sdk_core3 = require("@mitralab.io/sdk-core");
558
577
  var FunctionsModule = class {
559
578
  core;
560
579
  constructor(httpClient) {
561
- this.core = createFunctionsModule(httpClient, { emptyInput: "omit-body" }, coreErrors);
580
+ this.core = (0, import_sdk_core3.createFunctionsModule)(httpClient, { emptyInput: "omit-body" }, coreErrors);
562
581
  }
563
582
  /**
564
583
  * Executes a Function using the Platform SDK 1.x server-default invocation semantics.
@@ -576,13 +595,11 @@ var FunctionsModule = class {
576
595
  };
577
596
 
578
597
  // src/modules/integration.ts
579
- import {
580
- createIntegrationModule
581
- } from "@mitralab.io/sdk-core";
598
+ var import_sdk_core4 = require("@mitralab.io/sdk-core");
582
599
  var IntegrationModule = class {
583
600
  core;
584
601
  constructor(httpClient) {
585
- this.core = createIntegrationModule(httpClient, coreErrors);
602
+ this.core = (0, import_sdk_core4.createIntegrationModule)(httpClient, coreErrors);
586
603
  }
587
604
  executeResource(resourceId, params) {
588
605
  return this.core.executeResource(resourceId, params);
@@ -593,14 +610,12 @@ var IntegrationModule = class {
593
610
  };
594
611
 
595
612
  // src/modules/queries.ts
596
- import {
597
- createQueriesModule
598
- } from "@mitralab.io/sdk-core";
613
+ var import_sdk_core5 = require("@mitralab.io/sdk-core");
599
614
  var QueriesModule = class {
600
615
  dataSourceId = "";
601
616
  core;
602
617
  constructor(httpClient) {
603
- this.core = createQueriesModule(httpClient, () => this.dataSourceId, coreErrors);
618
+ this.core = (0, import_sdk_core5.createQueriesModule)(httpClient, () => this.dataSourceId, coreErrors);
604
619
  }
605
620
  /** Called by `client.init()` to set the app's resolved data source. */
606
621
  setDataSourceId(dataSourceId) {
@@ -614,7 +629,7 @@ var QueriesModule = class {
614
629
 
615
630
  // src/client.ts
616
631
  function expectAppInfoResponse(value) {
617
- const response = expectObject(
632
+ const response = (0, import_sdk_core6.expectObject)(
618
633
  value,
619
634
  "App info response",
620
635
  coreErrors
@@ -679,7 +694,7 @@ function createClient(config) {
679
694
  });
680
695
  const appInfo = expectAppInfoResponse(
681
696
  await publicClient.get(
682
- `/api/v1/apps/${encodePathSegment(appId, "appId", coreErrors)}/info`
697
+ `/api/v1/apps/${(0, import_sdk_core6.encodePathSegment)(appId, "appId", coreErrors)}/info`
683
698
  )
684
699
  );
685
700
  entitiesModule.setDataSourceId(appInfo.dataSourceId);
@@ -700,7 +715,8 @@ function createClient(config) {
700
715
  config
701
716
  };
702
717
  }
703
- export {
718
+ // Annotate the CommonJS export names for ESM import in node:
719
+ 0 && (module.exports = {
704
720
  MitraApiError,
705
721
  createClient
706
- };
722
+ });
@@ -376,13 +376,13 @@ declare class AuthModule {
376
376
  declare class EntitiesModule {
377
377
  private readonly httpClient;
378
378
  private core;
379
- constructor(httpClient: HttpClient, dataSourceId: string);
379
+ constructor(httpClient: HttpClient, _dataSourceId: string);
380
380
  static createProxy(httpClient: HttpClient, dataSourceId: string): EntitiesModule;
381
381
  /**
382
382
  * Preserved for Platform SDK 1.x compatibility.
383
383
  * Records now resolve the app from authenticated context instead of a data source path.
384
384
  */
385
- setDataSourceId(dataSourceId: string): void;
385
+ setDataSourceId(_dataSourceId: string): void;
386
386
  getTable<T = Record<string, unknown>>(tableName: string): EntityTable<T>;
387
387
  }
388
388
  type EntitiesProxy = EntitiesModule & {
@@ -496,6 +496,7 @@ interface MitraClientConfig {
496
496
  * ```typescript
497
497
  * const mitra = createClient({
498
498
  * appId: 'your-app-id',
499
+ * apiUrl: 'https://api.example.com',
499
500
  * onError: (error) => toast.error(error.message),
500
501
  * });
501
502
  * ```
@@ -509,6 +510,7 @@ interface MitraClientConfig {
509
510
  * ```typescript
510
511
  * const mitra = createClient({
511
512
  * appId: 'your-app-id',
513
+ * apiUrl: 'https://api.example.com',
512
514
  * });
513
515
  *
514
516
  * // Initialize (resolves app config automatically)
@@ -535,7 +537,10 @@ interface MitraClient {
535
537
  *
536
538
  * @example
537
539
  * ```typescript
538
- * const mitra = createClient({ appId: 'your-app-id' });
540
+ * const mitra = createClient({
541
+ * appId: 'your-app-id',
542
+ * apiUrl: 'https://api.example.com',
543
+ * });
539
544
  * await mitra.init();
540
545
  * ```
541
546
  */
@@ -628,7 +633,7 @@ interface MitraClient {
628
633
  *
629
634
  * @example
630
635
  * ```typescript
631
- * import { createClient } from 'mitra-platform-sdk';
636
+ * import { createClient } from '@mitralab.io/platform-sdk';
632
637
  *
633
638
  * const mitra = createClient({
634
639
  * appId: import.meta.env.VITE_MITRA_APP_ID,
@@ -646,7 +651,7 @@ interface MitraClient {
646
651
  * ```typescript
647
652
  * // Export as singleton for use throughout your app
648
653
  * // src/api/mitraClient.ts
649
- * import { createClient } from 'mitra-platform-sdk';
654
+ * import { createClient } from '@mitralab.io/platform-sdk';
650
655
  *
651
656
  * export const mitra = createClient({
652
657
  * appId: import.meta.env.VITE_MITRA_APP_ID,
package/dist/index.d.ts CHANGED
@@ -376,13 +376,13 @@ declare class AuthModule {
376
376
  declare class EntitiesModule {
377
377
  private readonly httpClient;
378
378
  private core;
379
- constructor(httpClient: HttpClient, dataSourceId: string);
379
+ constructor(httpClient: HttpClient, _dataSourceId: string);
380
380
  static createProxy(httpClient: HttpClient, dataSourceId: string): EntitiesModule;
381
381
  /**
382
382
  * Preserved for Platform SDK 1.x compatibility.
383
383
  * Records now resolve the app from authenticated context instead of a data source path.
384
384
  */
385
- setDataSourceId(dataSourceId: string): void;
385
+ setDataSourceId(_dataSourceId: string): void;
386
386
  getTable<T = Record<string, unknown>>(tableName: string): EntityTable<T>;
387
387
  }
388
388
  type EntitiesProxy = EntitiesModule & {
@@ -496,6 +496,7 @@ interface MitraClientConfig {
496
496
  * ```typescript
497
497
  * const mitra = createClient({
498
498
  * appId: 'your-app-id',
499
+ * apiUrl: 'https://api.example.com',
499
500
  * onError: (error) => toast.error(error.message),
500
501
  * });
501
502
  * ```
@@ -509,6 +510,7 @@ interface MitraClientConfig {
509
510
  * ```typescript
510
511
  * const mitra = createClient({
511
512
  * appId: 'your-app-id',
513
+ * apiUrl: 'https://api.example.com',
512
514
  * });
513
515
  *
514
516
  * // Initialize (resolves app config automatically)
@@ -535,7 +537,10 @@ interface MitraClient {
535
537
  *
536
538
  * @example
537
539
  * ```typescript
538
- * const mitra = createClient({ appId: 'your-app-id' });
540
+ * const mitra = createClient({
541
+ * appId: 'your-app-id',
542
+ * apiUrl: 'https://api.example.com',
543
+ * });
539
544
  * await mitra.init();
540
545
  * ```
541
546
  */
@@ -628,7 +633,7 @@ interface MitraClient {
628
633
  *
629
634
  * @example
630
635
  * ```typescript
631
- * import { createClient } from 'mitra-platform-sdk';
636
+ * import { createClient } from '@mitralab.io/platform-sdk';
632
637
  *
633
638
  * const mitra = createClient({
634
639
  * appId: import.meta.env.VITE_MITRA_APP_ID,
@@ -646,7 +651,7 @@ interface MitraClient {
646
651
  * ```typescript
647
652
  * // Export as singleton for use throughout your app
648
653
  * // src/api/mitraClient.ts
649
- * import { createClient } from 'mitra-platform-sdk';
654
+ * import { createClient } from '@mitralab.io/platform-sdk';
650
655
  *
651
656
  * export const mitra = createClient({
652
657
  * appId: import.meta.env.VITE_MITRA_APP_ID,
package/dist/index.js CHANGED
@@ -1,32 +1,5 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- MitraApiError: () => MitraApiError,
24
- createClient: () => createClient
25
- });
26
- module.exports = __toCommonJS(index_exports);
27
-
28
1
  // src/client.ts
29
- var import_sdk_core6 = require("@mitralab.io/sdk-core");
2
+ import { encodePathSegment, expectObject } from "@mitralab.io/sdk-core";
30
3
 
31
4
  // src/utils/http-client.ts
32
5
  var bearerCredentialPattern = /(Bearer\s+)\S+/gi;
@@ -54,6 +27,16 @@ function asErrorPayload(value) {
54
27
  function optionalString(value) {
55
28
  return typeof value === "string" ? value : void 0;
56
29
  }
30
+ function buildRequestUrl(baseUrl, path, params) {
31
+ const url = `${baseUrl}${path}`;
32
+ if (!params) return url;
33
+ const searchParams = new URLSearchParams();
34
+ Object.entries(params).forEach(([key, value]) => {
35
+ if (value !== void 0) searchParams.append(key, String(value));
36
+ });
37
+ const queryString = searchParams.toString();
38
+ return queryString ? `${url}?${queryString}` : url;
39
+ }
57
40
  var HttpClient = class {
58
41
  baseUrl;
59
42
  tokenGetter;
@@ -92,19 +75,7 @@ var HttpClient = class {
92
75
  */
93
76
  async request(path, options = {}) {
94
77
  const { method = "GET", body, headers = {}, params, isRetry } = options;
95
- let url = `${this.baseUrl}${path}`;
96
- if (params) {
97
- const searchParams = new URLSearchParams();
98
- Object.entries(params).forEach(([key, value]) => {
99
- if (value !== void 0) {
100
- searchParams.append(key, String(value));
101
- }
102
- });
103
- const queryString = searchParams.toString();
104
- if (queryString) {
105
- url += `?${queryString}`;
106
- }
107
- }
78
+ const url = buildRequestUrl(this.baseUrl, path, params);
108
79
  const requestHeaders = {
109
80
  "Content-Type": "application/json",
110
81
  ...this.defaultHeaders,
@@ -232,7 +203,7 @@ var coreErrors = {
232
203
  };
233
204
 
234
205
  // src/modules/auth.ts
235
- var import_sdk_core = require("@mitralab.io/sdk-core");
206
+ import { createAuthModule } from "@mitralab.io/sdk-core";
236
207
  var AuthModule = class {
237
208
  appId;
238
209
  _currentUser = null;
@@ -249,7 +220,7 @@ var AuthModule = class {
249
220
  this.storageKey = `mitra_auth_${appId}`;
250
221
  this.publicClient = new HttpClient({ baseUrl: iamBaseUrl, getToken: () => null });
251
222
  this.authedClient = new HttpClient({ baseUrl: iamBaseUrl, getToken: () => this.#accessToken });
252
- this.currentUserApi = (0, import_sdk_core.createAuthModule)(this.authedClient, coreErrors);
223
+ this.currentUserApi = createAuthModule(this.authedClient, coreErrors);
253
224
  this.loadFromStorage();
254
225
  }
255
226
  /** The currently authenticated user, or null. */
@@ -544,12 +515,13 @@ var AuthModule = class {
544
515
  };
545
516
 
546
517
  // src/modules/entities.ts
547
- var import_sdk_core2 = require("@mitralab.io/sdk-core");
518
+ import {
519
+ createEntitiesModule
520
+ } from "@mitralab.io/sdk-core";
548
521
  var EntitiesModule = class _EntitiesModule {
549
- constructor(httpClient, dataSourceId) {
522
+ constructor(httpClient, _dataSourceId) {
550
523
  this.httpClient = httpClient;
551
- void dataSourceId;
552
- this.core = (0, import_sdk_core2.createEntitiesModule)(httpClient, coreErrors);
524
+ this.core = createEntitiesModule(httpClient, coreErrors);
553
525
  }
554
526
  core;
555
527
  static createProxy(httpClient, dataSourceId) {
@@ -567,9 +539,8 @@ var EntitiesModule = class _EntitiesModule {
567
539
  * Preserved for Platform SDK 1.x compatibility.
568
540
  * Records now resolve the app from authenticated context instead of a data source path.
569
541
  */
570
- setDataSourceId(dataSourceId) {
571
- void dataSourceId;
572
- this.core = (0, import_sdk_core2.createEntitiesModule)(this.httpClient, coreErrors);
542
+ setDataSourceId(_dataSourceId) {
543
+ this.core = createEntitiesModule(this.httpClient, coreErrors);
573
544
  }
574
545
  getTable(tableName) {
575
546
  return this.core.getTable(tableName);
@@ -577,11 +548,13 @@ var EntitiesModule = class _EntitiesModule {
577
548
  };
578
549
 
579
550
  // src/modules/functions.ts
580
- var import_sdk_core3 = require("@mitralab.io/sdk-core");
551
+ import {
552
+ createFunctionsModule
553
+ } from "@mitralab.io/sdk-core";
581
554
  var FunctionsModule = class {
582
555
  core;
583
556
  constructor(httpClient) {
584
- this.core = (0, import_sdk_core3.createFunctionsModule)(httpClient, { emptyInput: "omit-body" }, coreErrors);
557
+ this.core = createFunctionsModule(httpClient, { emptyInput: "omit-body" }, coreErrors);
585
558
  }
586
559
  /**
587
560
  * Executes a Function using the Platform SDK 1.x server-default invocation semantics.
@@ -599,11 +572,13 @@ var FunctionsModule = class {
599
572
  };
600
573
 
601
574
  // src/modules/integration.ts
602
- var import_sdk_core4 = require("@mitralab.io/sdk-core");
575
+ import {
576
+ createIntegrationModule
577
+ } from "@mitralab.io/sdk-core";
603
578
  var IntegrationModule = class {
604
579
  core;
605
580
  constructor(httpClient) {
606
- this.core = (0, import_sdk_core4.createIntegrationModule)(httpClient, coreErrors);
581
+ this.core = createIntegrationModule(httpClient, coreErrors);
607
582
  }
608
583
  executeResource(resourceId, params) {
609
584
  return this.core.executeResource(resourceId, params);
@@ -614,12 +589,14 @@ var IntegrationModule = class {
614
589
  };
615
590
 
616
591
  // src/modules/queries.ts
617
- var import_sdk_core5 = require("@mitralab.io/sdk-core");
592
+ import {
593
+ createQueriesModule
594
+ } from "@mitralab.io/sdk-core";
618
595
  var QueriesModule = class {
619
596
  dataSourceId = "";
620
597
  core;
621
598
  constructor(httpClient) {
622
- this.core = (0, import_sdk_core5.createQueriesModule)(httpClient, () => this.dataSourceId, coreErrors);
599
+ this.core = createQueriesModule(httpClient, () => this.dataSourceId, coreErrors);
623
600
  }
624
601
  /** Called by `client.init()` to set the app's resolved data source. */
625
602
  setDataSourceId(dataSourceId) {
@@ -633,7 +610,7 @@ var QueriesModule = class {
633
610
 
634
611
  // src/client.ts
635
612
  function expectAppInfoResponse(value) {
636
- const response = (0, import_sdk_core6.expectObject)(
613
+ const response = expectObject(
637
614
  value,
638
615
  "App info response",
639
616
  coreErrors
@@ -698,7 +675,7 @@ function createClient(config) {
698
675
  });
699
676
  const appInfo = expectAppInfoResponse(
700
677
  await publicClient.get(
701
- `/api/v1/apps/${(0, import_sdk_core6.encodePathSegment)(appId, "appId", coreErrors)}/info`
678
+ `/api/v1/apps/${encodePathSegment(appId, "appId", coreErrors)}/info`
702
679
  )
703
680
  );
704
681
  entitiesModule.setDataSourceId(appInfo.dataSourceId);
@@ -719,8 +696,7 @@ function createClient(config) {
719
696
  config
720
697
  };
721
698
  }
722
- // Annotate the CommonJS export names for ESM import in node:
723
- 0 && (module.exports = {
699
+ export {
724
700
  MitraApiError,
725
701
  createClient
726
- });
702
+ };
package/package.json CHANGED
@@ -1,20 +1,34 @@
1
1
  {
2
2
  "name": "@mitralab.io/platform-sdk",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "JavaScript/TypeScript SDK for building apps on the Mitra Platform",
5
- "main": "dist/index.js",
6
- "module": "dist/index.mjs",
7
- "types": "dist/index.d.ts",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
8
10
  "exports": {
9
11
  ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.mjs",
12
- "require": "./dist/index.js"
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
13
20
  }
14
21
  },
15
22
  "files": [
16
- "dist"
23
+ "dist",
24
+ "README.md",
25
+ "LICENSE",
26
+ "CHANGELOG.md"
17
27
  ],
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "registry": "https://registry.npmjs.org"
31
+ },
18
32
  "scripts": {
19
33
  "build": "tsup src/index.ts --format cjs,esm --dts --clean",
20
34
  "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
@@ -22,9 +36,11 @@
22
36
  "typecheck": "tsc --noEmit",
23
37
  "test": "vitest run --coverage",
24
38
  "test:watch": "vitest",
39
+ "check:package-types": "npx --yes @arethetypeswrong/cli@0.18.5 --pack .",
40
+ "pack:check": "npm pack --dry-run",
25
41
  "smoke:package": "node scripts/smoke-package.mjs",
26
- "check": "npm run lint && npm run typecheck && npm test && npm run build && npm run smoke:package",
27
- "prepublishOnly": "npm run check"
42
+ "check": "npm run lint && npm run typecheck && npm test && npm run build && npm run pack:check && npm run smoke:package",
43
+ "prepublishOnly": "npm run check && npm run check:package-types"
28
44
  },
29
45
  "keywords": [
30
46
  "mitra",
@@ -64,6 +80,7 @@
64
80
  "node": ">=18.0.0"
65
81
  },
66
82
  "overrides": {
83
+ "esbuild": "^0.25.0",
67
84
  "rollup": "^4.59.0",
68
85
  "test-exclude": "7.0.1"
69
86
  }