geo-engine-node 2.1.0 → 3.0.0-rc.1

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.
@@ -0,0 +1,1231 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;// src/errors.ts
2
+ var GeoEngineError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "GeoEngineError";
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ };
9
+ var ClientClosedError = class extends GeoEngineError {
10
+ constructor(message = "geoengine: client is closed") {
11
+ super(message);
12
+ this.name = "ClientClosedError";
13
+ }
14
+ };
15
+ var ValidationError = class extends GeoEngineError {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "ValidationError";
19
+ }
20
+ };
21
+ var DeviceIDRequiredError = class extends ValidationError {
22
+ constructor(message = "geoengine: device_id is required") {
23
+ super(message);
24
+ this.name = "DeviceIDRequiredError";
25
+ }
26
+ };
27
+ var GeofenceIDRequiredError = class extends ValidationError {
28
+ constructor(message = "geoengine: geofence_id is required") {
29
+ super(message);
30
+ this.name = "GeofenceIDRequiredError";
31
+ }
32
+ };
33
+ var InvalidLatitudeError = class extends ValidationError {
34
+ constructor(message = "geoengine: latitude must be between -90 and 90 degrees") {
35
+ super(message);
36
+ this.name = "InvalidLatitudeError";
37
+ }
38
+ };
39
+ var InvalidLongitudeError = class extends ValidationError {
40
+ constructor(message = "geoengine: longitude must be between -180 and 180 degrees") {
41
+ super(message);
42
+ this.name = "InvalidLongitudeError";
43
+ }
44
+ };
45
+ var InvalidCoordinatesError = class extends ValidationError {
46
+ constructor(message = "geoengine: at least 3 coordinate pairs are required for a polygon") {
47
+ super(message);
48
+ this.name = "InvalidCoordinatesError";
49
+ }
50
+ };
51
+ var APIError = class extends GeoEngineError {
52
+
53
+ constructor(statusCode, message) {
54
+ super(`geoengine: API error (status ${statusCode}): ${message}`);
55
+ this.name = "APIError";
56
+ this.statusCode = statusCode;
57
+ }
58
+ };
59
+ var SpatialAPIError = class extends APIError {
60
+
61
+
62
+
63
+ constructor(statusCode, code, message, statusText, details = []) {
64
+ const formattedMessage = code ? `geoengine: spatial API error (status ${statusCode}, code ${code}): ${message}` : `geoengine: spatial API error (status ${statusCode}): ${message}`;
65
+ super(statusCode, formattedMessage);
66
+ this.name = "SpatialAPIError";
67
+ this.code = code;
68
+ this.statusText = statusText;
69
+ this.details = details;
70
+ }
71
+ /**
72
+ * Returns true if the error indicates the geofence or resource was not found.
73
+ */
74
+ isNotFound() {
75
+ return this.statusCode === 204 || this.statusCode === 404 || this.code === "NOT_FOUND";
76
+ }
77
+ /**
78
+ * Returns true if the error indicates quota limit was hit.
79
+ */
80
+ isQuotaExceeded() {
81
+ return this.statusCode === 402 || this.code === "QUOTA_EXCEEDED";
82
+ }
83
+ /**
84
+ * Returns true if authentication failed.
85
+ */
86
+ isUnauthorized() {
87
+ return this.statusCode === 401 || this.code === "UNAUTHORIZED" || this.code === "MISSING_API_KEY" || this.code === "MISSING_ORGANIZATION";
88
+ }
89
+ /**
90
+ * Returns true if access to the requested resource is forbidden.
91
+ */
92
+ isForbidden() {
93
+ return this.statusCode === 403 || this.code === "FORBIDDEN";
94
+ }
95
+ };
96
+ var GeofenceNotFoundError = class extends SpatialAPIError {
97
+ constructor(message = "geofence not found", statusCode = 204, details = []) {
98
+ super(statusCode, "NOT_FOUND", message, "Not Found", details);
99
+ this.name = "GeofenceNotFoundError";
100
+ }
101
+ };
102
+ var QuotaExceededError = class extends SpatialAPIError {
103
+ constructor(message = "request quota exceeded", statusCode = 402, details = []) {
104
+ super(statusCode, "QUOTA_EXCEEDED", message, "Payment Required", details);
105
+ this.name = "QuotaExceededError";
106
+ }
107
+ };
108
+ var AuthenticationError = class extends SpatialAPIError {
109
+ constructor(message = "unauthorized API request", statusCode = 401, details = []) {
110
+ super(statusCode, "UNAUTHORIZED", message, "Unauthorized", details);
111
+ this.name = "AuthenticationError";
112
+ }
113
+ };
114
+ var ForbiddenError = class extends SpatialAPIError {
115
+ constructor(message = "access forbidden", statusCode = 403, details = []) {
116
+ super(statusCode, "FORBIDDEN", message, "Forbidden", details);
117
+ this.name = "ForbiddenError";
118
+ }
119
+ };
120
+ var TimeoutError = class extends GeoEngineError {
121
+ constructor(timeoutMs) {
122
+ super(`geoengine: request exceeded the timeout limit of ${timeoutMs}ms`);
123
+ this.name = "TimeoutError";
124
+ }
125
+ };
126
+ var UserIDRequiredError = class extends ValidationError {
127
+ constructor(message = "geoengine: user_id is required") {
128
+ super(message);
129
+ this.name = "UserIDRequiredError";
130
+ }
131
+ };
132
+ var RuleIDRequiredError = class extends ValidationError {
133
+ constructor(message = "geoengine: rule_id is required") {
134
+ super(message);
135
+ this.name = "RuleIDRequiredError";
136
+ }
137
+ };
138
+ var RuleNameRequiredError = class extends ValidationError {
139
+ constructor(message = "geoengine: rule name is required") {
140
+ super(message);
141
+ this.name = "RuleNameRequiredError";
142
+ }
143
+ };
144
+ var EmailRequiredError = class extends ValidationError {
145
+ constructor(message = "geoengine: email is required") {
146
+ super(message);
147
+ this.name = "EmailRequiredError";
148
+ }
149
+ };
150
+ var RoleRequiredError = class extends ValidationError {
151
+ constructor(message = "geoengine: role is required") {
152
+ super(message);
153
+ this.name = "RoleRequiredError";
154
+ }
155
+ };
156
+ var APIServiceError = class extends APIError {
157
+ /** Machine-readable reason, e.g. "USER_NOT_FOUND". Empty when the API sent none. */
158
+
159
+ /** Message returned by the API, without the SDK prefix. */
160
+
161
+
162
+ constructor(statusCode, code, message, details = []) {
163
+ super(statusCode, message);
164
+ this.message = code ? `geoengine: api-service error (status ${statusCode}, code ${code}): ${message}` : `geoengine: api-service error (status ${statusCode}): ${message}`;
165
+ this.name = "APIServiceError";
166
+ this.code = code;
167
+ this.apiMessage = message;
168
+ this.details = details;
169
+ }
170
+ };
171
+ var UserNotFoundError = class extends APIServiceError {
172
+ constructor(message = "user not found in organization", statusCode = 404, code = "USER_NOT_FOUND", details = []) {
173
+ super(statusCode, code, message, details);
174
+ this.name = "UserNotFoundError";
175
+ }
176
+ };
177
+ var RuleNotFoundError = class extends APIServiceError {
178
+ constructor(message = "geoidentity rule not found", statusCode = 404, code = "RULE_NOT_FOUND", details = []) {
179
+ super(statusCode, code, message, details);
180
+ this.name = "RuleNotFoundError";
181
+ }
182
+ };
183
+ var UserAlreadyExistsError = class extends APIServiceError {
184
+ constructor(message = "user already belongs to the organization", statusCode = 409, code = "USER_ALREADY_EXISTS", details = []) {
185
+ super(statusCode, code, message, details);
186
+ this.name = "UserAlreadyExistsError";
187
+ }
188
+ };
189
+ var InvitationPendingError = class extends APIServiceError {
190
+ constructor(message = "a pending invitation already exists for this email", statusCode = 409, code = "INVITATION_PENDING", details = []) {
191
+ super(statusCode, code, message, details);
192
+ this.name = "InvitationPendingError";
193
+ }
194
+ };
195
+ var LastAdminError = class extends APIServiceError {
196
+ constructor(message = "organization must keep at least one admin", statusCode = 409, code = "LAST_ADMIN", details = []) {
197
+ super(statusCode, code, message, details);
198
+ this.name = "LastAdminError";
199
+ }
200
+ };
201
+ var LastSubjectError = class extends APIServiceError {
202
+ constructor(message = "rule must keep at least one assigned subject", statusCode = 409, code = "LAST_SUBJECT", details = []) {
203
+ super(statusCode, code, message, details);
204
+ this.name = "LastSubjectError";
205
+ }
206
+ };
207
+
208
+ // src/crypto.ts
209
+ var _crypto = require('crypto');
210
+ function generateHMACSignature(key, timestamp) {
211
+ if (!key) {
212
+ return "";
213
+ }
214
+ return _crypto.createHmac.call(void 0, "sha256", key).update(timestamp.toString()).digest("hex");
215
+ }
216
+
217
+ // src/version.ts
218
+ var SDK_VERSION = true ? "3.0.0-rc.1" : "unknown";
219
+
220
+ // src/http.ts
221
+ var USER_AGENT = `GeoEngineNodeSDK/${SDK_VERSION}`;
222
+ function parseHttpError(statusCode, bodyText, isSpatial = false) {
223
+ let parsedErrorContainer = null;
224
+ try {
225
+ parsedErrorContainer = JSON.parse(bodyText);
226
+ } catch (e) {
227
+ }
228
+ const container = _optionalChain([parsedErrorContainer, 'optionalAccess', _ => _.error]);
229
+ let code = _nullishCoalesce(_optionalChain([container, 'optionalAccess', _2 => _2.status]), () => ( ""));
230
+ let message = _nullishCoalesce(_nullishCoalesce(_optionalChain([container, 'optionalAccess', _3 => _3.message]), () => ( _optionalChain([parsedErrorContainer, 'optionalAccess', _4 => _4.message]))), () => ( bodyText.trim()));
231
+ const details = _nullishCoalesce(_optionalChain([container, 'optionalAccess', _5 => _5.details]), () => ( []));
232
+ if (_optionalChain([container, 'optionalAccess', _6 => _6.details]) && container.details.length > 0) {
233
+ for (const detail of container.details) {
234
+ if (detail.reason) {
235
+ code = detail.reason;
236
+ break;
237
+ }
238
+ }
239
+ }
240
+ if (!code) {
241
+ switch (statusCode) {
242
+ case 204:
243
+ case 404:
244
+ code = "NOT_FOUND";
245
+ break;
246
+ case 402:
247
+ code = "QUOTA_EXCEEDED";
248
+ break;
249
+ case 401:
250
+ code = "UNAUTHORIZED";
251
+ break;
252
+ case 403:
253
+ code = "FORBIDDEN";
254
+ break;
255
+ default:
256
+ code = "";
257
+ }
258
+ }
259
+ if (!message) {
260
+ message = `HTTP ${statusCode}`;
261
+ }
262
+ if (statusCode === 204 || statusCode === 404 || code === "NOT_FOUND") {
263
+ return new GeofenceNotFoundError(message, statusCode, details);
264
+ }
265
+ if (statusCode === 402 || code === "QUOTA_EXCEEDED") {
266
+ return new QuotaExceededError(message, statusCode, details);
267
+ }
268
+ if (statusCode === 401 || code === "UNAUTHORIZED" || code === "MISSING_API_KEY" || code === "MISSING_ORGANIZATION") {
269
+ return new AuthenticationError(message, statusCode, details);
270
+ }
271
+ if (statusCode === 403 || code === "FORBIDDEN") {
272
+ return new ForbiddenError(message, statusCode, details);
273
+ }
274
+ if (isSpatial) {
275
+ return new SpatialAPIError(statusCode, code, message, void 0, details);
276
+ }
277
+ return new APIError(statusCode, message);
278
+ }
279
+ function parseApiServiceError(statusCode, bodyText) {
280
+ let parsed = null;
281
+ try {
282
+ parsed = JSON.parse(bodyText);
283
+ } catch (e2) {
284
+ }
285
+ const container = parsed && typeof parsed === "object" ? parsed.error : void 0;
286
+ const details = Array.isArray(_optionalChain([container, 'optionalAccess', _7 => _7.details])) ? container.details : [];
287
+ let code = "";
288
+ let message = "";
289
+ if (container && typeof container === "object") {
290
+ code = _nullishCoalesce(container.status, () => ( ""));
291
+ message = _nullishCoalesce(container.message, () => ( ""));
292
+ const withReason = details.find((d) => _optionalChain([d, 'optionalAccess', _8 => _8.reason]));
293
+ if (_optionalChain([withReason, 'optionalAccess', _9 => _9.reason])) {
294
+ code = withReason.reason;
295
+ }
296
+ } else {
297
+ message = bodyText.trim();
298
+ }
299
+ if (!message) {
300
+ message = `HTTP ${statusCode}`;
301
+ }
302
+ switch (code) {
303
+ case "USER_NOT_FOUND":
304
+ case "USER_REVOKED":
305
+ return new UserNotFoundError(message, statusCode, code, details);
306
+ case "RULE_NOT_FOUND":
307
+ return new RuleNotFoundError(message, statusCode, code, details);
308
+ case "USER_ALREADY_EXISTS":
309
+ return new UserAlreadyExistsError(message, statusCode, code, details);
310
+ case "INVITATION_PENDING":
311
+ return new InvitationPendingError(message, statusCode, code, details);
312
+ case "LAST_ADMIN":
313
+ return new LastAdminError(message, statusCode, code, details);
314
+ case "LAST_SUBJECT":
315
+ return new LastSubjectError(message, statusCode, code, details);
316
+ case "QUOTA_EXCEEDED":
317
+ return new QuotaExceededError(message, statusCode, details);
318
+ case "MISSING_API_KEY":
319
+ case "MISSING_ORGANIZATION":
320
+ return new AuthenticationError(message, statusCode, details);
321
+ }
322
+ switch (statusCode) {
323
+ case 401:
324
+ return new AuthenticationError(message, statusCode, details);
325
+ case 403:
326
+ return new ForbiddenError(message, statusCode, details);
327
+ case 402:
328
+ return new QuotaExceededError(message, statusCode, details);
329
+ }
330
+ return new APIServiceError(statusCode, code, message, details);
331
+ }
332
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
333
+ function assertSecureServiceUrl(name, value) {
334
+ let parsed;
335
+ try {
336
+ parsed = new URL(value);
337
+ } catch (e3) {
338
+ throw new ValidationError(`GeoEngine: ${name} no es una URL v\xE1lida.`);
339
+ }
340
+ if (parsed.protocol === "https:") {
341
+ return;
342
+ }
343
+ if (parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname)) {
344
+ return;
345
+ }
346
+ throw new ValidationError(
347
+ `GeoEngine: ${name} debe usar https (http solo se permite para localhost, 127.0.0.1 o ::1).`
348
+ );
349
+ }
350
+ var HttpClient = class {
351
+ #apiKey;
352
+
353
+ constructor(options = {}) {
354
+ const defaultManagement = "https://management.geoengine.dev";
355
+ const defaultIngest = "https://ingest.geoengine.dev";
356
+ const defaultApiService = "https://api.geoengine.dev";
357
+ this.#apiKey = _nullishCoalesce(options.apiKey, () => ( ""));
358
+ const resolvedUrls = {
359
+ managementUrl: _nullishCoalesce(_nullishCoalesce(options.baseUrl, () => ( options.managementUrl)), () => ( defaultManagement)),
360
+ ingestUrl: _nullishCoalesce(_nullishCoalesce(options.baseUrl, () => ( options.ingestUrl)), () => ( defaultIngest)),
361
+ apiServiceUrl: _nullishCoalesce(_nullishCoalesce(options.baseUrl, () => ( options.apiServiceUrl)), () => ( defaultApiService))
362
+ };
363
+ const urlLabels = {
364
+ managementUrl: options.baseUrl !== void 0 ? "baseUrl" : "managementUrl",
365
+ ingestUrl: options.baseUrl !== void 0 ? "baseUrl" : "ingestUrl",
366
+ apiServiceUrl: options.baseUrl !== void 0 ? "baseUrl" : "apiServiceUrl"
367
+ };
368
+ for (const key of Object.keys(resolvedUrls)) {
369
+ assertSecureServiceUrl(urlLabels[key], resolvedUrls[key]);
370
+ }
371
+ this.config = {
372
+ jwtToken: options.jwtToken,
373
+ environment: _nullishCoalesce(options.environment, () => ( "live")),
374
+ ...resolvedUrls,
375
+ timeout: _nullishCoalesce(options.timeout, () => ( 1e4)),
376
+ identityTimeoutMs: _nullishCoalesce(options.identityTimeoutMs, () => ( 500)),
377
+ maxRetries: _nullishCoalesce(options.maxRetries, () => ( 2)),
378
+ batchSize: _nullishCoalesce(options.batchSize, () => ( 100)),
379
+ flushInterval: _nullishCoalesce(options.flushInterval, () => ( 500)),
380
+ bufferSize: _nullishCoalesce(options.bufferSize, () => ( 5e3)),
381
+ fetch: _nullishCoalesce(options.fetch, () => ( globalThis.fetch))
382
+ };
383
+ }
384
+ /** Removes the API key and JWT from text that may be echoed into error messages. */
385
+ #redact(text) {
386
+ let out = text;
387
+ for (const secret of [this.#apiKey, this.config.jwtToken]) {
388
+ if (secret && secret.trim() !== "") {
389
+ out = out.split(secret).join("[REDACTED]");
390
+ const trimmed = secret.trim();
391
+ if (trimmed !== secret) {
392
+ out = out.split(trimmed).join("[REDACTED]");
393
+ }
394
+ }
395
+ }
396
+ return out;
397
+ }
398
+ get options() {
399
+ return this.config;
400
+ }
401
+ toJSON() {
402
+ return {
403
+ apiKey: "[REDACTED]",
404
+ ...this.config.jwtToken ? { jwtToken: "[REDACTED]" } : {},
405
+ environment: this.config.environment,
406
+ managementUrl: this.config.managementUrl,
407
+ ingestUrl: this.config.ingestUrl,
408
+ apiServiceUrl: this.config.apiServiceUrl,
409
+ timeout: this.config.timeout,
410
+ identityTimeoutMs: this.config.identityTimeoutMs,
411
+ maxRetries: this.config.maxRetries,
412
+ batchSize: this.config.batchSize,
413
+ flushInterval: this.config.flushInterval,
414
+ bufferSize: this.config.bufferSize
415
+ };
416
+ }
417
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
418
+ return this.toJSON();
419
+ }
420
+ /**
421
+ * Executes an HTTP request with timeout, authentication headers and exponential backoff retry.
422
+ */
423
+ async request(opts) {
424
+ const method = _nullishCoalesce(opts.method, () => ( "POST"));
425
+ const timeoutMs = _nullishCoalesce(opts.timeout, () => ( this.config.timeout));
426
+ const maxRetries = opts.isApiService && method !== "GET" ? 0 : this.config.maxRetries;
427
+ let attempt = 0;
428
+ while (true) {
429
+ attempt++;
430
+ const controller = new globalThis.AbortController();
431
+ const timeoutId = globalThis.setTimeout(() => controller.abort(), timeoutMs);
432
+ const now = Date.now();
433
+ const headers = {
434
+ ...opts.isApiService ? { Accept: "application/json" } : { "Content-Type": "application/json" },
435
+ "X-API-Key": this.#apiKey,
436
+ "X-Geo-Environment": this.config.environment,
437
+ "X-Request-Time": now.toString(),
438
+ "X-Signature": generateHMACSignature(this.#apiKey, now),
439
+ "User-Agent": USER_AGENT
440
+ };
441
+ if (opts.isApiService && opts.body !== void 0) {
442
+ headers["Content-Type"] = "application/json";
443
+ }
444
+ if (this.config.jwtToken) {
445
+ headers["Authorization"] = `Bearer ${this.config.jwtToken}`;
446
+ }
447
+ try {
448
+ const response = await this.config.fetch(opts.endpoint, {
449
+ method,
450
+ headers,
451
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
452
+ signal: controller.signal,
453
+ // Never follow redirects: custom headers (X-API-Key, X-Signature) are not
454
+ // stripped by fetch on cross-origin redirects.
455
+ redirect: "manual"
456
+ });
457
+ globalThis.clearTimeout(timeoutId);
458
+ if (response.status === 204) {
459
+ if (opts.isSpatial) {
460
+ throw new GeofenceNotFoundError("geofence not found", 204);
461
+ }
462
+ return null;
463
+ }
464
+ if ((response.status === 429 || response.status >= 500) && attempt <= maxRetries) {
465
+ const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
466
+ await new Promise(
467
+ (resolve) => globalThis.setTimeout(() => resolve(), delay)
468
+ );
469
+ continue;
470
+ }
471
+ const responseText = this.#redact(await response.text());
472
+ if (!response.ok) {
473
+ throw opts.isApiService ? parseApiServiceError(response.status, responseText) : parseHttpError(response.status, responseText, opts.isSpatial);
474
+ }
475
+ if (!responseText || responseText.trim() === "") {
476
+ return null;
477
+ }
478
+ const json = JSON.parse(responseText);
479
+ if ((opts.isSpatial || opts.isApiService) && typeof json === "object" && json !== null && "success" in json) {
480
+ if (!json.success) {
481
+ throw opts.isApiService ? parseApiServiceError(response.status, responseText) : parseHttpError(response.status, responseText, true);
482
+ }
483
+ return json.data;
484
+ }
485
+ return json;
486
+ } catch (err) {
487
+ globalThis.clearTimeout(timeoutId);
488
+ if (err instanceof Error && err.name === "AbortError") {
489
+ throw new TimeoutError(timeoutMs);
490
+ }
491
+ if (err instanceof APIError) {
492
+ throw err;
493
+ }
494
+ if (attempt <= maxRetries) {
495
+ const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
496
+ await new Promise(
497
+ (resolve) => globalThis.setTimeout(() => resolve(), delay)
498
+ );
499
+ continue;
500
+ }
501
+ throw err;
502
+ }
503
+ }
504
+ }
505
+ };
506
+
507
+ // src/identity/errors.ts
508
+ var TRANSIENT_BRAND = /* @__PURE__ */ Symbol.for("geo-engine-node.IdentityTransientError");
509
+ var INTEGRATION_BRAND = /* @__PURE__ */ Symbol.for("geo-engine-node.IdentityIntegrationError");
510
+ function redactSecret(value, secret) {
511
+ if (value === void 0) {
512
+ return void 0;
513
+ }
514
+ let sanitized = value;
515
+ if (secret) {
516
+ sanitized = sanitized.split(secret).join("[REDACTED]");
517
+ const trimmed = secret.trim();
518
+ if (trimmed && trimmed !== secret) {
519
+ sanitized = sanitized.split(trimmed).join("[REDACTED]");
520
+ }
521
+ }
522
+ return sanitized;
523
+ }
524
+ function buildSafeErrorPayload(name, message, fields) {
525
+ return {
526
+ name,
527
+ code: fields.code,
528
+ message,
529
+ status: fields.status,
530
+ type: fields.type,
531
+ title: fields.title,
532
+ detail: fields.detail,
533
+ requestId: fields.requestId,
534
+ reason: fields.reason
535
+ };
536
+ }
537
+ var IdentityTransientError = (_class = class extends GeoEngineError {
538
+
539
+
540
+
541
+
542
+
543
+
544
+ /** Stable machine-readable code; the contract between ESM and CJS builds. */
545
+ __init() {this.code = "IDENTITY_TRANSIENT"}
546
+ __init2() {this[TRANSIENT_BRAND] = true}
547
+ static [Symbol.hasInstance](instance) {
548
+ return typeof instance === "object" && instance !== null && TRANSIENT_BRAND in instance;
549
+ }
550
+ constructor(fields) {
551
+ const safeMessage = _nullishCoalesce(redactSecret(fields.message, fields.apiKeyToRedact), () => ( "GeoIdentity transient error"));
552
+ super(safeMessage);_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;
553
+ this.name = "IdentityTransientError";
554
+ this.status = fields.status;
555
+ this.type = redactSecret(fields.type, fields.apiKeyToRedact);
556
+ this.title = redactSecret(fields.title, fields.apiKeyToRedact);
557
+ this.detail = redactSecret(fields.detail, fields.apiKeyToRedact);
558
+ this.requestId = redactSecret(fields.requestId, fields.apiKeyToRedact);
559
+ this.reason = fields.reason;
560
+ }
561
+ toJSON() {
562
+ return buildSafeErrorPayload(this.name, this.message, this);
563
+ }
564
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
565
+ return this.toJSON();
566
+ }
567
+ }, _class);
568
+ var IdentityIntegrationError = (_class2 = class extends GeoEngineError {
569
+
570
+
571
+
572
+
573
+
574
+
575
+ /** Stable machine-readable code; the contract between ESM and CJS builds. */
576
+ __init3() {this.code = "IDENTITY_INTEGRATION"}
577
+ __init4() {this[INTEGRATION_BRAND] = true}
578
+ static [Symbol.hasInstance](instance) {
579
+ return typeof instance === "object" && instance !== null && INTEGRATION_BRAND in instance;
580
+ }
581
+ constructor(fields) {
582
+ const safeMessage = _nullishCoalesce(redactSecret(fields.message, fields.apiKeyToRedact), () => ( "GeoIdentity integration error"));
583
+ super(safeMessage);_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);;
584
+ this.name = "IdentityIntegrationError";
585
+ this.status = fields.status;
586
+ this.type = redactSecret(fields.type, fields.apiKeyToRedact);
587
+ this.title = redactSecret(fields.title, fields.apiKeyToRedact);
588
+ this.detail = redactSecret(fields.detail, fields.apiKeyToRedact);
589
+ this.requestId = redactSecret(fields.requestId, fields.apiKeyToRedact);
590
+ this.reason = fields.reason;
591
+ }
592
+ toJSON() {
593
+ return buildSafeErrorPayload(this.name, this.message, this);
594
+ }
595
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
596
+ return this.toJSON();
597
+ }
598
+ }, _class2);
599
+ function isTransient(err) {
600
+ return typeof err === "object" && err !== null && TRANSIENT_BRAND in err;
601
+ }
602
+
603
+ // src/identity/runtime.ts
604
+ function assertServerEnvironment() {
605
+ if (typeof globalThis.window !== "undefined") {
606
+ throw new GeoEngineError(
607
+ "geoengine/identity: /v1 es solo de servidor y no puede usarse en un navegador porque la API key es secreta y /v1 no admite peticiones desde navegador (CORS)."
608
+ );
609
+ }
610
+ }
611
+
612
+ // src/identity/evaluate.ts
613
+
614
+ var DEFAULT_IDENTITY_TIMEOUT_MS = 500;
615
+ var MIN_RETRY_BUDGET_MS = 10;
616
+ var RETRY_SAFETY_MARGIN_MS = 5;
617
+ function isPlainObject(value) {
618
+ return typeof value === "object" && value !== null && !Array.isArray(value);
619
+ }
620
+ function isNonEmptyString(value) {
621
+ return typeof value === "string" && value.trim().length > 0;
622
+ }
623
+ function parseProblemJson(contentType, rawBody) {
624
+ const mediaType = (_nullishCoalesce(contentType.split(";", 1)[0], () => ( ""))).trim().toLowerCase();
625
+ if (mediaType !== "application/problem+json") {
626
+ return null;
627
+ }
628
+ let parsed;
629
+ try {
630
+ parsed = JSON.parse(rawBody);
631
+ } catch (e4) {
632
+ return null;
633
+ }
634
+ if (!isPlainObject(parsed)) {
635
+ return null;
636
+ }
637
+ const result = {};
638
+ if (typeof parsed.type === "string") {
639
+ result.type = parsed.type;
640
+ }
641
+ if (typeof parsed.title === "string") {
642
+ result.title = parsed.title;
643
+ }
644
+ if (typeof parsed.status === "number" && Number.isInteger(parsed.status)) {
645
+ result.status = parsed.status;
646
+ }
647
+ if (typeof parsed.detail === "string") {
648
+ result.detail = parsed.detail;
649
+ }
650
+ if (typeof parsed.request_id === "string") {
651
+ result.request_id = parsed.request_id;
652
+ }
653
+ return result;
654
+ }
655
+ function parseRuleRef(value) {
656
+ if (!isPlainObject(value)) {
657
+ return null;
658
+ }
659
+ if (typeof value.id !== "string" || typeof value.name !== "string" || typeof value.priority !== "number" || !Number.isFinite(value.priority)) {
660
+ return null;
661
+ }
662
+ return {
663
+ id: value.id,
664
+ name: value.name,
665
+ priority: value.priority
666
+ };
667
+ }
668
+ function parseShadowMatches(value) {
669
+ if (!Array.isArray(value)) {
670
+ return null;
671
+ }
672
+ const matches = [];
673
+ for (const entry of value) {
674
+ if (!isPlainObject(entry)) {
675
+ return null;
676
+ }
677
+ const rule = parseRuleRef(entry.rule);
678
+ if (!rule || typeof entry.would_decide !== "string") {
679
+ return null;
680
+ }
681
+ const shadowMatch = {
682
+ rule,
683
+ would_decide: entry.would_decide
684
+ };
685
+ if (entry.signals !== void 0) {
686
+ if (!Array.isArray(entry.signals) || !entry.signals.every((s) => typeof s === "string")) {
687
+ return null;
688
+ }
689
+ shadowMatch.signals = [...entry.signals];
690
+ }
691
+ matches.push(shadowMatch);
692
+ }
693
+ return matches;
694
+ }
695
+ function parseEvaluateMeta(value) {
696
+ if (!isPlainObject(value)) {
697
+ return null;
698
+ }
699
+ if (typeof value.config_version !== "number" || !Number.isFinite(value.config_version) || typeof value.stale !== "boolean" || typeof value.config_age_s !== "number" || !Number.isFinite(value.config_age_s) || typeof value.source !== "string" || typeof value.evaluated_at !== "string") {
700
+ return null;
701
+ }
702
+ const meta = {
703
+ config_version: value.config_version,
704
+ stale: value.stale,
705
+ config_age_s: value.config_age_s,
706
+ source: value.source,
707
+ evaluated_at: value.evaluated_at
708
+ };
709
+ if (typeof value.request_id === "string") {
710
+ meta.request_id = value.request_id;
711
+ }
712
+ if (typeof value.reputation === "string") {
713
+ meta.reputation = value.reputation;
714
+ }
715
+ return meta;
716
+ }
717
+ function parseEvaluateResponse(rawBody) {
718
+ let parsed;
719
+ try {
720
+ parsed = JSON.parse(rawBody);
721
+ } catch (e5) {
722
+ return null;
723
+ }
724
+ if (!isPlainObject(parsed)) {
725
+ return null;
726
+ }
727
+ if (typeof parsed.decision !== "string" || parsed.decision.length === 0) {
728
+ return null;
729
+ }
730
+ let matchedRule = null;
731
+ if (parsed.matched_rule !== null) {
732
+ matchedRule = parseRuleRef(parsed.matched_rule);
733
+ if (!matchedRule) {
734
+ return null;
735
+ }
736
+ }
737
+ if (typeof parsed.default_applied !== "boolean" || typeof parsed.reason !== "string") {
738
+ return null;
739
+ }
740
+ if (!Array.isArray(parsed.signals) || !parsed.signals.every((s) => typeof s === "string")) {
741
+ return null;
742
+ }
743
+ const shadowMatches = parseShadowMatches(parsed.shadow_matches);
744
+ if (!shadowMatches) {
745
+ return null;
746
+ }
747
+ const meta = parseEvaluateMeta(parsed.meta);
748
+ if (!meta) {
749
+ return null;
750
+ }
751
+ let challenge;
752
+ if (parsed.challenge !== void 0 && parsed.challenge !== null) {
753
+ if (!isPlainObject(parsed.challenge)) {
754
+ return null;
755
+ }
756
+ challenge = {};
757
+ if (typeof parsed.challenge.hint === "string") {
758
+ challenge.hint = parsed.challenge.hint;
759
+ }
760
+ }
761
+ const result = {
762
+ decision: parsed.decision,
763
+ matched_rule: matchedRule,
764
+ default_applied: parsed.default_applied,
765
+ reason: parsed.reason,
766
+ signals: [...parsed.signals],
767
+ shadow_matches: shadowMatches,
768
+ meta
769
+ };
770
+ if (challenge !== void 0) {
771
+ result.challenge = challenge;
772
+ }
773
+ return result;
774
+ }
775
+ function buildRequestPayload(request) {
776
+ const subjectPayload = {};
777
+ if (request.subject.user_id !== void 0) {
778
+ subjectPayload.user_id = request.subject.user_id;
779
+ }
780
+ if (request.subject.device_id !== void 0) {
781
+ subjectPayload.device_id = request.subject.device_id;
782
+ }
783
+ if (request.subject.roles !== void 0) {
784
+ subjectPayload.roles = request.subject.roles;
785
+ }
786
+ const payload = {
787
+ scope: request.scope,
788
+ subject: subjectPayload
789
+ };
790
+ if (request.context !== void 0 && request.context !== null) {
791
+ const contextPayload = {};
792
+ if (request.context.ip !== void 0) {
793
+ contextPayload.ip = request.context.ip;
794
+ }
795
+ if (request.context.location !== void 0 && request.context.location !== null) {
796
+ const loc = request.context.location;
797
+ const locationPayload = {
798
+ lat: loc.lat,
799
+ lng: loc.lng
800
+ };
801
+ if (loc.accuracy_m !== void 0) {
802
+ locationPayload.accuracy_m = loc.accuracy_m;
803
+ }
804
+ if (loc.source !== void 0) {
805
+ locationPayload.source = loc.source;
806
+ }
807
+ if (loc.captured_at !== void 0) {
808
+ locationPayload.captured_at = loc.captured_at;
809
+ }
810
+ contextPayload.location = locationPayload;
811
+ }
812
+ payload.context = contextPayload;
813
+ }
814
+ return payload;
815
+ }
816
+ function mapIntegrationReason(status, problemType) {
817
+ if (problemType) {
818
+ const prefix = "urn:geoengine:problem:";
819
+ const slug = problemType.startsWith(prefix) ? problemType.slice(prefix.length) : problemType;
820
+ switch (slug) {
821
+ case "unauthorized":
822
+ return "unauthorized";
823
+ case "malformed-request":
824
+ return "malformed_request";
825
+ case "invalid-request":
826
+ return "invalid_request";
827
+ case "scope-not-found":
828
+ return "scope_not_found";
829
+ default:
830
+ break;
831
+ }
832
+ }
833
+ switch (status) {
834
+ case 400:
835
+ return "malformed_request";
836
+ case 401:
837
+ return "unauthorized";
838
+ case 403:
839
+ return "forbidden";
840
+ case 404:
841
+ return "not_found";
842
+ case 422:
843
+ return "invalid_request";
844
+ default:
845
+ return status >= 400 && status < 500 ? "client_error" : "unexpected_response";
846
+ }
847
+ }
848
+ function parseRetryAfterMs(headerValue) {
849
+ if (headerValue === null) {
850
+ return null;
851
+ }
852
+ const trimmed = headerValue.trim();
853
+ if (trimmed === "") {
854
+ return null;
855
+ }
856
+ if (/^\d+$/.test(trimmed)) {
857
+ const seconds = Number(trimmed);
858
+ return Number.isFinite(seconds) ? seconds * 1e3 : null;
859
+ }
860
+ const targetTime = Date.parse(trimmed);
861
+ if (Number.isNaN(targetTime)) {
862
+ return null;
863
+ }
864
+ return Math.max(0, targetTime - Date.now());
865
+ }
866
+ function computeJitterDelayMs(remainingMs) {
867
+ if (remainingMs <= MIN_RETRY_BUDGET_MS) {
868
+ return null;
869
+ }
870
+ const rawJitter = 10 + Math.random() * 40;
871
+ const maxAllowed = Math.max(0, Math.floor(remainingMs / 3));
872
+ const delay = Math.min(rawJitter, maxAllowed);
873
+ return remainingMs - delay >= MIN_RETRY_BUDGET_MS ? Math.floor(delay) : null;
874
+ }
875
+ function sleepAbortable(ms, signal) {
876
+ if (_optionalChain([signal, 'optionalAccess', _10 => _10.aborted])) {
877
+ return Promise.resolve(false);
878
+ }
879
+ if (ms <= 0) {
880
+ return Promise.resolve(true);
881
+ }
882
+ return new Promise((resolve) => {
883
+ const onAbort = () => {
884
+ clearTimeout(timer);
885
+ resolve(false);
886
+ };
887
+ const timer = setTimeout(() => {
888
+ _optionalChain([signal, 'optionalAccess', _11 => _11.removeEventListener, 'call', _12 => _12("abort", onAbort)]);
889
+ resolve(true);
890
+ }, ms);
891
+ _optionalChain([signal, 'optionalAccess', _13 => _13.addEventListener, 'call', _14 => _14("abort", onAbort, { once: true })]);
892
+ });
893
+ }
894
+ async function readTextWithAbort(response, signal) {
895
+ if (signal.aborted) {
896
+ const abortErr = new Error("The operation was aborted.");
897
+ abortErr.name = "AbortError";
898
+ throw abortErr;
899
+ }
900
+ return new Promise((resolve, reject) => {
901
+ let settled = false;
902
+ const onAbort = () => {
903
+ if (settled) {
904
+ return;
905
+ }
906
+ settled = true;
907
+ const abortErr = new Error("The operation was aborted.");
908
+ abortErr.name = "AbortError";
909
+ reject(abortErr);
910
+ };
911
+ signal.addEventListener("abort", onAbort, { once: true });
912
+ Promise.resolve(response.text()).then(
913
+ (text) => {
914
+ if (settled) {
915
+ return;
916
+ }
917
+ settled = true;
918
+ signal.removeEventListener("abort", onAbort);
919
+ resolve(text);
920
+ },
921
+ (err) => {
922
+ if (settled) {
923
+ return;
924
+ }
925
+ settled = true;
926
+ signal.removeEventListener("abort", onAbort);
927
+ reject(err);
928
+ }
929
+ );
930
+ });
931
+ }
932
+ var IdentityService = class {
933
+ #getBaseUrl;
934
+ #getApiKey;
935
+ #getTimeoutMs;
936
+ #getFetch;
937
+ #isClosed;
938
+ constructor(config) {
939
+ this.#getBaseUrl = config.getBaseUrl;
940
+ this.#getApiKey = config.getApiKey;
941
+ this.#getTimeoutMs = config.getTimeoutMs;
942
+ this.#getFetch = config.getFetch;
943
+ this.#isClosed = config.isClosed;
944
+ }
945
+ toJSON() {
946
+ return {
947
+ service: "IdentityService",
948
+ apiKey: "[REDACTED]"
949
+ };
950
+ }
951
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
952
+ return this.toJSON();
953
+ }
954
+ /**
955
+ * Calls `POST /v1/evaluate` with Bearer authentication, X-Request-Id tracking,
956
+ * a total deadline (default 500ms), and at most one retry for transient failures.
957
+ * Never applies `failOpen` directly; throws typed transient or integration errors.
958
+ */
959
+ async evaluate(request, options) {
960
+ assertServerEnvironment();
961
+ if (this.#isClosed()) {
962
+ throw new ClientClosedError();
963
+ }
964
+ const apiKey = this.#getApiKey();
965
+ if (!isPlainObject(request) || !isNonEmptyString(request.scope)) {
966
+ throw new IdentityIntegrationError({
967
+ message: "GeoIdentity: scope es requerido y debe ser una cadena no vac\xEDa",
968
+ reason: "invalid_request",
969
+ apiKeyToRedact: apiKey
970
+ });
971
+ }
972
+ if (!isPlainObject(request.subject) || !isNonEmptyString(request.subject.user_id) && !isNonEmptyString(request.subject.device_id)) {
973
+ throw new IdentityIntegrationError({
974
+ message: "GeoIdentity: subject requiere al menos user_id o device_id",
975
+ reason: "invalid_request",
976
+ apiKeyToRedact: apiKey
977
+ });
978
+ }
979
+ const timeoutMs = _nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.timeoutMs]), () => ( this.#getTimeoutMs())), () => ( DEFAULT_IDENTITY_TIMEOUT_MS));
980
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
981
+ throw new IdentityIntegrationError({
982
+ message: "GeoIdentity: timeoutMs debe ser un n\xFAmero finito mayor a 0",
983
+ reason: "configuration_error",
984
+ apiKeyToRedact: apiKey
985
+ });
986
+ }
987
+ if (_optionalChain([options, 'optionalAccess', _16 => _16.requestId]) !== void 0 && typeof options.requestId !== "string") {
988
+ throw new IdentityIntegrationError({
989
+ message: "GeoIdentity: requestId debe ser una cadena de texto",
990
+ reason: "invalid_request",
991
+ apiKeyToRedact: apiKey
992
+ });
993
+ }
994
+ const requestId = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _17 => _17.requestId]), () => ( _crypto.randomUUID.call(void 0, )));
995
+ const endpoint = `${this.#getBaseUrl().replace(/\/+$/, "")}/v1/evaluate`;
996
+ const bodyJson = JSON.stringify(buildRequestPayload(request));
997
+ const fetchFn = this.#getFetch();
998
+ const headers = {
999
+ Authorization: `Bearer ${apiKey}`,
1000
+ "Content-Type": "application/json",
1001
+ Accept: "application/json, application/problem+json",
1002
+ "X-Request-Id": requestId,
1003
+ "User-Agent": USER_AGENT
1004
+ };
1005
+ const deadline = Date.now() + timeoutMs;
1006
+ for (let attempt = 1; attempt <= 2; attempt++) {
1007
+ if (_optionalChain([options, 'optionalAccess', _18 => _18.signal, 'optionalAccess', _19 => _19.aborted])) {
1008
+ throw new IdentityTransientError({
1009
+ message: "GeoIdentity: evaluaci\xF3n cancelada por AbortSignal",
1010
+ requestId,
1011
+ reason: "timeout",
1012
+ apiKeyToRedact: apiKey
1013
+ });
1014
+ }
1015
+ const remainingMs = deadline - Date.now();
1016
+ if (remainingMs <= 0) {
1017
+ throw new IdentityTransientError({
1018
+ message: `GeoIdentity: tiempo de espera agotado (${timeoutMs}ms)`,
1019
+ requestId,
1020
+ reason: "timeout",
1021
+ apiKeyToRedact: apiKey
1022
+ });
1023
+ }
1024
+ const controller = new AbortController();
1025
+ let onExternalAbort;
1026
+ if (_optionalChain([options, 'optionalAccess', _20 => _20.signal])) {
1027
+ onExternalAbort = () => controller.abort();
1028
+ options.signal.addEventListener("abort", onExternalAbort, { once: true });
1029
+ }
1030
+ const timeoutId = setTimeout(() => controller.abort(), remainingMs);
1031
+ try {
1032
+ const response = await fetchFn(endpoint, {
1033
+ method: "POST",
1034
+ headers,
1035
+ body: bodyJson,
1036
+ signal: controller.signal,
1037
+ redirect: "manual"
1038
+ });
1039
+ const rawBody = await readTextWithAbort(response, controller.signal);
1040
+ const contentType = _nullishCoalesce(_optionalChain([response, 'access', _21 => _21.headers, 'optionalAccess', _22 => _22.get, 'call', _23 => _23("content-type")]), () => ( ""));
1041
+ const echoedRequestId = _optionalChain([response, 'access', _24 => _24.headers, 'optionalAccess', _25 => _25.get, 'call', _26 => _26("x-request-id")]) || void 0;
1042
+ const problem = parseProblemJson(contentType, rawBody);
1043
+ const effectiveRequestId = _optionalChain([problem, 'optionalAccess', _27 => _27.request_id]) || echoedRequestId || requestId;
1044
+ if (response.status === 200) {
1045
+ const parsed = parseEvaluateResponse(rawBody);
1046
+ if (!parsed) {
1047
+ throw new IdentityIntegrationError({
1048
+ message: "GeoIdentity: forma de respuesta inesperada en HTTP 200",
1049
+ status: 200,
1050
+ requestId: _nullishCoalesce(echoedRequestId, () => ( requestId)),
1051
+ reason: "unexpected_response",
1052
+ apiKeyToRedact: apiKey
1053
+ });
1054
+ }
1055
+ return parsed;
1056
+ }
1057
+ if (response.status === 429) {
1058
+ const retryAfterHeader = _nullishCoalesce(_optionalChain([response, 'access', _28 => _28.headers, 'optionalAccess', _29 => _29.get, 'call', _30 => _30("retry-after")]), () => ( null));
1059
+ const rateLimitErr = new IdentityTransientError({
1060
+ message: _optionalChain([problem, 'optionalAccess', _31 => _31.detail]) || _optionalChain([problem, 'optionalAccess', _32 => _32.title]) || "GeoIdentity: l\xEDmite de peticiones excedido (HTTP 429)",
1061
+ status: 429,
1062
+ type: _optionalChain([problem, 'optionalAccess', _33 => _33.type]),
1063
+ title: _optionalChain([problem, 'optionalAccess', _34 => _34.title]),
1064
+ detail: _optionalChain([problem, 'optionalAccess', _35 => _35.detail]),
1065
+ requestId: effectiveRequestId,
1066
+ reason: "rate_limited",
1067
+ apiKeyToRedact: apiKey
1068
+ });
1069
+ if (attempt >= 2) {
1070
+ throw rateLimitErr;
1071
+ }
1072
+ const nowRemaining = deadline - Date.now();
1073
+ let waitMs;
1074
+ if (retryAfterHeader !== null && retryAfterHeader.trim() !== "") {
1075
+ const parsedRetryAfter = parseRetryAfterMs(retryAfterHeader);
1076
+ if (parsedRetryAfter === null || parsedRetryAfter + RETRY_SAFETY_MARGIN_MS >= nowRemaining) {
1077
+ throw rateLimitErr;
1078
+ }
1079
+ waitMs = parsedRetryAfter;
1080
+ } else {
1081
+ waitMs = computeJitterDelayMs(nowRemaining);
1082
+ if (waitMs === null) {
1083
+ throw rateLimitErr;
1084
+ }
1085
+ }
1086
+ const slept = await sleepAbortable(waitMs, _optionalChain([options, 'optionalAccess', _36 => _36.signal]));
1087
+ if (!slept) {
1088
+ throw new IdentityTransientError({
1089
+ message: "GeoIdentity: evaluaci\xF3n cancelada durante espera de reintento",
1090
+ requestId: effectiveRequestId,
1091
+ reason: "timeout",
1092
+ apiKeyToRedact: apiKey
1093
+ });
1094
+ }
1095
+ continue;
1096
+ }
1097
+ if (response.status >= 500) {
1098
+ const serverErr = new IdentityTransientError({
1099
+ message: _optionalChain([problem, 'optionalAccess', _37 => _37.detail]) || _optionalChain([problem, 'optionalAccess', _38 => _38.title]) || `GeoIdentity: error transitorio del servidor (HTTP ${response.status})`,
1100
+ status: response.status,
1101
+ type: _optionalChain([problem, 'optionalAccess', _39 => _39.type]),
1102
+ title: _optionalChain([problem, 'optionalAccess', _40 => _40.title]),
1103
+ detail: _optionalChain([problem, 'optionalAccess', _41 => _41.detail]),
1104
+ requestId: effectiveRequestId,
1105
+ reason: "server_error",
1106
+ apiKeyToRedact: apiKey
1107
+ });
1108
+ if (attempt >= 2) {
1109
+ throw serverErr;
1110
+ }
1111
+ const waitMs = computeJitterDelayMs(deadline - Date.now());
1112
+ if (waitMs === null) {
1113
+ throw serverErr;
1114
+ }
1115
+ const slept = await sleepAbortable(waitMs, _optionalChain([options, 'optionalAccess', _42 => _42.signal]));
1116
+ if (!slept) {
1117
+ throw new IdentityTransientError({
1118
+ message: "GeoIdentity: evaluaci\xF3n cancelada durante espera de reintento",
1119
+ requestId: effectiveRequestId,
1120
+ reason: "timeout",
1121
+ apiKeyToRedact: apiKey
1122
+ });
1123
+ }
1124
+ continue;
1125
+ }
1126
+ if (response.status === 403 && !problem) {
1127
+ throw new IdentityIntegrationError({
1128
+ message: "GeoIdentity: bloqueado en el borde (HTTP 403)",
1129
+ status: 403,
1130
+ requestId: _nullishCoalesce(echoedRequestId, () => ( requestId)),
1131
+ reason: "edge_forbidden",
1132
+ apiKeyToRedact: apiKey
1133
+ });
1134
+ }
1135
+ throw new IdentityIntegrationError({
1136
+ message: _optionalChain([problem, 'optionalAccess', _43 => _43.detail]) || _optionalChain([problem, 'optionalAccess', _44 => _44.title]) || `GeoIdentity: error de integraci\xF3n (HTTP ${response.status})`,
1137
+ status: response.status,
1138
+ type: _optionalChain([problem, 'optionalAccess', _45 => _45.type]),
1139
+ title: _optionalChain([problem, 'optionalAccess', _46 => _46.title]),
1140
+ detail: _optionalChain([problem, 'optionalAccess', _47 => _47.detail]),
1141
+ requestId: effectiveRequestId,
1142
+ reason: mapIntegrationReason(response.status, _optionalChain([problem, 'optionalAccess', _48 => _48.type])),
1143
+ apiKeyToRedact: apiKey
1144
+ });
1145
+ } catch (err) {
1146
+ if (err instanceof IdentityIntegrationError || err instanceof IdentityTransientError) {
1147
+ throw err;
1148
+ }
1149
+ if (controller.signal.aborted || err instanceof Error && err.name === "AbortError") {
1150
+ throw new IdentityTransientError({
1151
+ message: `GeoIdentity: tiempo de espera agotado (${timeoutMs}ms)`,
1152
+ requestId,
1153
+ reason: "timeout",
1154
+ apiKeyToRedact: apiKey
1155
+ });
1156
+ }
1157
+ const networkErr = new IdentityTransientError({
1158
+ message: "GeoIdentity: error de red al evaluar la identidad",
1159
+ requestId,
1160
+ reason: "network",
1161
+ apiKeyToRedact: apiKey
1162
+ });
1163
+ if (attempt >= 2) {
1164
+ throw networkErr;
1165
+ }
1166
+ const waitMs = computeJitterDelayMs(deadline - Date.now());
1167
+ if (waitMs === null) {
1168
+ throw networkErr;
1169
+ }
1170
+ const slept = await sleepAbortable(waitMs, _optionalChain([options, 'optionalAccess', _49 => _49.signal]));
1171
+ if (!slept) {
1172
+ throw new IdentityTransientError({
1173
+ message: "GeoIdentity: evaluaci\xF3n cancelada durante espera de reintento",
1174
+ requestId,
1175
+ reason: "timeout",
1176
+ apiKeyToRedact: apiKey
1177
+ });
1178
+ }
1179
+ } finally {
1180
+ clearTimeout(timeoutId);
1181
+ if (_optionalChain([options, 'optionalAccess', _50 => _50.signal]) && onExternalAbort) {
1182
+ options.signal.removeEventListener("abort", onExternalAbort);
1183
+ }
1184
+ }
1185
+ }
1186
+ throw new IdentityTransientError({
1187
+ message: `GeoIdentity: tiempo de espera agotado (${timeoutMs}ms)`,
1188
+ requestId,
1189
+ reason: "timeout",
1190
+ apiKeyToRedact: apiKey
1191
+ });
1192
+ }
1193
+ };
1194
+
1195
+
1196
+
1197
+
1198
+
1199
+
1200
+
1201
+
1202
+
1203
+
1204
+
1205
+
1206
+
1207
+
1208
+
1209
+
1210
+
1211
+
1212
+
1213
+
1214
+
1215
+
1216
+
1217
+
1218
+
1219
+
1220
+
1221
+
1222
+
1223
+
1224
+
1225
+
1226
+
1227
+
1228
+
1229
+
1230
+ exports.GeoEngineError = GeoEngineError; exports.ClientClosedError = ClientClosedError; exports.ValidationError = ValidationError; exports.DeviceIDRequiredError = DeviceIDRequiredError; exports.GeofenceIDRequiredError = GeofenceIDRequiredError; exports.InvalidLatitudeError = InvalidLatitudeError; exports.InvalidLongitudeError = InvalidLongitudeError; exports.InvalidCoordinatesError = InvalidCoordinatesError; exports.APIError = APIError; exports.SpatialAPIError = SpatialAPIError; exports.GeofenceNotFoundError = GeofenceNotFoundError; exports.QuotaExceededError = QuotaExceededError; exports.AuthenticationError = AuthenticationError; exports.ForbiddenError = ForbiddenError; exports.TimeoutError = TimeoutError; exports.UserIDRequiredError = UserIDRequiredError; exports.RuleIDRequiredError = RuleIDRequiredError; exports.RuleNameRequiredError = RuleNameRequiredError; exports.EmailRequiredError = EmailRequiredError; exports.RoleRequiredError = RoleRequiredError; exports.APIServiceError = APIServiceError; exports.UserNotFoundError = UserNotFoundError; exports.RuleNotFoundError = RuleNotFoundError; exports.UserAlreadyExistsError = UserAlreadyExistsError; exports.InvitationPendingError = InvitationPendingError; exports.LastAdminError = LastAdminError; exports.LastSubjectError = LastSubjectError; exports.generateHMACSignature = generateHMACSignature; exports.HttpClient = HttpClient; exports.IdentityTransientError = IdentityTransientError; exports.IdentityIntegrationError = IdentityIntegrationError; exports.isTransient = isTransient; exports.assertServerEnvironment = assertServerEnvironment; exports.IdentityService = IdentityService;
1231
+ //# sourceMappingURL=chunk-A6RGK4MA.cjs.map