@mono-lit/utility 0.0.1 → 0.0.3

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 (36) hide show
  1. package/LICENSE.md +54 -54
  2. package/README.md +156 -156
  3. package/dist/{app-roots-BJsIxzjk.d.ts → app-roots-DK41xMWj.d.ts} +1 -2
  4. package/dist/config-node.d.ts +134 -188
  5. package/dist/config-node.js +1 -1
  6. package/dist/config.d.ts +1 -1
  7. package/dist/{create-config-D3m6xTaQ.d.ts → create-config-B8IhX4ht.d.ts} +5 -3
  8. package/dist/fetching.d.ts +51 -46
  9. package/dist/fetching.js +163 -15
  10. package/dist/{index-C2hZeNkq.d.ts → index-BAy6tbOG.d.ts} +12 -6
  11. package/dist/{index-ClrZbU7n.d.ts → index-DYlzhHq7.d.ts} +83 -87
  12. package/dist/index.d.ts +3 -7
  13. package/dist/index.js +5 -3
  14. package/dist/{merge-file-C5nzi_MY.d.ts → merge-file-CLc3wxY4.d.ts} +5 -28
  15. package/dist/{mock-db-5mJTObSC.js → mock-db-4tTWrF-P.js} +12 -12
  16. package/dist/mock-db.d.ts +1 -1
  17. package/dist/mock-db.js +1 -1
  18. package/dist/mono-db.d.ts +1 -1
  19. package/dist/mono-db.js +115 -108
  20. package/dist/mono-prepare.d.ts +1 -1
  21. package/dist/mono-prepare.js +3 -2
  22. package/dist/mono-skills.d.ts +1 -1
  23. package/dist/mono-skills.js +39 -32
  24. package/dist/nuxt-layers.d.ts +4 -2
  25. package/dist/nuxt-runtime.d.ts +4 -5
  26. package/dist/nuxt-runtime.js +1 -1
  27. package/dist/nuxt.d.ts +42 -38
  28. package/dist/nuxt.js +153 -6
  29. package/dist/{runtime-C_IWNrAG.js → runtime-vs7U9Ed4.js} +394 -157
  30. package/dist/runtime.d.ts +68 -133
  31. package/dist/runtime.js +2 -2
  32. package/dist/{session-Bk985AIM.js → session-Bcig-rPi.js} +4 -4
  33. package/dist/{universal-B2eD9xho.d.ts → universal-BR0O7Qwk.d.ts} +8 -46
  34. package/dist/{universal-BNTo_83u.js → universal-DIVEzCvN.js} +3 -2
  35. package/dist/vite.d.ts +44 -41
  36. package/package.json +11 -15
@@ -1,5 +1,5 @@
1
1
  import { a as resolveEnv, c as resolveMonoConfig } from "./create-config-DdL3Fh6T.js";
2
- import { c as useMyToken, n as monoJwt, s as useMyCookie, t as monoCookie, u as useMyJwt } from "./universal-BNTo_83u.js";
2
+ import { c as useMyToken, d as useMyJwt, n as monoJwt, s as useMyCookie, t as monoCookie } from "./universal-DIVEzCvN.js";
3
3
  import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, defineComponent, isRef, markRaw, normalizeStyle, onBeforeUnmount, openBlock, reactive, readonly, ref, renderList, toDisplayString, watch, withCtx } from "vue";
4
4
  import { Notifications, Notivue, pastelTheme, push } from "notivue";
5
5
  import { Deferred } from "devextreme/core/utils/deferred";
@@ -12,7 +12,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
12
  var __getOwnPropNames = Object.getOwnPropertyNames;
13
13
  var __getProtoOf = Object.getPrototypeOf;
14
14
  var __hasOwnProp = Object.prototype.hasOwnProperty;
15
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
15
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
16
16
  var __copyProps = (to, from, except, desc) => {
17
17
  if (from && typeof from === "object" || typeof from === "function") {
18
18
  for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
@@ -27,7 +27,7 @@ var __copyProps = (to, from, except, desc) => {
27
27
  }
28
28
  return to;
29
29
  };
30
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
31
31
  value: mod,
32
32
  enumerable: true
33
33
  }) : target, mod));
@@ -565,7 +565,9 @@ async function createStaticDatasource(opts) {
565
565
  ] : a || b;
566
566
  function runOdataOnArray(rows, loadOptions) {
567
567
  const ci = opts.caseInsensitive ?? true;
568
- const filterDx = andFilters(typeof currentParams.$filter === "string" ? parseOdataFilterToDx(currentParams.$filter) : Array.isArray(currentParams.$filter) ? currentParams.$filter : null, Array.isArray(loadOptions?.filter) ? loadOptions.filter : null);
568
+ const base = typeof currentParams.$filter === "string" ? parseOdataFilterToDx(currentParams.$filter) : Array.isArray(currentParams.$filter) ? currentParams.$filter : null;
569
+ const extra = Array.isArray(loadOptions?.filter) ? loadOptions.filter : null;
570
+ const filterDx = andFilters(base, extra);
569
571
  let items = rows.slice();
570
572
  if (filterDx) items = items.filter((r) => evalDxFilter(r, filterDx, ci));
571
573
  const needles = [currentParams.$search, loadOptions?.searchValue].filter(Boolean).map(String);
@@ -611,7 +613,8 @@ async function createStaticDatasource(opts) {
611
613
  },
612
614
  byKey: (k) => {
613
615
  const toKeyStr = (v) => v == null ? "" : String(v);
614
- return dxResolve(local.find((x) => toKeyStr(x[key]) === toKeyStr(k)) ?? null);
616
+ const r = local.find((x) => toKeyStr(x[key]) === toKeyStr(k)) ?? null;
617
+ return dxResolve(r);
615
618
  },
616
619
  insert: (values) => {
617
620
  const row = ensureKey({ ...values });
@@ -681,8 +684,15 @@ var require_property_expr = /* @__PURE__ */ __commonJSMin(((exports, module) =>
681
684
  if (!(key in this._values)) this._size++;
682
685
  return this._values[key] = value;
683
686
  };
684
- var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g, DIGIT_REGEX = /^\d+$/, LEAD_DIGIT_REGEX = /^\d/, SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g, CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/, MAX_CACHE_SIZE = 512;
685
- var pathCache = new Cache(MAX_CACHE_SIZE), setCache = new Cache(MAX_CACHE_SIZE), getCache = new Cache(MAX_CACHE_SIZE);
687
+ var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g;
688
+ var DIGIT_REGEX = /^\d+$/;
689
+ var LEAD_DIGIT_REGEX = /^\d/;
690
+ var SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g;
691
+ var CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/;
692
+ var MAX_CACHE_SIZE = 512;
693
+ var pathCache = new Cache(MAX_CACHE_SIZE);
694
+ var setCache = new Cache(MAX_CACHE_SIZE);
695
+ var getCache = new Cache(MAX_CACHE_SIZE);
686
696
  module.exports = {
687
697
  Cache,
688
698
  split,
@@ -728,8 +738,8 @@ var require_property_expr = /* @__PURE__ */ __commonJSMin(((exports, module) =>
728
738
  return path.match(SPLIT_REGEX) || [""];
729
739
  }
730
740
  function forEach(parts, iter, thisArg) {
731
- var len = parts.length, part, idx, isArray, isBracket;
732
- for (idx = 0; idx < len; idx++) {
741
+ var len = parts.length, part, idx = 0, isArray, isBracket;
742
+ for (; idx < len; idx++) {
733
743
  part = parts[idx];
734
744
  if (part) {
735
745
  if (shouldBeQuoted(part)) part = "\"" + part + "\"";
@@ -889,7 +899,9 @@ function printValue(value, quoteStrings) {
889
899
  function toArray(value) {
890
900
  return value == null ? [] : [].concat(value);
891
901
  }
892
- let _Symbol$toStringTag, _Symbol$hasInstance, _Symbol$toStringTag2;
902
+ let _Symbol$toStringTag;
903
+ let _Symbol$hasInstance;
904
+ let _Symbol$toStringTag2;
893
905
  let strReg = /\$\{\s*(\w+)\s*\}/g;
894
906
  _Symbol$toStringTag = Symbol.toStringTag;
895
907
  var ValidationErrorNoStack = class {
@@ -1662,9 +1674,10 @@ var Schema = class {
1662
1674
  */
1663
1675
  test(...args) {
1664
1676
  let opts;
1665
- if (args.length === 1) if (typeof args[0] === "function") opts = { test: args[0] };
1666
- else opts = args[0];
1667
- else if (args.length === 2) opts = {
1677
+ if (args.length === 1) {
1678
+ if (typeof args[0] === "function") opts = { test: args[0] };
1679
+ else opts = args[0];
1680
+ } else if (args.length === 2) opts = {
1668
1681
  name: args[0],
1669
1682
  test: args[1]
1670
1683
  };
@@ -2026,8 +2039,10 @@ var StringSchema = class extends Schema {
2026
2039
  let excludeEmptyString = false;
2027
2040
  let message;
2028
2041
  let name;
2029
- if (options) if (typeof options === "object") ({excludeEmptyString = false, message, name} = options);
2030
- else message = options;
2042
+ if (options) {
2043
+ if (typeof options === "object") ({excludeEmptyString = false, message, name} = options);
2044
+ else message = options;
2045
+ }
2031
2046
  return this.test({
2032
2047
  name: name || "matches",
2033
2048
  message: message || string.matches,
@@ -2061,8 +2076,10 @@ var StringSchema = class extends Schema {
2061
2076
  let message = "";
2062
2077
  let allowOffset;
2063
2078
  let precision;
2064
- if (options) if (typeof options === "object") ({message = "", allowOffset = false, precision = void 0} = options);
2065
- else message = options;
2079
+ if (options) {
2080
+ if (typeof options === "object") ({message = "", allowOffset = false, precision = void 0} = options);
2081
+ else message = options;
2082
+ }
2066
2083
  return this.matches(rIsoDateTime, {
2067
2084
  name: "datetime",
2068
2085
  message: message || string.datetime,
@@ -3253,16 +3270,18 @@ var require_tslib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3253
3270
  var __createBinding;
3254
3271
  (function(factory) {
3255
3272
  var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
3256
- if (typeof define === "function" && define.amd) define("tslib", ["exports"], function(exports$1) {
3257
- factory(createExporter(root, createExporter(exports$1)));
3273
+ if (typeof define === "function" && define.amd) define("tslib", ["exports"], function(exports) {
3274
+ factory(createExporter(root, createExporter(exports)));
3258
3275
  });
3259
3276
  else if (typeof module === "object" && typeof module.exports === "object") factory(createExporter(root, createExporter(module.exports)));
3260
3277
  else factory(createExporter(root));
3261
- function createExporter(exports$2, previous) {
3262
- if (exports$2 !== root) if (typeof Object.create === "function") Object.defineProperty(exports$2, "__esModule", { value: true });
3263
- else exports$2.__esModule = true;
3278
+ function createExporter(exports, previous) {
3279
+ if (exports !== root) {
3280
+ if (typeof Object.create === "function") Object.defineProperty(exports, "__esModule", { value: true });
3281
+ else exports.__esModule = true;
3282
+ }
3264
3283
  return function(id, v) {
3265
- return exports$2[id] = previous ? previous(id, v) : v;
3284
+ return exports[id] = previous ? previous(id, v) : v;
3266
3285
  };
3267
3286
  }
3268
3287
  })(function(exporter) {
@@ -3344,12 +3363,12 @@ var require_tslib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3344
3363
  },
3345
3364
  trys: [],
3346
3365
  ops: []
3347
- }, f, y, t, g;
3348
- return g = {
3366
+ }, f, y, t, g = {
3349
3367
  next: verb(0),
3350
3368
  "throw": verb(1),
3351
3369
  "return": verb(2)
3352
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
3370
+ };
3371
+ return typeof Symbol === "function" && (g[Symbol.iterator] = function() {
3353
3372
  return this;
3354
3373
  }), g;
3355
3374
  function verb(n) {
@@ -3525,8 +3544,8 @@ var require_tslib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3525
3544
  }
3526
3545
  };
3527
3546
  __asyncDelegator = function(o) {
3528
- var i, p;
3529
- return i = {}, verb("next"), verb("throw", function(e) {
3547
+ var i = {}, p;
3548
+ return verb("next"), verb("throw", function(e) {
3530
3549
  throw e;
3531
3550
  }), verb("return"), i[Symbol.iterator] = function() {
3532
3551
  return this;
@@ -3946,8 +3965,151 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports) => {
3946
3965
  }));
3947
3966
 
3948
3967
  //#endregion
3949
- //#region src/core/composables/use-fetch-helper.ts
3968
+ //#region src/core/composables/prefetch-bridge.ts
3950
3969
  var import_lib = require_lib();
3970
+ /** Store classes that implement the `prefetch` option themselves (`@mono-lit/data`). */
3971
+ const PREFETCH_SUPPORT = Symbol.for("mono.prefetch");
3972
+ let bridge = null;
3973
+ function setPrefetchBridge(next) {
3974
+ bridge = next;
3975
+ }
3976
+ function getPrefetchBridge() {
3977
+ return bridge;
3978
+ }
3979
+ const CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
3980
+ "authorization",
3981
+ "cookie",
3982
+ "set-cookie",
3983
+ "proxy-authorization",
3984
+ "x-api-key"
3985
+ ]);
3986
+ function safeHeaders(headers) {
3987
+ if (!headers || typeof headers !== "object") return void 0;
3988
+ const out = {};
3989
+ for (const [name, value] of Object.entries(headers)) {
3990
+ if (CREDENTIAL_HEADERS.has(name.toLowerCase()) || typeof value !== "string") continue;
3991
+ out[name] = value;
3992
+ }
3993
+ return Object.keys(out).length ? out : void 0;
3994
+ }
3995
+ /** Reports a request (credential headers stripped). A no-op without a bridge. */
3996
+ function learnPrefetch(request) {
3997
+ if (!bridge || !request?.url) return;
3998
+ try {
3999
+ const headers = safeHeaders(request.headers);
4000
+ bridge.learn({
4001
+ url: request.url,
4002
+ ...request.query && Object.keys(request.query).length ? { query: { ...request.query } } : {},
4003
+ ...headers ? { headers } : {},
4004
+ ...request.auth ? { auth: request.auth } : {}
4005
+ });
4006
+ } catch {}
4007
+ }
4008
+ /**
4009
+ * A per-store `@mono-lit/data` prefetch provider that captures the store's first load exactly as
4010
+ * it would be sent, and answers it with an empty result (nothing is fetched here).
4011
+ */
4012
+ function captureProvider(emit) {
4013
+ return {
4014
+ learn: (request) => emit(request),
4015
+ expects: () => true,
4016
+ take: async () => ({ data: {
4017
+ "value": [],
4018
+ "@odata.count": 0
4019
+ } })
4020
+ };
4021
+ }
4022
+ /**
4023
+ * Serving plain DevExtreme stores (`@mono-lit/devextreme`), which can't serve by themselves.
4024
+ *
4025
+ * DevExtreme's OData stores call the store's `beforeSend(request)` and then, synchronously in the
4026
+ * same call, open and send ONE XMLHttpRequest for it. So utility's own `beforeSend` arms the
4027
+ * request the bridge expects ({@link armPrefetchServe}), and the very next `send()` of a GET to that
4028
+ * URL is answered from the prefetched result instead of the network — DevExtreme then parses it
4029
+ * exactly like a response (dates, `@odata.count`, `map`). This needs no access to DevExtreme's own
4030
+ * modules (in Vite dev the data layer is pre-bundled with its OWN copy of DevExtreme's internals,
4031
+ * out of reach of an `ajax.inject` from here). Every other XHR is untouched; a missing result (e.g.
4032
+ * it failed on the server) is sent normally — the request was opened but not yet sent.
4033
+ */
4034
+ let armed = null;
4035
+ const opened = /* @__PURE__ */ new WeakMap();
4036
+ let xhrPatched = false;
4037
+ function patchXhr() {
4038
+ if (xhrPatched) return true;
4039
+ const proto = globalThis.XMLHttpRequest?.prototype;
4040
+ if (!proto || typeof proto.open !== "function" || typeof proto.send !== "function") return false;
4041
+ xhrPatched = true;
4042
+ const { open, send, abort } = proto;
4043
+ proto.open = function(method, url, ...rest) {
4044
+ opened.set(this, {
4045
+ method: String(method).toUpperCase(),
4046
+ url: String(url)
4047
+ });
4048
+ return open.call(this, method, url, ...rest);
4049
+ };
4050
+ proto.send = function(body) {
4051
+ const request = opened.get(this);
4052
+ const hit = armed;
4053
+ armed = null;
4054
+ if (!hit || request?.method !== "GET" || !request.url.startsWith(hit.url)) return send.call(this, body);
4055
+ const xhr = this;
4056
+ let aborted = false;
4057
+ xhr.abort = function() {
4058
+ aborted = true;
4059
+ return abort.call(xhr);
4060
+ };
4061
+ const passThrough = () => {
4062
+ if (!aborted) send.call(xhr, body);
4063
+ };
4064
+ hit.bridge.take("GET", hit.url, hit.query).then((result) => {
4065
+ if (aborted) return;
4066
+ if (!result) return passThrough();
4067
+ const text = JSON.stringify(result.data);
4068
+ for (const [name, value] of Object.entries({
4069
+ readyState: 4,
4070
+ status: 200,
4071
+ statusText: "OK",
4072
+ responseText: text,
4073
+ response: text,
4074
+ responseURL: request.url
4075
+ })) Object.defineProperty(xhr, name, {
4076
+ configurable: true,
4077
+ value
4078
+ });
4079
+ xhr.onreadystatechange?.(new Event("readystatechange"));
4080
+ xhr.onload?.(new Event("load"));
4081
+ xhr.onloadend?.(new Event("loadend"));
4082
+ }, passThrough);
4083
+ };
4084
+ return true;
4085
+ }
4086
+ /**
4087
+ * Called from a plain DevExtreme store's `beforeSend` with the final request: when the bridge has a
4088
+ * result for this GET, the XHR DevExtreme sends right after is answered from it. Returns whether
4089
+ * it was armed.
4090
+ */
4091
+ function armPrefetchServe(url, query) {
4092
+ armed = null;
4093
+ const current = bridge;
4094
+ if (!current || typeof url !== "string" || !url) return false;
4095
+ try {
4096
+ if (!current.expects("GET", url, query) || !patchXhr()) return false;
4097
+ } catch {
4098
+ return false;
4099
+ }
4100
+ armed = {
4101
+ url,
4102
+ query,
4103
+ bridge: current
4104
+ };
4105
+ queueMicrotask(() => {
4106
+ if (armed?.url === url) armed = null;
4107
+ });
4108
+ return true;
4109
+ }
4110
+
4111
+ //#endregion
4112
+ //#region src/core/composables/use-fetch-helper.ts
3951
4113
  /**
3952
4114
  * Deterministic serialization of a value, for request-dedupe keys.
3953
4115
  *
@@ -4168,6 +4330,24 @@ function tokenFollowsCookie(token, config, tokenOptions) {
4168
4330
  return token === getCookieToken(api.name, api.split) || token === getCookieToken(config?.jwtName, true);
4169
4331
  }
4170
4332
  /**
4333
+ * For the `prefetch` option: the cookie a request's Bearer came from, so the prefetch host can
4334
+ * read the same cookie off the page request itself — the token is never reported. A token that
4335
+ * matches no cookie (the caller's own) gets no hint: the host's replay then goes without auth
4336
+ * and the browser fetches as usual if that fails.
4337
+ */
4338
+ function prefetchAuthFor(token, config, tokenOptions) {
4339
+ if (!token) return void 0;
4340
+ const api = apiCookieRef(config, tokenOptions);
4341
+ if (api.name && token === getCookieToken(api.name, api.split)) return api.split ? {
4342
+ cookie: api.name,
4343
+ split: true
4344
+ } : { cookie: api.name };
4345
+ if (config?.jwtName && token === getCookieToken(config.jwtName, true)) return {
4346
+ cookie: config.jwtName,
4347
+ split: true
4348
+ };
4349
+ }
4350
+ /**
4171
4351
  * The Bearer for a request.
4172
4352
  *
4173
4353
  * `followCookie` is the fix for a store that outlives its token: a DataSource is built once
@@ -4586,9 +4766,9 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
4586
4766
  keyValue: null,
4587
4767
  keyName: "",
4588
4768
  keyType: ""
4589
- }, config, tokenOptions, tanstack }) => {
4590
- const helper = window.helper || useHelper();
4591
- const isNotif = typeof notif === "boolean" && notif === true ? helper.notif : notif;
4769
+ }, config, tokenOptions, tanstack, prefetch, __capture }) => {
4770
+ const helper = typeof window !== "undefined" && window.helper || useHelper();
4771
+ const isNotif = __capture ? void 0 : typeof notif === "boolean" && notif === true ? helper.notif : notif;
4592
4772
  const zeroGuardFields = "all";
4593
4773
  const isZeroVal = (v) => v === 0 || v === "0";
4594
4774
  const shouldStripZero = (k, v, allowZero, guard) => !allowZero && !k.startsWith("$") && isZeroVal(v) && (guard === "all" || Array.isArray(guard) && guard.includes(k));
@@ -4609,7 +4789,7 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
4609
4789
  return false;
4610
4790
  }
4611
4791
  try {
4612
- token = await ensureFreshToken({
4792
+ if (!__capture) token = await ensureFreshToken({
4613
4793
  token,
4614
4794
  config,
4615
4795
  tokenOptions
@@ -4646,7 +4826,7 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
4646
4826
  callUnauth(unauthCall);
4647
4827
  return;
4648
4828
  }
4649
- if (expiredBehaviour === "refresh") window.location.reload();
4829
+ if (expiredBehaviour === "refresh" && typeof window !== "undefined") window.location.reload();
4650
4830
  });
4651
4831
  };
4652
4832
  const urls = `${selfProxy ? selfProxy : baseUrl}${url}`;
@@ -4656,6 +4836,25 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
4656
4836
  const tanstackFlag = Symbol.for("mono.tanstack");
4657
4837
  const odsTanstack = tanstack && ods?.[tanstackFlag] ? { tanstack } : {};
4658
4838
  const csTanstack = tanstack && cs?.[tanstackFlag] ? { tanstack } : {};
4839
+ if (__capture && !ods?.[PREFETCH_SUPPORT]) throw new Error("[@mono-lit/utility] .prefetch() needs a data layer that supports it (@mono-lit/data stores)");
4840
+ const odsPrefetch = __capture ? { prefetch: {
4841
+ auth: __capture.auth,
4842
+ provider: captureProvider(__capture.emit)
4843
+ } } : prefetch && ods?.[PREFETCH_SUPPORT] ? { prefetch: { auth: prefetchAuthFor(readToken(), config, tokenOptions) } } : {};
4844
+ let firstLoadReported = false;
4845
+ const learnFirstLoad = (req, latestToken) => {
4846
+ if (__capture || ods?.[PREFETCH_SUPPORT] || !getPrefetchBridge()) return;
4847
+ if (String(req?.method ?? "get").toLowerCase() !== "get") return;
4848
+ if (prefetch !== false) armPrefetchServe(req.url, req.params);
4849
+ if (!prefetch || firstLoadReported || req?.url !== urls) return;
4850
+ firstLoadReported = true;
4851
+ learnPrefetch({
4852
+ url: req.url,
4853
+ query: req.params,
4854
+ headers: req.headers,
4855
+ auth: prefetchAuthFor(latestToken, config, tokenOptions)
4856
+ });
4857
+ };
4659
4858
  const keyName = payload?.keyName || options?.key || "Id";
4660
4859
  const isFake = type === "fakedatasource" || type === "fakedata";
4661
4860
  function isZeroKey(v) {
@@ -4804,126 +5003,129 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
4804
5003
  };
4805
5004
  };
4806
5005
  let store;
4807
- if (isFake) if (method === "GET") store = new ods({
4808
- url: urls,
4809
- version: 4,
4810
- key: keyName,
4811
- ...payload.keyType && { keyType: payload.keyType },
4812
- beforeSend: (req) => {
4813
- try {
4814
- if (force) {
4815
- req.url = urls;
4816
- req.method = method;
4817
- req.params = { ...params || {} };
4818
- } else req.params = {
4819
- ...req.params || {},
4820
- ...params || {}
4821
- };
4822
- const latestToken = readToken();
4823
- req.headers = {
4824
- ...req.headers || {},
4825
- ...headers || {},
4826
- ...latestToken ? { Authorization: `Bearer ${latestToken}` } : {}
5006
+ if (isFake) {
5007
+ if (method === "GET") store = new ods({
5008
+ url: urls,
5009
+ version: 4,
5010
+ key: keyName,
5011
+ ...payload.keyType && { keyType: payload.keyType },
5012
+ beforeSend: (req) => {
5013
+ try {
5014
+ if (force) {
5015
+ req.url = urls;
5016
+ req.method = method;
5017
+ req.params = { ...params || {} };
5018
+ } else req.params = {
5019
+ ...req.params || {},
5020
+ ...params || {}
5021
+ };
5022
+ const latestToken = readToken();
5023
+ req.headers = {
5024
+ ...req.headers || {},
5025
+ ...headers || {},
5026
+ ...latestToken ? { Authorization: `Bearer ${latestToken}` } : {}
5027
+ };
5028
+ stripZeroParams(req.params, allowZero, zeroGuardFields);
5029
+ override?.dataSource?.beforeSend?.(req);
5030
+ learnFirstLoad(req, latestToken);
5031
+ } catch {}
5032
+ },
5033
+ errorHandler: (err) => {
5034
+ const p = parseDxError(err);
5035
+ if (isNotif) isNotif({
5036
+ type: httpVariant(p.status),
5037
+ message: `${p.message}`
5038
+ });
5039
+ if (p.status === 401) onStore401(err);
5040
+ },
5041
+ ...odsTanstack,
5042
+ ...odsPrefetch,
5043
+ ...override?.dataSource
5044
+ });
5045
+ else store = new cs({
5046
+ key: keyName,
5047
+ load: async (loadOptions) => {
5048
+ const sp = new URLSearchParams();
5049
+ const s = loadOptions.sort && loadOptions.sort[0] || null;
5050
+ if (loadOptions.searchValue) sp.set("q", String(loadOptions.searchValue));
5051
+ if (s?.selector) {
5052
+ sp.set("_sort", String(s.selector));
5053
+ sp.set("_order", s.desc ? "desc" : "asc");
5054
+ }
5055
+ if (loadOptions.skip != null) sp.set("_start", String(loadOptions.skip));
5056
+ if (loadOptions.take != null) sp.set("_limit", String(loadOptions.take));
5057
+ const resp = await manageRequest.smartFetch({
5058
+ url: `${urls}${sp.toString() ? `?${sp.toString()}` : ""}`,
5059
+ init: {
5060
+ token: readToken(),
5061
+ headers: {
5062
+ "Content-Type": "application/json",
5063
+ ...headers || {}
5064
+ }
5065
+ },
5066
+ tokenOptions,
5067
+ config
5068
+ });
5069
+ if (!resp.ok) throw new Error(`Load failed: ${resp.status} ${resp.statusText}`);
5070
+ const data = await resp.json();
5071
+ return {
5072
+ data,
5073
+ totalCount: Number(resp.headers.get("X-Total-Count")) || (Array.isArray(data) ? data.length : 0)
4827
5074
  };
4828
- stripZeroParams(req.params, allowZero, zeroGuardFields);
4829
- override?.dataSource?.beforeSend?.(req);
4830
- } catch {}
4831
- },
4832
- errorHandler: (err) => {
4833
- const p = parseDxError(err);
4834
- if (isNotif) isNotif({
4835
- type: httpVariant(p.status),
4836
- message: `${p.message}`
4837
- });
4838
- if (p.status === 401) onStore401(err);
4839
- },
4840
- ...odsTanstack,
4841
- ...override?.dataSource
4842
- });
4843
- else store = new cs({
4844
- key: keyName,
4845
- load: async (loadOptions) => {
4846
- const sp = new URLSearchParams();
4847
- const s = loadOptions.sort && loadOptions.sort[0] || null;
4848
- if (loadOptions.searchValue) sp.set("q", String(loadOptions.searchValue));
4849
- if (s?.selector) {
4850
- sp.set("_sort", String(s.selector));
4851
- sp.set("_order", s.desc ? "desc" : "asc");
4852
- }
4853
- if (loadOptions.skip != null) sp.set("_start", String(loadOptions.skip));
4854
- if (loadOptions.take != null) sp.set("_limit", String(loadOptions.take));
4855
- const resp = await manageRequest.smartFetch({
4856
- url: `${urls}${sp.toString() ? `?${sp.toString()}` : ""}`,
4857
- init: {
4858
- token: readToken(),
4859
- headers: {
4860
- "Content-Type": "application/json",
4861
- ...headers || {}
4862
- }
4863
- },
4864
- tokenOptions,
5075
+ },
5076
+ byKey: (key) => {
5077
+ if (!isFake) {
5078
+ const origByKey = store.byKey?.bind(store);
5079
+ if (typeof origByKey === "function") store.byKey = (key, extra) => {
5080
+ if (!allowZero && isZeroKey(key)) return dxResolve(null);
5081
+ return ensureDx(origByKey(key, extra));
5082
+ };
5083
+ }
5084
+ return dxFromPromise(manageRequest.smartFetch({
5085
+ url: `${urls}/${encodeURIComponent(String(key))}`,
5086
+ init: {
5087
+ token: readToken(),
5088
+ headers: {
5089
+ "Content-Type": "application/json",
5090
+ ...headers || {}
5091
+ }
5092
+ },
5093
+ tokenOptions,
5094
+ config
5095
+ }).then((resp) => {
5096
+ if (!resp.ok) throw new Error(`byKey failed: ${resp.status} ${resp.statusText}`);
5097
+ return resp.json();
5098
+ }));
5099
+ },
5100
+ insert: (values) => fakeWrite({
5101
+ verb: "POST",
5102
+ body: values,
4865
5103
  config
4866
- });
4867
- if (!resp.ok) throw new Error(`Load failed: ${resp.status} ${resp.statusText}`);
4868
- const data = await resp.json();
4869
- return {
4870
- data,
4871
- totalCount: Number(resp.headers.get("X-Total-Count")) || (Array.isArray(data) ? data.length : 0)
4872
- };
4873
- },
4874
- byKey: (key) => {
4875
- if (!isFake) {
4876
- const origByKey = store.byKey?.bind(store);
4877
- if (typeof origByKey === "function") store.byKey = (key, extra) => {
4878
- if (!allowZero && isZeroKey(key)) return dxResolve(null);
4879
- return ensureDx(origByKey(key, extra));
4880
- };
4881
- }
4882
- return dxFromPromise(manageRequest.smartFetch({
4883
- url: `${urls}/${encodeURIComponent(String(key))}`,
4884
- init: {
4885
- token: readToken(),
4886
- headers: {
4887
- "Content-Type": "application/json",
4888
- ...headers || {}
4889
- }
4890
- },
4891
- tokenOptions,
5104
+ }).then((r) => {
5105
+ if (r.error) throw r.error;
5106
+ return r.data;
5107
+ }),
5108
+ update: (key, values) => fakeWrite({
5109
+ verb: "PATCH",
5110
+ body: values,
5111
+ key,
4892
5112
  config
4893
- }).then((resp) => {
4894
- if (!resp.ok) throw new Error(`byKey failed: ${resp.status} ${resp.statusText}`);
4895
- return resp.json();
4896
- }));
4897
- },
4898
- insert: (values) => fakeWrite({
4899
- verb: "POST",
4900
- body: values,
4901
- config
4902
- }).then((r) => {
4903
- if (r.error) throw r.error;
4904
- return r.data;
4905
- }),
4906
- update: (key, values) => fakeWrite({
4907
- verb: "PATCH",
4908
- body: values,
4909
- key,
4910
- config
4911
- }).then((r) => {
4912
- if (r.error) throw r.error;
4913
- return r.data;
4914
- }),
4915
- remove: (key) => fakeWrite({
4916
- verb: "DELETE",
4917
- key,
4918
- config
4919
- }).then((r) => {
4920
- if (r.error) throw r.error;
4921
- return key;
4922
- }),
4923
- ...csTanstack,
4924
- ...override?.fakeDataSource
4925
- });
4926
- else {
5113
+ }).then((r) => {
5114
+ if (r.error) throw r.error;
5115
+ return r.data;
5116
+ }),
5117
+ remove: (key) => fakeWrite({
5118
+ verb: "DELETE",
5119
+ key,
5120
+ config
5121
+ }).then((r) => {
5122
+ if (r.error) throw r.error;
5123
+ return key;
5124
+ }),
5125
+ ...csTanstack,
5126
+ ...override?.fakeDataSource
5127
+ });
5128
+ } else {
4927
5129
  const odsInst = new ods({
4928
5130
  url: urls,
4929
5131
  version: 4,
@@ -4947,6 +5149,7 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
4947
5149
  };
4948
5150
  stripZeroParams(req.params, allowZero, zeroGuardFields);
4949
5151
  override?.dataSource?.beforeSend?.(req);
5152
+ learnFirstLoad(req, latestToken);
4950
5153
  lastSent = {
4951
5154
  params: { ...req.params || {} },
4952
5155
  headers: { ...req.headers || {} }
@@ -4962,6 +5165,7 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
4962
5165
  if (p.status === 401) onStore401(err);
4963
5166
  },
4964
5167
  ...odsTanstack,
5168
+ ...odsPrefetch,
4965
5169
  ...override?.dataSource
4966
5170
  });
4967
5171
  /**
@@ -5112,7 +5316,7 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
5112
5316
  }
5113
5317
  } else store = odsInst;
5114
5318
  }
5115
- manageRequest.patchDxStore(store, override?.dataSource ? `${urls}::${nextStoreId()}` : `${urls}?${paramsIdentity(params)}::${stable(headers)}::${method}${force ? "::force" : ""}`, "share");
5319
+ if (!__capture) manageRequest.patchDxStore(store, override?.dataSource ? `${urls}::${nextStoreId()}` : `${urls}?${paramsIdentity(params)}::${stable(headers)}::${method}${force ? "::force" : ""}`, "share");
5116
5320
  applyByKeyGuardAndCache(store, {
5117
5321
  allowZero,
5118
5322
  cache
@@ -5126,7 +5330,8 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
5126
5330
  const origLoadSingle = dataSource.loadSingle;
5127
5331
  if (typeof origLoadSingle === "function") dataSource.loadSingle = function(prop, value, select) {
5128
5332
  if (!allowZero && isZeroKey(value)) return dxResolve(null);
5129
- return ensureDx(origLoadSingle.call(this, prop, value, select));
5333
+ const res = origLoadSingle.call(this, prop, value, select);
5334
+ return ensureDx(res);
5130
5335
  };
5131
5336
  let result;
5132
5337
  if (method !== "GET") {
@@ -5253,6 +5458,16 @@ const useFetchOData = async ({ url, options, source, type = "datasource", params
5253
5458
  }
5254
5459
  }
5255
5460
  if (method === "GET") {
5461
+ if (__capture) {
5462
+ if (__capture.load) await dataSource.store().load(__capture.load);
5463
+ else await dataSource.load();
5464
+ return {
5465
+ dataSource: null,
5466
+ data: null,
5467
+ statusCode: 200,
5468
+ error: null
5469
+ };
5470
+ }
5256
5471
  if (type === "data" || type === "fakedata") {
5257
5472
  const usedToken = readToken();
5258
5473
  try {
@@ -5375,12 +5590,32 @@ async function useNormalFetch(url, options, config) {
5375
5590
  const { notif } = useHelper();
5376
5591
  const isNotif = typeof options?.notif === "boolean" && options.notif === true ? notif : options?.notif;
5377
5592
  try {
5378
- const { token, tokenOptions, ...fetchOptions } = options;
5593
+ const { token, tokenOptions, prefetch, ...fetchOptions } = options;
5379
5594
  const freshToken = await ensureFreshToken({
5380
5595
  token,
5381
5596
  config,
5382
5597
  tokenOptions
5383
5598
  }) ?? void 0;
5599
+ const fullUrl = (options?.baseUrl ?? "") + url;
5600
+ const isGet = String(fetchOptions.method ?? "GET").toUpperCase() === "GET" && fetchOptions.body == null;
5601
+ const bridge = prefetch !== false && isGet ? getPrefetchBridge() : null;
5602
+ if (bridge) {
5603
+ if (prefetch) learnPrefetch({
5604
+ url: fullUrl,
5605
+ headers: options?.headers,
5606
+ auth: prefetchAuthFor(freshToken ?? token, config, tokenOptions)
5607
+ });
5608
+ const hit = bridge.expects("GET", fullUrl) ? await bridge.take("GET", fullUrl) : void 0;
5609
+ if (hit) {
5610
+ const body = hit.data;
5611
+ return {
5612
+ data: body?.data,
5613
+ statusCode: 200,
5614
+ message: body?.message || null,
5615
+ all: body
5616
+ };
5617
+ }
5618
+ }
5384
5619
  response = await manageRequest.smartFetch({
5385
5620
  url: options?.baseUrl + url,
5386
5621
  init: {
@@ -5397,7 +5632,9 @@ async function useNormalFetch(url, options, config) {
5397
5632
  if (!response.ok) {
5398
5633
  if (response.status === 401) {
5399
5634
  callUnauth(options?.unauthCall);
5400
- if (options?.expiredBehaviour === "refresh" && !options?.unauthCall) window.location.reload();
5635
+ if (options?.expiredBehaviour === "refresh" && !options?.unauthCall) {
5636
+ if (typeof window !== "undefined") window.location.reload();
5637
+ }
5401
5638
  }
5402
5639
  const raw = await response.text();
5403
5640
  let errorResponse = null;
@@ -5448,7 +5685,7 @@ async function useNormalFetch(url, options, config) {
5448
5685
  }
5449
5686
  }
5450
5687
  async function tryCatchDatasource({ tryCallback, catchCallback, finallyCallback, notif }) {
5451
- const helper = window.helper || useHelper();
5688
+ const helper = typeof window !== "undefined" && window.helper || useHelper();
5452
5689
  const isNotif = typeof notif === "boolean" && notif === true ? helper.notif : notif;
5453
5690
  try {
5454
5691
  return await tryCallback();
@@ -5814,4 +6051,4 @@ function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
5814
6051
  var MonoNotivue_default = /*#__PURE__*/ export_helper_default(_sfc_main, [["render", _sfc_render], ["__file", "C:\\Users\\VCT-DEV\\Desktop\\libs\\packages\\utility\\src\\components\\MonoNotivue.vue"]]);
5815
6052
 
5816
6053
  //#endregion
5817
- export { monoEnv as C, monoStateReset as E, monoConfig as S, monoStatePatch as T, monoUseState as _, createUniqueFetcher as a, createMono as b, tryCatchDatasource as c, useHelper as d, createStaticDatasource as f, clearNuxtState as g, defineLayout as h, createFetcher as i, useFetchOData as l, monoProvide as m, useMonoUtility as n, loadChuckStore as o, monoInject as p, Notif_default as r, promiseWrapper as s, MonoNotivue_default as t, useNormalFetch as u, nuxtStateKeys as v, monoState as w, initMono as x, useState as y };
6054
+ export { createMono as C, monoState as D, monoEnv as E, monoStatePatch as O, useState as S, monoConfig as T, monoProvide as _, createUniqueFetcher as a, monoUseState as b, tryCatchDatasource as c, PREFETCH_SUPPORT as d, getPrefetchBridge as f, monoInject as g, createStaticDatasource as h, createFetcher as i, monoStateReset as k, useFetchOData as l, useHelper as m, useMonoUtility as n, loadChuckStore as o, setPrefetchBridge as p, Notif_default as r, promiseWrapper as s, MonoNotivue_default as t, useNormalFetch as u, defineLayout as v, initMono as w, nuxtStateKeys as x, clearNuxtState as y };