@neetru/sdk 3.6.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/ai.cjs +254 -391
  3. package/dist/ai.d.cts +1 -1
  4. package/dist/ai.d.ts +1 -1
  5. package/dist/ai.mjs +254 -391
  6. package/dist/auth.cjs +3547 -4998
  7. package/dist/auth.d.cts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.mjs +3544 -4995
  10. package/dist/build-guard.cjs +101 -119
  11. package/dist/build-guard.mjs +91 -109
  12. package/dist/catalog.cjs +152 -224
  13. package/dist/catalog.d.cts +1 -1
  14. package/dist/catalog.d.ts +1 -1
  15. package/dist/catalog.mjs +152 -224
  16. package/dist/checkout.cjs +237 -320
  17. package/dist/checkout.d.cts +1 -1
  18. package/dist/checkout.d.ts +1 -1
  19. package/dist/checkout.mjs +236 -319
  20. package/dist/db-react.cjs +59 -87
  21. package/dist/db-react.d.cts +1 -1
  22. package/dist/db-react.d.ts +1 -1
  23. package/dist/db-react.mjs +56 -84
  24. package/dist/db.cjs +2055 -3013
  25. package/dist/db.d.cts +1 -1
  26. package/dist/db.d.ts +1 -1
  27. package/dist/db.mjs +2068 -3026
  28. package/dist/entitlements.cjs +12 -20
  29. package/dist/entitlements.d.cts +1 -1
  30. package/dist/entitlements.d.ts +1 -1
  31. package/dist/entitlements.mjs +12 -20
  32. package/dist/errors.cjs +9 -12
  33. package/dist/errors.d.cts +37 -2
  34. package/dist/errors.d.ts +37 -2
  35. package/dist/errors.mjs +8 -12
  36. package/dist/firestore-compat.cjs +241 -297
  37. package/dist/firestore-compat.d.cts +1 -1
  38. package/dist/firestore-compat.d.ts +1 -1
  39. package/dist/firestore-compat.mjs +215 -271
  40. package/dist/index.cjs +3605 -5131
  41. package/dist/index.d.cts +6 -4
  42. package/dist/index.d.ts +6 -4
  43. package/dist/index.mjs +3710 -5236
  44. package/dist/mobile.cjs +238 -342
  45. package/dist/mobile.d.cts +1 -1
  46. package/dist/mobile.d.ts +1 -1
  47. package/dist/mobile.mjs +238 -342
  48. package/dist/mocks.cjs +312 -447
  49. package/dist/mocks.d.cts +1 -1
  50. package/dist/mocks.d.ts +1 -1
  51. package/dist/mocks.mjs +306 -441
  52. package/dist/notifications.cjs +226 -314
  53. package/dist/notifications.d.cts +1 -1
  54. package/dist/notifications.d.ts +1 -1
  55. package/dist/notifications.mjs +225 -313
  56. package/dist/react.cjs +522 -693
  57. package/dist/react.d.cts +1 -1
  58. package/dist/react.d.ts +1 -1
  59. package/dist/react.mjs +512 -683
  60. package/dist/support.cjs +329 -325
  61. package/dist/support.d.cts +25 -3
  62. package/dist/support.d.ts +25 -3
  63. package/dist/support.mjs +328 -325
  64. package/dist/telemetry.cjs +197 -301
  65. package/dist/telemetry.d.cts +1 -1
  66. package/dist/telemetry.d.ts +1 -1
  67. package/dist/telemetry.mjs +197 -301
  68. package/dist/{types-Du_iioJ7.d.cts → types-Bx4kTLmk.d.cts} +26 -0
  69. package/dist/{types-BPATkXYu.d.ts → types-Dx0IrOSF.d.ts} +26 -0
  70. package/dist/usage.cjs +163 -227
  71. package/dist/usage.d.cts +1 -1
  72. package/dist/usage.d.ts +1 -1
  73. package/dist/usage.mjs +163 -227
  74. package/dist/webhooks.cjs +258 -359
  75. package/dist/webhooks.d.cts +1 -1
  76. package/dist/webhooks.d.ts +1 -1
  77. package/dist/webhooks.mjs +255 -356
  78. package/package.json +4 -3
  79. package/dist/ai.cjs.map +0 -1
  80. package/dist/ai.mjs.map +0 -1
  81. package/dist/auth.cjs.map +0 -1
  82. package/dist/auth.mjs.map +0 -1
  83. package/dist/build-guard.cjs.map +0 -1
  84. package/dist/build-guard.mjs.map +0 -1
  85. package/dist/catalog.cjs.map +0 -1
  86. package/dist/catalog.mjs.map +0 -1
  87. package/dist/checkout.cjs.map +0 -1
  88. package/dist/checkout.mjs.map +0 -1
  89. package/dist/db-react.cjs.map +0 -1
  90. package/dist/db-react.mjs.map +0 -1
  91. package/dist/db.cjs.map +0 -1
  92. package/dist/db.mjs.map +0 -1
  93. package/dist/entitlements.cjs.map +0 -1
  94. package/dist/entitlements.mjs.map +0 -1
  95. package/dist/errors.cjs.map +0 -1
  96. package/dist/errors.mjs.map +0 -1
  97. package/dist/firestore-compat.cjs.map +0 -1
  98. package/dist/firestore-compat.mjs.map +0 -1
  99. package/dist/index.cjs.map +0 -1
  100. package/dist/index.mjs.map +0 -1
  101. package/dist/mobile.cjs.map +0 -1
  102. package/dist/mobile.mjs.map +0 -1
  103. package/dist/mocks.cjs.map +0 -1
  104. package/dist/mocks.mjs.map +0 -1
  105. package/dist/notifications.cjs.map +0 -1
  106. package/dist/notifications.mjs.map +0 -1
  107. package/dist/react.cjs.map +0 -1
  108. package/dist/react.mjs.map +0 -1
  109. package/dist/support.cjs.map +0 -1
  110. package/dist/support.mjs.map +0 -1
  111. package/dist/telemetry.cjs.map +0 -1
  112. package/dist/telemetry.mjs.map +0 -1
  113. package/dist/usage.cjs.map +0 -1
  114. package/dist/usage.mjs.map +0 -1
  115. package/dist/webhooks.cjs.map +0 -1
  116. package/dist/webhooks.mjs.map +0 -1
package/dist/mobile.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/errors.ts
4
- var NeetruError = class _NeetruError extends Error {
4
+ var r = class t extends Error {
5
5
  code;
6
6
  status;
7
7
  requestId;
@@ -14,502 +14,398 @@ var NeetruError = class _NeetruError extends Error {
14
14
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
15
15
  */
16
16
  reason;
17
- constructor(code, message, status, requestId, reason) {
18
- super(message);
19
- this.name = "NeetruError";
20
- this.code = code;
21
- this.status = status;
22
- this.requestId = requestId;
23
- this.reason = reason;
24
- Object.setPrototypeOf(this, _NeetruError.prototype);
17
+ constructor(e, i, s, o, l) {
18
+ super(i), this.name = "NeetruError", this.code = e, this.status = s, this.requestId = o, this.reason = l, Object.setPrototypeOf(this, t.prototype);
25
19
  }
26
20
  };
27
21
 
28
22
  // src/types.ts
29
- var DEFAULT_BASE_URL = "https://api.neetru.com";
23
+ var L = "https://api.neetru.com";
30
24
 
31
25
  // src/base-url-allowlist.ts
32
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
33
- var NEETRU_SUFFIX = ".neetru.com";
34
- var NEETRU_APEX = "neetru.com";
35
- var SAFE_DEV_HOST_RE = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
36
- function isSafeDevHost(hostname) {
37
- return SAFE_DEV_HOST_RE.test(hostname);
26
+ var O = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), F = ".neetru.com", J = "neetru.com", Y = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
27
+ function D(t) {
28
+ return Y.test(t);
38
29
  }
39
- function normalizeHostname(hostname) {
40
- return hostname.toLowerCase().replace(/\.+$/, "");
30
+ function X(t) {
31
+ return t.toLowerCase().replace(/\.+$/, "");
41
32
  }
42
- function validateBaseUrl(baseUrl, allowedHosts = []) {
43
- if (typeof baseUrl !== "string" || baseUrl.length === 0) {
44
- throw new NeetruError("invalid_config", "baseUrl is required");
45
- }
46
- let parsed;
33
+ function M(t, e = []) {
34
+ if (typeof t != "string" || t.length === 0)
35
+ throw new r("invalid_config", "baseUrl is required");
36
+ let i;
47
37
  try {
48
- parsed = new URL(baseUrl);
38
+ i = new URL(t);
49
39
  } catch {
50
- throw new NeetruError("invalid_config", `baseUrl is not a valid URL: ${baseUrl}`);
40
+ throw new r("invalid_config", `baseUrl is not a valid URL: ${t}`);
51
41
  }
52
- const protocol = parsed.protocol;
53
- const hostname = normalizeHostname(parsed.hostname);
54
- if (isInsecureBypassActive()) {
55
- if (typeof console !== "undefined") {
56
- console.warn(
57
- `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${baseUrl} aceito sem valida\xE7\xE3o.`
58
- );
59
- }
60
- return baseUrl.replace(/\/+$/, "");
61
- }
62
- if (protocol !== "https:" && protocol !== "http:") {
63
- throw new NeetruError(
42
+ let s = i.protocol, o = X(i.hostname);
43
+ if (Z())
44
+ return typeof console < "u" && console.warn(
45
+ `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${t} aceito sem valida\xE7\xE3o.`
46
+ ), t.replace(/\/+$/, "");
47
+ if (s !== "https:" && s !== "http:")
48
+ throw new r(
64
49
  "invalid_config",
65
- `baseUrl protocol must be http: or https:, got ${protocol}`
50
+ `baseUrl protocol must be http: or https:, got ${s}`
66
51
  );
67
- }
68
- if (protocol === "http:") {
69
- const isLoopback = LOOPBACK_HOSTS.has(hostname) || isSafeDevHost(hostname);
70
- if (!isLoopback) {
71
- throw new NeetruError(
52
+ if (s === "http:") {
53
+ if (!(O.has(o) || D(o)))
54
+ throw new r(
72
55
  "invalid_config",
73
- `baseUrl with http: only allowed for localhost/127.0.0.1/*.test/*.localhost. Got: ${hostname}. Use https: or set NEETRU_ALLOW_INSECURE_BASEURL=1 to bypass.`
56
+ `baseUrl with http: only allowed for localhost/127.0.0.1/*.test/*.localhost. Got: ${o}. Use https: or set NEETRU_ALLOW_INSECURE_BASEURL=1 to bypass.`
74
57
  );
75
- }
76
- return baseUrl.replace(/\/+$/, "");
58
+ return t.replace(/\/+$/, "");
77
59
  }
78
- const isNeetruDomain = hostname === NEETRU_APEX || hostname.endsWith(NEETRU_SUFFIX);
79
- const isAllowedHost = allowedHosts.some((allowed) => {
80
- const norm = allowed.toLowerCase();
81
- return hostname === norm || hostname.endsWith(`.${norm}`);
82
- });
83
- const isLoopbackHttps = LOOPBACK_HOSTS.has(hostname) || isSafeDevHost(hostname);
84
- if (!isNeetruDomain && !isAllowedHost && !isLoopbackHttps) {
85
- throw new NeetruError(
60
+ let l = o === J || o.endsWith(F), A = e.some((m) => {
61
+ let k = m.toLowerCase();
62
+ return o === k || o.endsWith(`.${k}`);
63
+ }), R = O.has(o) || D(o);
64
+ if (!l && !A && !R)
65
+ throw new r(
86
66
  "invalid_config",
87
- `baseUrl ${hostname} is not in the allowlist. Allowed: *.neetru.com, localhost, or configure { allowedHosts: ['...'] }. Bypass: NEETRU_ALLOW_INSECURE_BASEURL=1.`
67
+ `baseUrl ${o} is not in the allowlist. Allowed: *.neetru.com, localhost, or configure { allowedHosts: ['...'] }. Bypass: NEETRU_ALLOW_INSECURE_BASEURL=1.`
88
68
  );
89
- }
90
- return baseUrl.replace(/\/+$/, "");
69
+ return t.replace(/\/+$/, "");
91
70
  }
92
- function isInsecureBypassActive() {
71
+ function Z() {
93
72
  try {
94
- const proc = globalThis.process;
95
- const envVal = proc?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
96
- if (envVal === "1" || envVal === "true") return true;
73
+ let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
74
+ if (e === "1" || e === "true") return !0;
97
75
  } catch {
98
76
  }
99
77
  try {
100
- const g = globalThis.NEETRU_ALLOW_INSECURE_BASEURL;
101
- if (g === "1" || g === "true" || g === true) return true;
78
+ let t = globalThis.NEETRU_ALLOW_INSECURE_BASEURL;
79
+ if (t === "1" || t === "true" || t === !0) return !0;
102
80
  } catch {
103
81
  }
104
82
  return false;
105
83
  }
106
84
 
107
85
  // src/api-key.ts
108
- var API_KEY_RE = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
109
- function parseApiKey(apiKey) {
110
- if (typeof apiKey !== "string" || apiKey.length === 0) {
111
- throw new NeetruError(
86
+ var G = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
87
+ function K(t) {
88
+ if (typeof t != "string" || t.length === 0)
89
+ throw new r(
112
90
  "invalid_config",
113
91
  "apiKey is required (formato nrt_<keyId>_<secret>)"
114
92
  );
115
- }
116
- const match = API_KEY_RE.exec(apiKey);
117
- if (!match) {
118
- throw new NeetruError(
93
+ let e = G.exec(t);
94
+ if (!e)
95
+ throw new r(
119
96
  "invalid_config",
120
97
  "apiKey malformado - esperado formato nrt_<keyId>_<secret>"
121
98
  );
122
- }
123
- return { keyId: match[1], secret: match[2] };
99
+ return { keyId: e[1], secret: e[2] };
124
100
  }
125
101
 
126
102
  // src/auth-pkce-shared.ts
127
- function getWebCrypto() {
128
- const c = globalThis.crypto;
129
- if (!c || typeof c.getRandomValues !== "function" || !c.subtle) {
130
- throw new NeetruError(
103
+ function H() {
104
+ let t = globalThis.crypto;
105
+ if (!t || typeof t.getRandomValues != "function" || !t.subtle)
106
+ throw new r(
131
107
  "runtime_unsupported",
132
108
  "auth.signIn requer WebCrypto (crypto.subtle) \u2014 indispon\xEDvel neste runtime. Use HTTPS (ou http://localhost) num browser moderno, ou instale um polyfill WebCrypto (ex: react-native-quick-crypto) em React Native."
133
109
  );
134
- }
135
- return c;
110
+ return t;
136
111
  }
137
- function base64UrlFromBytes(bytes) {
138
- let str = "";
139
- for (const b of bytes) str += String.fromCharCode(b);
140
- const b64 = typeof btoa === "function" ? btoa(str) : Buffer.from(str, "binary").toString("base64");
141
- return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
112
+ function $(t) {
113
+ let e = "";
114
+ for (let s of t) e += String.fromCharCode(s);
115
+ return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
142
116
  }
143
- function randomUrlSafe(crypto, byteLen) {
144
- const bytes = new Uint8Array(byteLen);
145
- crypto.getRandomValues(bytes);
146
- return base64UrlFromBytes(bytes);
117
+ function v(t, e) {
118
+ let i = new Uint8Array(e);
119
+ return t.getRandomValues(i), $(i);
147
120
  }
148
- async function pkceChallengeS256(crypto, verifier) {
149
- const data = new TextEncoder().encode(verifier);
150
- const digest = await crypto.subtle.digest("SHA-256", data);
151
- return base64UrlFromBytes(new Uint8Array(digest));
121
+ async function B(t, e) {
122
+ let i = new TextEncoder().encode(e), s = await t.subtle.digest("SHA-256", i);
123
+ return $(new Uint8Array(s));
152
124
  }
153
- function resolveIdpOrigin(baseUrl) {
154
- const overrideAuthUrl = typeof globalThis.NEETRU_AUTH_URL === "string" ? globalThis.NEETRU_AUTH_URL : null;
155
- return overrideAuthUrl ?? baseUrl.replace(/^https?:\/\/api\./, "https://auth.");
125
+ function U(t) {
126
+ return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? t.replace(/^https?:\/\/api\./, "https://auth.");
156
127
  }
157
- function resolveOidcClientId(config) {
158
- let clientId = config.oidcClientId;
159
- if (!clientId && config.apiKey) {
160
- clientId = parseApiKey(config.apiKey).keyId;
161
- }
162
- if (!clientId) {
163
- throw new NeetruError(
128
+ function I(t) {
129
+ let e = t.oidcClientId;
130
+ if (!e && t.apiKey && (e = K(t.apiKey).keyId), !e)
131
+ throw new r(
164
132
  "invalid_config",
165
133
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
166
134
  );
167
- }
168
- return clientId;
135
+ return e;
169
136
  }
170
- function buildAuthorizeUrl(params) {
171
- const url = new URL("/api/v1/oauth/authorize", params.idpOrigin);
172
- url.searchParams.set("response_type", "code");
173
- url.searchParams.set("client_id", params.clientId);
174
- url.searchParams.set("redirect_uri", params.redirectUri);
175
- url.searchParams.set("scope", params.scope);
176
- url.searchParams.set("state", params.state);
177
- url.searchParams.set("nonce", params.nonce);
178
- url.searchParams.set("code_challenge", params.codeChallenge);
179
- url.searchParams.set("code_challenge_method", "S256");
180
- return url;
137
+ function q(t) {
138
+ let e = new URL("/api/v1/oauth/authorize", t.idpOrigin);
139
+ return e.searchParams.set("response_type", "code"), e.searchParams.set("client_id", t.clientId), e.searchParams.set("redirect_uri", t.redirectUri), e.searchParams.set("scope", t.scope), e.searchParams.set("state", t.state), e.searchParams.set("nonce", t.nonce), e.searchParams.set("code_challenge", t.codeChallenge), e.searchParams.set("code_challenge_method", "S256"), e;
181
140
  }
182
- var OAUTH_TOKEN_PATH = "/api/v1/oauth/token";
183
- function decodeJwtPayload(token) {
184
- const parts = token.split(".");
185
- if (parts.length !== 3) return null;
141
+ var W = "/api/v1/oauth/token";
142
+ function N(t) {
143
+ let e = t.split(".");
144
+ if (e.length !== 3) return null;
186
145
  try {
187
- const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
188
- const pad = "=".repeat((4 - b64.length % 4) % 4);
189
- const decoded = typeof atob === "function" ? atob(b64 + pad) : Buffer.from(b64 + pad, "base64").toString("utf-8");
190
- return JSON.parse(decoded);
146
+ let i = e[1].replace(/-/g, "+").replace(/_/g, "/"), s = "=".repeat((4 - i.length % 4) % 4), o = typeof atob == "function" ? atob(i + s) : Buffer.from(i + s, "base64").toString("utf-8");
147
+ return JSON.parse(o);
191
148
  } catch {
192
149
  return null;
193
150
  }
194
151
  }
195
- function jwtToNeetruUser(token) {
196
- const payload = decodeJwtPayload(token);
197
- if (!payload || typeof payload.sub !== "string") return null;
198
- if (typeof payload.exp === "number" && payload.exp * 1e3 < Date.now()) {
199
- return null;
200
- }
201
- return {
202
- uid: payload.sub,
203
- email: typeof payload.email === "string" ? payload.email : "",
204
- emailVerified: typeof payload.email_verified === "boolean" ? payload.email_verified : void 0,
205
- displayName: typeof payload.name === "string" ? payload.name : void 0,
206
- photoURL: typeof payload.picture === "string" ? payload.picture : void 0,
207
- isStaff: payload.is_staff === true,
208
- isCustomer: payload.is_customer === true,
209
- tenantId: typeof payload.tenant_id === "string" ? payload.tenant_id : void 0,
210
- ...payload
152
+ function _(t) {
153
+ let e = N(t);
154
+ return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
155
+ uid: e.sub,
156
+ email: typeof e.email == "string" ? e.email : "",
157
+ emailVerified: typeof e.email_verified == "boolean" ? e.email_verified : void 0,
158
+ displayName: typeof e.name == "string" ? e.name : void 0,
159
+ photoURL: typeof e.picture == "string" ? e.picture : void 0,
160
+ isStaff: e.is_staff === true,
161
+ isCustomer: e.is_customer === true,
162
+ tenantId: typeof e.tenant_id == "string" ? e.tenant_id : void 0,
163
+ ...e
211
164
  };
212
165
  }
213
166
 
214
167
  // src/mobile.ts
215
- var OIDC_TX_KEY = "neetru_oauth_tx";
216
- var ID_TOKEN_KEY = "neetru_id_token";
217
- var REFRESH_TOKEN_KEY = "neetru_refresh_token";
218
- function resolveMobileConfig(config) {
219
- if (!config.storage) {
220
- throw new NeetruError(
168
+ var h = "neetru_oauth_tx", y = "neetru_id_token", S = "neetru_refresh_token";
169
+ function Q(t) {
170
+ if (!t.storage)
171
+ throw new r(
221
172
  "invalid_config",
222
173
  "createMobileAuthNamespace requer `storage` (MobileAuthStorage) \u2014 ver JSDoc de src/mobile.ts requisito 4."
223
174
  );
224
- }
225
- if (typeof config.openAuthUrl !== "function") {
226
- throw new NeetruError(
175
+ if (typeof t.openAuthUrl != "function")
176
+ throw new r(
227
177
  "invalid_config",
228
178
  "createMobileAuthNamespace requer `openAuthUrl` (browser externo, NUNCA WebView embutida) \u2014 ver JSDoc de src/mobile.ts requisito 3."
229
179
  );
230
- }
231
- const fetchImpl = config.fetch ?? globalThis.fetch;
232
- if (typeof fetchImpl !== "function") {
233
- throw new NeetruError(
180
+ let e = t.fetch ?? globalThis.fetch;
181
+ if (typeof e != "function")
182
+ throw new r(
234
183
  "invalid_config",
235
184
  "fetch is not available in this runtime. Pass `fetch` explicitly to createMobileAuthNamespace."
236
185
  );
237
- }
238
- const baseUrl = validateBaseUrl(config.baseUrl ?? DEFAULT_BASE_URL, config.allowedHosts ?? []);
186
+ let i = M(t.baseUrl ?? L, t.allowedHosts ?? []);
239
187
  return {
240
- fetchImpl: fetchImpl.bind(globalThis),
241
- baseUrl,
242
- oidcClientId: config.oidcClientId,
243
- apiKey: config.apiKey,
244
- storage: config.storage,
245
- openAuthUrl: config.openAuthUrl
188
+ fetchImpl: e.bind(globalThis),
189
+ baseUrl: i,
190
+ oidcClientId: t.oidcClientId,
191
+ apiKey: t.apiKey,
192
+ storage: t.storage,
193
+ openAuthUrl: t.openAuthUrl
246
194
  };
247
195
  }
248
- async function postToken(fetchImpl, tokenUrl, form) {
249
- let res;
196
+ async function z(t, e, i) {
197
+ let s;
250
198
  try {
251
- res = await fetchImpl(tokenUrl, {
199
+ s = await t(e, {
252
200
  method: "POST",
253
201
  headers: { "content-type": "application/x-www-form-urlencoded" },
254
- body: form.toString()
202
+ body: i.toString()
255
203
  });
256
- } catch (err) {
257
- throw new NeetruError(
204
+ } catch (l) {
205
+ throw new r(
258
206
  "network_error",
259
- `POST ${tokenUrl} falhou (network): ${err?.message ?? String(err)}`
207
+ `POST ${e} falhou (network): ${l?.message ?? String(l)}`
260
208
  );
261
209
  }
262
- let payload = null;
210
+ let o = null;
263
211
  try {
264
- payload = await res.json();
212
+ o = await s.json();
265
213
  } catch {
266
- payload = null;
214
+ o = null;
267
215
  }
268
- if (!res.ok || typeof payload?.error === "string") {
269
- const desc = typeof payload?.error_description === "string" && payload.error_description || typeof payload?.error === "string" && payload.error || `HTTP ${res.status}`;
270
- throw new NeetruError(
216
+ if (!s.ok || typeof o?.error == "string") {
217
+ let l = typeof o?.error_description == "string" && o.error_description || typeof o?.error == "string" && o.error || `HTTP ${s.status}`;
218
+ throw new r(
271
219
  "token_exchange_failed",
272
- `Troca de tokens falhou no /token: ${desc}`,
273
- res.status
220
+ `Troca de tokens falhou no /token: ${l}`,
221
+ s.status
274
222
  );
275
223
  }
276
- return payload ?? {};
224
+ return o ?? {};
277
225
  }
278
- function createMobileAuthNamespace(config) {
279
- const resolved = resolveMobileConfig(config);
280
- const listeners = /* @__PURE__ */ new Set();
281
- function tokenUrl() {
282
- return `${resolveIdpOrigin(resolved.baseUrl)}${OAUTH_TOKEN_PATH}`;
226
+ function ge(t) {
227
+ let e = Q(t), i = /* @__PURE__ */ new Set();
228
+ function s() {
229
+ return `${U(e.baseUrl)}${W}`;
283
230
  }
284
- async function notify() {
285
- const user = await getUser();
286
- for (const l of listeners) {
231
+ async function o() {
232
+ let n = await m();
233
+ for (let a of i)
287
234
  try {
288
- l(user);
235
+ a(n);
289
236
  } catch {
290
237
  }
291
- }
292
238
  }
293
- async function signIn(options) {
294
- if (!options?.redirectUri) {
295
- throw new NeetruError(
239
+ async function l(n) {
240
+ if (!n?.redirectUri)
241
+ throw new r(
296
242
  "invalid_config",
297
243
  "mobile auth.signIn requer `redirectUri` (Universal Link/App Link https://... registrado no Core) \u2014 n\xE3o h\xE1 location.origin impl\xEDcito em React Native."
298
244
  );
299
- }
300
- const crypto = getWebCrypto();
301
- const scope = options.scope ?? "openid profile email";
302
- const clientId = resolveOidcClientId(resolved);
303
- const state = randomUrlSafe(crypto, 16);
304
- const nonce = randomUrlSafe(crypto, 16);
305
- const codeVerifier = randomUrlSafe(crypto, 32);
306
- const codeChallenge = await pkceChallengeS256(crypto, codeVerifier);
307
- const tx = {
308
- state,
309
- nonce,
310
- codeVerifier,
311
- redirectUri: options.redirectUri,
312
- postLoginRedirect: options.postLoginRedirect
245
+ let a = H(), u = n.scope ?? "openid profile email", c = I(e), d = v(a, 16), f = v(a, 16), g = v(a, 32), p = await B(a, g), T = {
246
+ state: d,
247
+ nonce: f,
248
+ codeVerifier: g,
249
+ redirectUri: n.redirectUri,
250
+ postLoginRedirect: n.postLoginRedirect
313
251
  };
314
- await resolved.storage.setItem(OIDC_TX_KEY, JSON.stringify(tx));
315
- const idpOrigin = resolveIdpOrigin(resolved.baseUrl);
316
- const url = buildAuthorizeUrl({
317
- idpOrigin,
318
- clientId,
319
- redirectUri: options.redirectUri,
320
- scope,
321
- state,
322
- nonce,
323
- codeChallenge
252
+ await e.storage.setItem(h, JSON.stringify(T));
253
+ let C = U(e.baseUrl), w = q({
254
+ idpOrigin: C,
255
+ clientId: c,
256
+ redirectUri: n.redirectUri,
257
+ scope: u,
258
+ state: d,
259
+ nonce: f,
260
+ codeChallenge: p
324
261
  });
325
- await resolved.openAuthUrl(url.toString());
262
+ await e.openAuthUrl(w.toString());
326
263
  }
327
- async function completeSignIn(callbackUrl) {
328
- if (!callbackUrl || typeof callbackUrl !== "string") {
329
- throw new NeetruError(
264
+ async function A(n) {
265
+ if (!n || typeof n != "string")
266
+ throw new r(
330
267
  "invalid_config",
331
268
  "mobile auth.completeSignIn requer `callbackUrl` (a URL completa do deep link de retorno) \u2014 mobile n\xE3o tem location.href impl\xEDcito."
332
269
  );
333
- }
334
- let parsed;
270
+ let a;
335
271
  try {
336
- parsed = new URL(callbackUrl);
272
+ a = new URL(n);
337
273
  } catch {
338
- throw new NeetruError("invalid_config", `callbackUrl n\xE3o \xE9 uma URL v\xE1lida: ${callbackUrl}`);
274
+ throw new r("invalid_config", `callbackUrl n\xE3o \xE9 uma URL v\xE1lida: ${n}`);
339
275
  }
340
- const params = parsed.searchParams;
341
- const idpError = params.get("error");
342
- if (idpError) {
343
- const desc = params.get("error_description") ?? idpError;
344
- await resolved.storage.removeItem(OIDC_TX_KEY);
345
- throw new NeetruError(idpError, `OIDC authorize falhou: ${desc}`);
276
+ let u = a.searchParams, c = u.get("error");
277
+ if (c) {
278
+ let j = u.get("error_description") ?? c;
279
+ throw await e.storage.removeItem(h), new r(c, `OIDC authorize falhou: ${j}`);
346
280
  }
347
- const code = params.get("code");
348
- if (!code) {
349
- await resolved.storage.removeItem(OIDC_TX_KEY);
350
- throw new NeetruError(
281
+ let d = u.get("code");
282
+ if (!d)
283
+ throw await e.storage.removeItem(h), new r(
351
284
  "invalid_config",
352
285
  "callbackUrl n\xE3o cont\xE9m `?code=` nem `?error=` \u2014 n\xE3o \xE9 um callback OIDC v\xE1lido."
353
286
  );
354
- }
355
- const returnedState = params.get("state");
356
- const txRaw = await resolved.storage.getItem(OIDC_TX_KEY);
357
- let tx = null;
358
- if (txRaw) {
287
+ let f = u.get("state"), g = await e.storage.getItem(h), p = null;
288
+ if (g)
359
289
  try {
360
- tx = JSON.parse(txRaw);
290
+ p = JSON.parse(g);
361
291
  } catch {
362
- tx = null;
292
+ p = null;
363
293
  }
364
- }
365
- if (!tx) {
366
- throw new NeetruError(
294
+ if (!p)
295
+ throw new r(
367
296
  "oidc_state_mismatch",
368
297
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado (ou j\xE1 consumido)."
369
298
  );
370
- }
371
- if (!returnedState || returnedState !== tx.state) {
372
- await resolved.storage.removeItem(OIDC_TX_KEY);
373
- throw new NeetruError(
299
+ if (!f || f !== p.state)
300
+ throw await e.storage.removeItem(h), new r(
374
301
  "oidc_state_mismatch",
375
302
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
376
303
  );
377
- }
378
- await resolved.storage.removeItem(OIDC_TX_KEY);
379
- const clientId = resolveOidcClientId(resolved);
380
- const form = new URLSearchParams({
304
+ await e.storage.removeItem(h);
305
+ let T = I(e), C = new URLSearchParams({
381
306
  grant_type: "authorization_code",
382
- code,
383
- redirect_uri: tx.redirectUri,
384
- client_id: clientId,
385
- code_verifier: tx.codeVerifier
386
- });
387
- const payload = await postToken(resolved.fetchImpl, tokenUrl(), form);
388
- const idToken = payload.id_token;
389
- if (typeof idToken !== "string" || idToken.length === 0) {
390
- throw new NeetruError(
307
+ code: d,
308
+ redirect_uri: p.redirectUri,
309
+ client_id: T,
310
+ code_verifier: p.codeVerifier
311
+ }), w = await z(e.fetchImpl, s(), C), b = w.id_token;
312
+ if (typeof b != "string" || b.length === 0)
313
+ throw new r(
391
314
  "token_exchange_failed",
392
315
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado."
393
316
  );
394
- }
395
- const claims = decodeJwtPayload(idToken);
396
- if (!claims) {
397
- throw new NeetruError(
317
+ let x = N(b);
318
+ if (!x)
319
+ throw new r(
398
320
  "token_exchange_failed",
399
321
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
400
322
  );
401
- }
402
- if (claims.nonce !== tx.nonce) {
403
- throw new NeetruError(
323
+ if (x.nonce !== p.nonce)
324
+ throw new r(
404
325
  "oidc_nonce_mismatch",
405
326
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
406
327
  );
407
- }
408
- const user = jwtToNeetruUser(idToken);
409
- if (!user) {
410
- throw new NeetruError(
328
+ let E = _(b);
329
+ if (!E)
330
+ throw new r(
411
331
  "token_exchange_failed",
412
332
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
413
333
  );
414
- }
415
- await resolved.storage.setItem(ID_TOKEN_KEY, idToken);
416
- const refreshToken = payload.refresh_token;
417
- if (typeof refreshToken === "string" && refreshToken.length > 0) {
418
- await resolved.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
419
- }
420
- await notify();
421
- return { user, postLoginRedirect: tx.postLoginRedirect };
334
+ await e.storage.setItem(y, b);
335
+ let P = w.refresh_token;
336
+ return typeof P == "string" && P.length > 0 && await e.storage.setItem(S, P), await o(), { user: E, postLoginRedirect: p.postLoginRedirect };
422
337
  }
423
- async function getIdToken() {
424
- const token = await resolved.storage.getItem(ID_TOKEN_KEY);
425
- if (!token) return null;
426
- return jwtToNeetruUser(token) ? token : null;
338
+ async function R() {
339
+ let n = await e.storage.getItem(y);
340
+ return n && _(n) ? n : null;
427
341
  }
428
- async function getUser() {
429
- const token = await resolved.storage.getItem(ID_TOKEN_KEY);
430
- if (!token) return null;
431
- return jwtToNeetruUser(token);
342
+ async function m() {
343
+ let n = await e.storage.getItem(y);
344
+ return n ? _(n) : null;
432
345
  }
433
- async function refreshTokens() {
434
- const refreshToken = await resolved.storage.getItem(REFRESH_TOKEN_KEY);
435
- if (!refreshToken) return false;
436
- let clientId;
346
+ async function k() {
347
+ let n = await e.storage.getItem(S);
348
+ if (!n) return false;
349
+ let a;
437
350
  try {
438
- clientId = resolveOidcClientId(resolved);
351
+ a = I(e);
439
352
  } catch {
440
353
  return false;
441
354
  }
442
- const form = new URLSearchParams({
355
+ let u = new URLSearchParams({
443
356
  grant_type: "refresh_token",
444
- refresh_token: refreshToken,
445
- client_id: clientId
446
- });
447
- let payload;
357
+ refresh_token: n,
358
+ client_id: a
359
+ }), c;
448
360
  try {
449
- payload = await postToken(resolved.fetchImpl, tokenUrl(), form);
361
+ c = await z(e.fetchImpl, s(), u);
450
362
  } catch {
451
363
  return false;
452
364
  }
453
- const idToken = payload.id_token;
454
- if (typeof idToken !== "string" || idToken.length === 0) return false;
455
- const user = jwtToNeetruUser(idToken);
456
- if (!user) return false;
457
- await resolved.storage.setItem(ID_TOKEN_KEY, idToken);
458
- const rotated = payload.refresh_token;
459
- if (typeof rotated === "string" && rotated.length > 0) {
460
- await resolved.storage.setItem(REFRESH_TOKEN_KEY, rotated);
461
- }
462
- await notify();
463
- return true;
365
+ let d = c.id_token;
366
+ if (typeof d != "string" || d.length === 0 || !_(d)) return false;
367
+ await e.storage.setItem(y, d);
368
+ let g = c.refresh_token;
369
+ return typeof g == "string" && g.length > 0 && await e.storage.setItem(S, g), await o(), true;
464
370
  }
465
- async function signOut() {
466
- const storedToken = await resolved.storage.getItem(ID_TOKEN_KEY);
467
- await resolved.storage.removeItem(ID_TOKEN_KEY);
468
- await resolved.storage.removeItem(REFRESH_TOKEN_KEY);
469
- if (storedToken) {
470
- const idpOrigin = resolveIdpOrigin(resolved.baseUrl);
471
- const revokeUrl = `${idpOrigin}/api/v1/oauth/revoke`;
371
+ async function V() {
372
+ let n = await e.storage.getItem(y);
373
+ if (await e.storage.removeItem(y), await e.storage.removeItem(S), n) {
374
+ let u = `${U(e.baseUrl)}/api/v1/oauth/revoke`;
472
375
  try {
473
- await resolved.fetchImpl(revokeUrl, {
376
+ await e.fetchImpl(u, {
474
377
  method: "POST",
475
378
  headers: { "content-type": "application/json" },
476
- body: JSON.stringify({ token: storedToken })
379
+ body: JSON.stringify({ token: n })
477
380
  });
478
- } catch (err) {
479
- if (typeof console !== "undefined") {
480
- console.warn(
481
- "[neetru-sdk] mobile signOut: server-side revoke falhou. Refresh token pode estar stale.",
482
- err
483
- );
484
- }
381
+ } catch (c) {
382
+ typeof console < "u" && console.warn(
383
+ "[neetru-sdk] mobile signOut: server-side revoke falhou. Refresh token pode estar stale.",
384
+ c
385
+ );
485
386
  }
486
387
  }
487
- await notify();
388
+ await o();
488
389
  }
489
390
  return {
490
- signIn,
491
- completeSignIn,
492
- getIdToken,
493
- getUser,
494
- onAuthStateChanged(listener) {
495
- listeners.add(listener);
496
- void getUser().then((user) => {
497
- if (listeners.has(listener)) {
391
+ signIn: l,
392
+ completeSignIn: A,
393
+ getIdToken: R,
394
+ getUser: m,
395
+ onAuthStateChanged(n) {
396
+ return i.add(n), m().then((a) => {
397
+ if (i.has(n))
498
398
  try {
499
- listener(user);
399
+ n(a);
500
400
  } catch {
501
401
  }
502
- }
503
- });
504
- return () => {
505
- listeners.delete(listener);
402
+ }), () => {
403
+ i.delete(n);
506
404
  };
507
405
  },
508
- refreshTokens,
509
- signOut
406
+ refreshTokens: k,
407
+ signOut: V
510
408
  };
511
409
  }
512
410
 
513
- exports.createMobileAuthNamespace = createMobileAuthNamespace;
514
- //# sourceMappingURL=mobile.cjs.map
515
- //# sourceMappingURL=mobile.cjs.map
411
+ exports.createMobileAuthNamespace = ge;