@superrouteca/smap 1.1.6 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/smap.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! sMap Web SDK 1.1.6. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
1
+ /*! sMap Web SDK 1.1.7. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
2
2
  (function () {
3
3
  function smapCreateEngine() {
4
4
  var SMAP_BASE_URL = (typeof document !== 'undefined' && document.baseURI) || (typeof location !== 'undefined' && location.href) || 'about:blank';
@@ -28361,6 +28361,24 @@ function smapCreatePlan() {
28361
28361
  // its Origin; a native app also names itself with X-SMap-App (and X-SMap-App-Cert on Android).
28362
28362
 
28363
28363
  var DEFAULT_BASE = 'https://open.superroute.ca';
28364
+ // The sMap service a map key's configuration is read from (GET <smap>/plan/v1/config), unless the editor is told another.
28365
+ var DEFAULT_SMAP = 'https://tile.srsr.ca';
28366
+ // Fast path (OPEN-ROUTE-EDIT E19, §2f.5): a call there not answered within this long is repeated on the standard path.
28367
+ // Per call, in this one place: every call 2 s, except refine (its search runs up to 2 s inside sRoad, and sMap's own
28368
+ // refine budget is 4 s) 5 s.
28369
+ var FAST_PATH_TIMEOUT_MS = 2000;
28370
+ var FAST_PATH_REFINE_TIMEOUT_MS = 5000;
28371
+ /** The fast-path time limit of a call (`path` after /v1/plan), from the defaults or the options that replace them. */
28372
+ function fastPathTimeoutFor(path, o) {
28373
+ var refine = path === '/refine';
28374
+ var given = refine ? o.fastPathRefineTimeout : o.fastPathTimeout;
28375
+ if (typeof given === 'number' && given > 0) { return given; }
28376
+ return refine ? FAST_PATH_REFINE_TIMEOUT_MS : FAST_PATH_TIMEOUT_MS;
28377
+ }
28378
+ // A map key's configuration is kept this long; one that could not be read is asked for again after RETRY.
28379
+ var KEY_CONFIG_TTL_MS = 600000;
28380
+ var KEY_CONFIG_RETRY_MS = 60000;
28381
+ var PLAN_PREFIX = '/v1/plan';
28364
28382
  // A token whose expiry can be read is renewed this many seconds before it ends.
28365
28383
  var RENEW_BEFORE = 30;
28366
28384
  var TOKEN_PREFIX = 'sr_pet_';
@@ -28383,19 +28401,27 @@ function smapCreatePlan() {
28383
28401
  /**
28384
28402
  * What a token provider gave: the token string, or the token answer of POST /v1/plan/token
28385
28403
  * ({ access_token, token_type, expires_in, expires_at, scopes, origins }, or that answer's `{ data }` envelope).
28386
- * Returns { token, exp } with exp in Unix seconds (0 when it cannot be told).
28404
+ * Returns { token, exp, fastPath } with exp in Unix seconds (0 when it cannot be told) and fastPath the answer's
28405
+ * `fast_path.url` (null without one: every call goes to the standard path).
28387
28406
  */
28388
28407
  function readToken(t) {
28389
28408
  if (t && typeof t === 'object' && t.data && typeof t.data === 'object' && !t.access_token) { t = t.data; }
28390
- if (typeof t === 'string' && t) { return { token: t, exp: tokenExpiry(t) }; }
28409
+ if (typeof t === 'string' && t) { return { token: t, exp: tokenExpiry(t), fastPath: null }; }
28391
28410
  if (t && typeof t === 'object' && typeof t.access_token === 'string' && t.access_token) {
28392
28411
  var exp = t.expires_at ? Date.parse(t.expires_at) / 1000 : 0;
28393
28412
  if (!exp && typeof t.expires_in === 'number') { exp = Date.now() / 1000 + t.expires_in; }
28394
- return { token: t.access_token, exp: exp || tokenExpiry(t.access_token) };
28413
+ return { token: t.access_token, exp: exp || tokenExpiry(t.access_token), fastPath: fastPathOf(t) };
28395
28414
  }
28396
28415
  return null;
28397
28416
  }
28398
28417
 
28418
+ /** The fast-path address of a token answer or a map key's configuration (`fast_path.url`), or null. */
28419
+ function fastPathOf(o) {
28420
+ var f = o && typeof o === 'object' ? o.fast_path : null;
28421
+ var url = f && typeof f === 'object' && typeof f.url === 'string' ? f.url.replace(/\/+$/, '') : '';
28422
+ return url ? url : null;
28423
+ }
28424
+
28399
28425
  /** The app headers of a native app: options.app is 'android:<package>' / 'apple:<bundle id>' / 'windows:<id>', or { id, cert }. */
28400
28426
  function appHeaders(app) {
28401
28427
  var h = {};
@@ -28414,6 +28440,7 @@ function smapCreatePlan() {
28414
28440
  if (c && typeof c.token === 'function') {
28415
28441
  var token = null;
28416
28442
  var exp = 0;
28443
+ var fast = null;
28417
28444
  var pending = null;
28418
28445
  var fetchToken = function () {
28419
28446
  if (!pending) {
@@ -28423,6 +28450,7 @@ function smapCreatePlan() {
28423
28450
  if (!read) { throw new Error('sMap plan editor: the token provider gave no token'); }
28424
28451
  token = read.token;
28425
28452
  exp = read.exp;
28453
+ fast = read.fastPath;
28426
28454
  return token;
28427
28455
  }, function (e) { pending = null; throw e; });
28428
28456
  }
@@ -28436,6 +28464,8 @@ function smapCreatePlan() {
28436
28464
  },
28437
28465
  // After a 401 SESSION_EXPIRED: forget the token so the next call asks the provider again. True when a retry may help.
28438
28466
  renew: function () { token = null; exp = 0; return true; },
28467
+ // The fast-path address the latest token answer gave (read after headers()), or null.
28468
+ fastPath: function () { return Promise.resolve(fast); },
28439
28469
  };
28440
28470
  }
28441
28471
  if (c && typeof c.key === 'string' && c.key) {
@@ -28443,6 +28473,7 @@ function smapCreatePlan() {
28443
28473
  kind: 'key',
28444
28474
  headers: function () { return Promise.resolve({ Authorization: 'Bearer ' + c.key }); },
28445
28475
  renew: function () { return false; },
28476
+ fastPath: null, // set by the transport: the key's configuration on sMap
28446
28477
  };
28447
28478
  }
28448
28479
  throw new Error('sMap plan editor: credentials are { token: () => Promise<string | TokenAnswer> } or { key: string }');
@@ -28465,44 +28496,155 @@ function smapCreatePlan() {
28465
28496
  function cancelled() { var e = new Error('cancelled'); e.name = 'AbortError'; e.cancelled = true; return e; }
28466
28497
 
28467
28498
  /**
28468
- * The transport: send(method, path, body, signal) resolves { status, body, data, matrix } (matrix: the X-Plan-Matrix
28469
- * header) or rejects with a PlanError. A 401 SESSION_EXPIRED with a token provider asks for a new token and repeats
28470
- * the call once; every other refusal (SESSION_REVOKED, TOKEN_INVALID, 403 NOT_AUTHORIZED with its reason) is raised.
28499
+ * The transport: send(method, path, body, signal) resolves { status, body, data, matrix, path } (matrix: the
28500
+ * X-Plan-Matrix header; path: 'fast' or 'standard', where the answer came from) or rejects with a PlanError. A 401
28501
+ * SESSION_EXPIRED with a token provider asks for a new token and repeats the call once; every other refusal
28502
+ * (SESSION_REVOKED, TOKEN_INVALID, 403 NOT_AUTHORIZED with its reason) is raised.
28503
+ *
28504
+ * Fast path (OPEN-ROUTE-EDIT E19, §2f.5): when the credential names a fast-path address (the token answer's
28505
+ * `fast_path.url`, or a map key's configuration from GET <smapUrl>/plan/v1/config), each call goes to
28506
+ * <url>/<same path> with the same method, credential, headers and body. A 409 USE_STANDARD_PATH (or the header
28507
+ * X-Plan-Path: standard), any 5xx, a network error or no answer within 2 s (refine: 5 s) repeats the same call once on the standard
28508
+ * path (<baseUrl>/v1/plan/<same path>); the next call tries the fast path again. 402, 429 and every other 4xx are final.
28471
28509
  */
28472
28510
  function createTransport(o) {
28473
28511
  o = o || {};
28474
28512
  var base = String(o.baseUrl || DEFAULT_BASE).replace(/\/$/, '');
28513
+ var smap = String(o.smapUrl || DEFAULT_SMAP).replace(/\/$/, '');
28514
+ var fastOn = o.fastPath !== false;
28515
+ var timeoutMs = fastPathTimeoutFor('', o);
28475
28516
  var creds = credentialsOf(o.credentials);
28476
28517
  var app = appHeaders(o.app);
28477
28518
  var fetchFn = o.fetch || (typeof fetch === 'function' ? function (url, init) { return fetch(url, init); } : null);
28478
28519
  if (!fetchFn) { throw new Error('sMap plan editor: no fetch; pass options.fetch'); }
28479
28520
 
28521
+ function headersWith(h, json) {
28522
+ var headers = { Accept: 'application/json' };
28523
+ Object.keys(app).forEach(function (k) { headers[k] = app[k]; });
28524
+ Object.keys(h).forEach(function (k) { headers[k] = h[k]; });
28525
+ if (json) { headers['Content-Type'] = 'application/json'; }
28526
+ return headers;
28527
+ }
28528
+
28529
+ // One request, read to the end. With `limit` it gives up after that many ms ({ timedOut: true }); a network error
28530
+ // resolves { failed: error } unless the caller's own signal ended it (then it rejects, cancelled).
28531
+ function exchange(url, init, signal, limit) {
28532
+ if (!limit) {
28533
+ return fetchFn(url, init).then(read);
28534
+ }
28535
+ var inner = newController();
28536
+ var timedOut = false;
28537
+ var timer = null;
28538
+ var onAbort = function () { if (inner) { inner.abort(); } };
28539
+ if (signal) {
28540
+ if (signal.aborted) { return Promise.reject(cancelled()); }
28541
+ if (signal.addEventListener) { signal.addEventListener('abort', onAbort); }
28542
+ }
28543
+ var own = {};
28544
+ Object.keys(init).forEach(function (k) { own[k] = init[k]; });
28545
+ if (inner) { own.signal = inner.signal; }
28546
+ var done = function () {
28547
+ if (timer) { clearTimeout(timer); }
28548
+ if (signal && signal.removeEventListener) { signal.removeEventListener('abort', onAbort); }
28549
+ };
28550
+ var timeout = new Promise(function (resolve) {
28551
+ timer = setTimeout(function () { timedOut = true; if (inner) { inner.abort(); } resolve({ timedOut: true }); }, limit);
28552
+ });
28553
+ var answer = Promise.resolve().then(function () { return fetchFn(url, own); }).then(read).then(function (r) { return r; }, function (e) {
28554
+ if (signal && signal.aborted) { throw cancelled(); }
28555
+ if (timedOut) { return { timedOut: true }; }
28556
+ return { failed: e };
28557
+ });
28558
+ return Promise.race([answer, timeout]).then(function (r) {
28559
+ done();
28560
+ if (signal && signal.aborted) { throw cancelled(); }
28561
+ return r;
28562
+ }, function (e) { done(); throw e; });
28563
+ }
28564
+
28565
+ function read(res) {
28566
+ return res.text().then(function (text) {
28567
+ var json = null;
28568
+ try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; }
28569
+ var get = function (k) { return res.headers && typeof res.headers.get === 'function' ? res.headers.get(k) : null; };
28570
+ return { status: res.status, ok: res.ok, json: json, matrix: get('X-Plan-Matrix'), planPath: get('X-Plan-Path') };
28571
+ });
28572
+ }
28573
+
28574
+ // A map key's configuration on sMap: GET <smap>/plan/v1/config -> {"fast_path": {"url"}} or {}.
28575
+ var keyConfig = { url: null, until: 0, pending: null };
28576
+ function keyFastPath(h) {
28577
+ if (Date.now() < keyConfig.until) { return Promise.resolve(keyConfig.url); }
28578
+ if (keyConfig.pending) { return keyConfig.pending; }
28579
+ keyConfig.pending = exchange(smap + '/plan/v1/config', { method: 'GET', headers: headersWith(h, false) }, null, timeoutMs).then(function (r) {
28580
+ if (r.status >= 200 && r.status < 300) {
28581
+ keyConfig.url = fastPathOf(r.json);
28582
+ keyConfig.until = Date.now() + KEY_CONFIG_TTL_MS;
28583
+ } else {
28584
+ // A refusal is an answer (no fast path for this key); a failure is asked again after a minute.
28585
+ keyConfig.url = null;
28586
+ keyConfig.until = Date.now() + (r.status >= 400 && r.status < 500 ? KEY_CONFIG_TTL_MS : KEY_CONFIG_RETRY_MS);
28587
+ }
28588
+ return keyConfig.url;
28589
+ }, function () {
28590
+ keyConfig.url = null;
28591
+ keyConfig.until = Date.now() + KEY_CONFIG_RETRY_MS;
28592
+ return null;
28593
+ }).then(function (url) { keyConfig.pending = null; return url; });
28594
+ return keyConfig.pending;
28595
+ }
28596
+
28597
+ function fastPathFor(h) {
28598
+ if (!fastOn) { return Promise.resolve(null); }
28599
+ return creds.fastPath ? creds.fastPath() : keyFastPath(h);
28600
+ }
28601
+
28602
+ // Repeat on the standard path (§2f.5)?
28603
+ function useStandard(r) {
28604
+ if (r.timedOut || r.failed) { return true; }
28605
+ if (r.status >= 500) { return true; }
28606
+ if (r.status !== 409) { return false; }
28607
+ return !!(r.json && r.json.error && r.json.error.code === 'USE_STANDARD_PATH') || String(r.planPath || '').toLowerCase() === 'standard';
28608
+ }
28609
+
28480
28610
  function send(method, path, body, signal, retried) {
28481
- return creds.headers().then(function (h) {
28482
- var headers = { Accept: 'application/json' };
28483
- Object.keys(app).forEach(function (k) { headers[k] = app[k]; });
28484
- Object.keys(h).forEach(function (k) { headers[k] = h[k]; });
28485
- var init = { method: method, headers: headers };
28486
- if (body !== undefined) { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(body); }
28487
- if (signal) { init.signal = signal; }
28488
- return fetchFn(base + path, init);
28489
- }).then(function (res) {
28490
- return res.text().then(function (text) {
28491
- var json = null;
28492
- try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; }
28493
- var matrix = res.headers && typeof res.headers.get === 'function' ? res.headers.get('X-Plan-Matrix') : null;
28494
- if (!res.ok) {
28495
- var err = (json && json.error) || {};
28496
- if (res.status === 401 && err.code === 'SESSION_EXPIRED' && !retried && creds.renew()) { return send(method, path, body, signal, true); }
28497
- throw PlanError(err.message || ('HTTP ' + res.status), {
28498
- status: res.status, code: err.code || null, details: err.details || null, reason: err.reason || (json && json.reason) || null, path: path,
28499
- });
28500
- }
28501
- return { status: res.status, body: json, data: json && json.data, matrix: matrix };
28611
+ var h = null;
28612
+ return creds.headers().then(function (got) {
28613
+ h = got;
28614
+ return fastPathFor(h);
28615
+ }).then(function (fast) {
28616
+ if (signal && signal.aborted) { throw cancelled(); }
28617
+ var init = { method: method, headers: headersWith(h, body !== undefined) };
28618
+ if (body !== undefined) { init.body = JSON.stringify(body); }
28619
+ var standard = function () {
28620
+ var s = {};
28621
+ Object.keys(init).forEach(function (k) { s[k] = init[k]; });
28622
+ s.headers = headersWith(h, body !== undefined);
28623
+ if (signal) { s.signal = signal; }
28624
+ return exchange(base + path, s, signal, 0).then(function (r) { r.via = 'standard'; return r; });
28625
+ };
28626
+ if (!fast || path.indexOf(PLAN_PREFIX + '/') !== 0) { return standard(); }
28627
+ var rest = path.slice(PLAN_PREFIX.length);
28628
+ return exchange(fast + rest, init, signal, fastPathTimeoutFor(rest, o)).then(function (r) {
28629
+ if (useStandard(r)) { return standard(); }
28630
+ r.via = 'fast';
28631
+ return r;
28502
28632
  });
28633
+ }).then(function (r) {
28634
+ if (!r.ok) {
28635
+ var json = r.json;
28636
+ var err = (json && json.error) || {};
28637
+ if (r.status === 401 && err.code === 'SESSION_EXPIRED' && !retried && creds.renew()) { return send(method, path, body, signal, true); }
28638
+ var e = PlanError(err.message || ('HTTP ' + r.status), {
28639
+ status: r.status, code: err.code || null, details: err.details || null, reason: err.reason || (json && json.reason) || null, path: path,
28640
+ });
28641
+ e.via = r.via;
28642
+ throw e;
28643
+ }
28644
+ return { status: r.status, body: r.json, data: r.json && r.json.data, matrix: r.matrix, path: r.via };
28503
28645
  });
28504
28646
  }
28505
- return { send: send, kind: creds.kind, baseUrl: base };
28647
+ return { send: send, kind: creds.kind, baseUrl: base, smapUrl: smap };
28506
28648
  }
28507
28649
 
28508
28650
  // ------------------------------------------------------------------ plans
@@ -28655,7 +28797,12 @@ function smapCreatePlan() {
28655
28797
  * @param {Object} options
28656
28798
  * @param {Object} options.credentials { token: () => Promise<string | TokenAnswer> } or { key: string }
28657
28799
  * @param {string|Object} [options.app] a native app's identity: 'android:<package>' / 'apple:<bundle id>' / 'windows:<id>', or { id, cert }
28658
- * @param {string} [options.baseUrl] the Open Platform (default https://open.superroute.ca)
28800
+ * @param {string} [options.baseUrl] the Open Platform (default https://open.superroute.ca): the standard path
28801
+ * @param {string} [options.smapUrl] the sMap service a map key's configuration is read from (default
28802
+ * https://tile.srsr.ca; map.planEditor passes the map's own sMap address)
28803
+ * @param {boolean} [options.fastPath=true] use the fast path when the credential names one (false: standard only)
28804
+ * @param {number} [options.fastPathTimeout=2000] ms a fast-path call may take before it is repeated on the standard path
28805
+ * @param {number} [options.fastPathRefineTimeout=5000] the same for refine (its search takes longer)
28659
28806
  * @param {Function} [options.fetch] fetch to use (default the page's)
28660
28807
  * @param {Object} [options.plan] the starting plan: { vehicles, jobs, routes, region?, profile?, departed_at? }
28661
28808
  * @param {string} [options.region] used when the plan names none
@@ -28691,6 +28838,7 @@ function smapCreatePlan() {
28691
28838
  this._opening = null;
28692
28839
  this._openingKey = null;
28693
28840
  this._matrixRetryAt = 0;
28841
+ this._path = null;
28694
28842
  this._destroyed = false;
28695
28843
  if (options.plan) { this.setPlan(options.plan).catch(function () {}); }
28696
28844
  }
@@ -28759,7 +28907,7 @@ function smapCreatePlan() {
28759
28907
  return {
28760
28908
  plan: this.getPlan(), result: this.getResult(), busy: this._busy, error: this._error, canUndo: this.canUndo(),
28761
28909
  canRedo: this.canRedo(), choices: clone(this._choices), locked: this.locked(), last: clone(this._last),
28762
- preview: this._previewResult ? clone(this._previewResult) : null,
28910
+ preview: this._previewResult ? clone(this._previewResult) : null, path: this._path,
28763
28911
  };
28764
28912
  };
28765
28913
 
@@ -28969,7 +29117,7 @@ function smapCreatePlan() {
28969
29117
  var e = this._history[this._at] || {};
28970
29118
  this._emit('change', {
28971
29119
  kind: kind, plan: this.getPlan(), result: this.getResult(), answer: this._last ? clone(this._last.answer) : null,
28972
- pending: !e.result, canUndo: this.canUndo(), canRedo: this.canRedo(),
29120
+ pending: !e.result, canUndo: this.canUndo(), canRedo: this.canRedo(), path: this._path,
28973
29121
  });
28974
29122
  };
28975
29123
 
@@ -29069,7 +29217,7 @@ function smapCreatePlan() {
29069
29217
  self._error = null;
29070
29218
  self._setBusy(false);
29071
29219
  if (self._history[self._at] === target || kind !== 'recost') { self._changed(kind); }
29072
- return { kind: kind, plan: self.getPlan(), result: self.getResult(), answer: clone(answer) };
29220
+ return { kind: kind, plan: self.getPlan(), result: self.getResult(), answer: clone(answer), path: self._path };
29073
29221
  }, function (err) {
29074
29222
  var current = self._inflight === ticket;
29075
29223
  if (current) { self._inflight = null; self._setBusy(false); }
@@ -29100,6 +29248,7 @@ function smapCreatePlan() {
29100
29248
  if (matrix) { body.matrix = matrix; } else { delete body.matrix; }
29101
29249
  return self._transport.send('POST', path, body, signal);
29102
29250
  }).then(function (res) {
29251
+ if (!self._destroyed) { self._path = res.path || null; }
29103
29252
  if (body.matrix) { self._snapshotSeen(res.matrix, body.matrix); }
29104
29253
  return res;
29105
29254
  }, function (err) {
@@ -29151,7 +29300,7 @@ function smapCreatePlan() {
29151
29300
  }
29152
29301
  self._matrixRetryAt = 0;
29153
29302
  if (self._openingKey === key) { self._matrix = id; self._matrixKey = key; }
29154
- self._emit('snapshot', { status: 'opened', matrix: id, expires_at: res.data.expires_at || null, node: res.data.node || null });
29303
+ self._emit('snapshot', { status: 'opened', matrix: id, expires_at: res.data.expires_at || null, node: res.data.node || null, path: res.path || null });
29155
29304
  return id;
29156
29305
  }, function (err) {
29157
29306
  self._matrixRetryAt = Date.now() + SNAPSHOT_RETRY_MS;
@@ -29887,7 +30036,7 @@ function smapCreatePlan() {
29887
30036
  */
29888
30037
  function attach(map, options) {
29889
30038
  options = options || {};
29890
- var editor = new PlanEditor(Object.assign({}, options, { plan: null }));
30039
+ var editor = new PlanEditor(Object.assign({}, options, { plan: null, smapUrl: options.smapUrl || map._base }));
29891
30040
  var layer = attachToMap(map, editor, options);
29892
30041
  var toolId = null;
29893
30042
  var destroyed = false;
@@ -29973,7 +30122,7 @@ function smapCreateSdk(engine, interop, plan) {
29973
30122
  })(typeof self !== 'undefined' ? self : this, function (engine, interop, plan) {
29974
30123
  'use strict';
29975
30124
 
29976
- var VERSION = '1.1.6';
30125
+ var VERSION = '1.1.7';
29977
30126
  var FLAVORS = ['light', 'white', 'grayscale', 'dark', 'black'];
29978
30127
  var BASEMAP_SOURCE = 'basemap';
29979
30128
  var BUILDINGS_LAYER = 'smap-buildings-3d';