tevrocsdk 0.1.81 → 0.1.83

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/tevroc-sdk.esm.js CHANGED
@@ -8711,13 +8711,13 @@ var require_html2canvas = __commonJS({
8711
8711
  var textList = toCodePoints$1(node2.data).map(function(i5) {
8712
8712
  return fromCodePoint$1(i5);
8713
8713
  });
8714
- var offset = 0;
8714
+ var offset2 = 0;
8715
8715
  var prev = {};
8716
8716
  var supports = textList.every(function(text2, i5) {
8717
- range.setStart(node2, offset);
8718
- range.setEnd(node2, offset + text2.length);
8717
+ range.setStart(node2, offset2);
8718
+ range.setEnd(node2, offset2 + text2.length);
8719
8719
  var rect = range.getBoundingClientRect();
8720
- offset += text2.length;
8720
+ offset2 += text2.length;
8721
8721
  var boundAhead = rect.x > prev.x || rect.y > prev.y;
8722
8722
  prev = rect;
8723
8723
  if (i5 === 0) {
@@ -8866,16 +8866,16 @@ var require_html2canvas = __commonJS({
8866
8866
  var parseTextBounds = function(context, value, styles, node2) {
8867
8867
  var textList = breakText(value, styles);
8868
8868
  var textBounds = [];
8869
- var offset = 0;
8869
+ var offset2 = 0;
8870
8870
  textList.forEach(function(text2) {
8871
8871
  if (styles.textDecorationLine.length || text2.trim().length > 0) {
8872
8872
  if (FEATURES.SUPPORT_RANGE_BOUNDS) {
8873
- var clientRects = createRange(node2, offset, text2.length).getClientRects();
8873
+ var clientRects = createRange(node2, offset2, text2.length).getClientRects();
8874
8874
  if (clientRects.length > 1) {
8875
8875
  var subSegments = segmentGraphemes(text2);
8876
8876
  var subOffset_1 = 0;
8877
8877
  subSegments.forEach(function(subSegment) {
8878
- textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node2, subOffset_1 + offset, subSegment.length).getClientRects())));
8878
+ textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node2, subOffset_1 + offset2, subSegment.length).getClientRects())));
8879
8879
  subOffset_1 += subSegment.length;
8880
8880
  });
8881
8881
  } else {
@@ -8889,7 +8889,7 @@ var require_html2canvas = __commonJS({
8889
8889
  } else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
8890
8890
  node2 = node2.splitText(text2.length);
8891
8891
  }
8892
- offset += text2.length;
8892
+ offset2 += text2.length;
8893
8893
  });
8894
8894
  return textBounds;
8895
8895
  };
@@ -8910,14 +8910,14 @@ var require_html2canvas = __commonJS({
8910
8910
  }
8911
8911
  return Bounds.EMPTY;
8912
8912
  };
8913
- var createRange = function(node2, offset, length) {
8913
+ var createRange = function(node2, offset2, length) {
8914
8914
  var ownerDocument = node2.ownerDocument;
8915
8915
  if (!ownerDocument) {
8916
8916
  throw new Error("Node has no owner document");
8917
8917
  }
8918
8918
  var range = ownerDocument.createRange();
8919
- range.setStart(node2, offset);
8920
- range.setEnd(node2, offset + length);
8919
+ range.setStart(node2, offset2);
8920
+ range.setEnd(node2, offset2 + length);
8921
8921
  return range;
8922
8922
  };
8923
8923
  var segmentGraphemes = function(value) {
@@ -21228,13 +21228,13 @@ var init_index_es = __esm({
21228
21228
  } else if (typeof ctx.mozDash !== "undefined" && !(gaps.length === 1 && gaps[0] === 0)) {
21229
21229
  ctx.mozDash = gaps;
21230
21230
  }
21231
- var offset = strokeDashoffsetProp.getPixels();
21231
+ var offset2 = strokeDashoffsetProp.getPixels();
21232
21232
  if (typeof ctx.lineDashOffset !== "undefined") {
21233
- ctx.lineDashOffset = offset;
21233
+ ctx.lineDashOffset = offset2;
21234
21234
  } else if (typeof ctx.webkitLineDashOffset !== "undefined") {
21235
- ctx.webkitLineDashOffset = offset;
21235
+ ctx.webkitLineDashOffset = offset2;
21236
21236
  } else if (typeof ctx.mozDashOffset !== "undefined") {
21237
- ctx.mozDashOffset = offset;
21237
+ ctx.mozDashOffset = offset2;
21238
21238
  }
21239
21239
  }
21240
21240
  }
@@ -22671,7 +22671,7 @@ var init_index_es = __esm({
22671
22671
  constructor(document2, node2, captureTextNodes) {
22672
22672
  super(document2, node2, captureTextNodes);
22673
22673
  this.type = "stop";
22674
- var offset = Math.max(0, Math.min(1, this.getAttribute("offset").getNumber()));
22674
+ var offset2 = Math.max(0, Math.min(1, this.getAttribute("offset").getNumber()));
22675
22675
  var stopOpacity = this.getStyle("stop-opacity");
22676
22676
  var stopColor = this.getStyle("stop-color", true);
22677
22677
  if (stopColor.getString() === "") {
@@ -22680,7 +22680,7 @@ var init_index_es = __esm({
22680
22680
  if (stopOpacity.hasValue()) {
22681
22681
  stopColor = stopColor.addOpacity(stopOpacity);
22682
22682
  }
22683
- this.offset = offset;
22683
+ this.offset = offset2;
22684
22684
  this.color = stopColor.getColor();
22685
22685
  }
22686
22686
  };
@@ -23079,17 +23079,17 @@ var init_index_es = __esm({
23079
23079
  return this.letterSpacingCache[idx] || 0;
23080
23080
  }
23081
23081
  findSegmentToFitChar(ctx, anchor, textFullWidth, fullPathWidth, spacesNumber, inputOffset, dy, c4, charI) {
23082
- var offset = inputOffset;
23082
+ var offset2 = inputOffset;
23083
23083
  var glyphWidth = this.measureText(ctx, c4);
23084
23084
  if (c4 === " " && anchor === "justify" && textFullWidth < fullPathWidth) {
23085
23085
  glyphWidth += (fullPathWidth - textFullWidth) / spacesNumber;
23086
23086
  }
23087
23087
  if (charI > -1) {
23088
- offset += this.getLetterSpacingAt(charI);
23088
+ offset2 += this.getLetterSpacingAt(charI);
23089
23089
  }
23090
23090
  var splineStep = this.textHeight / 20;
23091
- var p0 = this.getEquidistantPointOnPath(offset, splineStep, 0);
23092
- var p1 = this.getEquidistantPointOnPath(offset + glyphWidth, splineStep, 0);
23091
+ var p0 = this.getEquidistantPointOnPath(offset2, splineStep, 0);
23092
+ var p1 = this.getEquidistantPointOnPath(offset2 + glyphWidth, splineStep, 0);
23093
23093
  var segment = {
23094
23094
  p0,
23095
23095
  p1
@@ -23107,9 +23107,9 @@ var init_index_es = __esm({
23107
23107
  y: p1.y + dyY
23108
23108
  });
23109
23109
  }
23110
- offset += glyphWidth;
23110
+ offset2 += glyphWidth;
23111
23111
  return {
23112
- offset,
23112
+ offset: offset2,
23113
23113
  segment,
23114
23114
  rotation
23115
23115
  };
@@ -23163,21 +23163,21 @@ var init_index_es = __esm({
23163
23163
  this.glyphInfo = [];
23164
23164
  var fullPathWidth = this.getPathLength();
23165
23165
  var startOffset = this.getStyle("startOffset").getNumber(0) * fullPathWidth;
23166
- var offset = 0;
23166
+ var offset2 = 0;
23167
23167
  if (anchor === "middle" || anchor === "center") {
23168
- offset = -textFullWidth / 2;
23168
+ offset2 = -textFullWidth / 2;
23169
23169
  }
23170
23170
  if (anchor === "end" || anchor === "right") {
23171
- offset = -textFullWidth;
23171
+ offset2 = -textFullWidth;
23172
23172
  }
23173
- offset += startOffset;
23173
+ offset2 += startOffset;
23174
23174
  chars.forEach((char, i5) => {
23175
23175
  var {
23176
23176
  offset: nextOffset,
23177
23177
  segment,
23178
23178
  rotation
23179
- } = this.findSegmentToFitChar(ctx, anchor, textFullWidth, fullPathWidth, spacesNumber, offset, dy, char, i5);
23180
- offset = nextOffset;
23179
+ } = this.findSegmentToFitChar(ctx, anchor, textFullWidth, fullPathWidth, spacesNumber, offset2, dy, char, i5);
23180
+ offset2 = nextOffset;
23181
23181
  if (!segment.p0 || !segment.p1) {
23182
23182
  return;
23183
23183
  }
@@ -25805,10 +25805,10 @@ var init_dist_js2 = __esm({
25805
25805
  *
25806
25806
  * @since 2.0.0
25807
25807
  */
25808
- async seek(offset, whence) {
25808
+ async seek(offset2, whence) {
25809
25809
  return await invoke("plugin:fs|seek", {
25810
25810
  rid: this.rid,
25811
- offset,
25811
+ offset: offset2,
25812
25812
  whence
25813
25813
  });
25814
25814
  }
@@ -28149,12 +28149,12 @@ var IOBuffer = class _IOBuffer {
28149
28149
  dataIsGiven = true;
28150
28150
  this.lastWrittenByte = data.byteLength;
28151
28151
  }
28152
- const offset = options.offset ? options.offset >>> 0 : 0;
28153
- const byteLength = data.byteLength - offset;
28154
- let dvOffset = offset;
28152
+ const offset2 = options.offset ? options.offset >>> 0 : 0;
28153
+ const byteLength = data.byteLength - offset2;
28154
+ let dvOffset = offset2;
28155
28155
  if (ArrayBuffer.isView(data) || data instanceof _IOBuffer) {
28156
28156
  if (data.byteLength !== data.buffer.byteLength) {
28157
- dvOffset = data.byteOffset + offset;
28157
+ dvOffset = data.byteOffset + offset2;
28158
28158
  }
28159
28159
  data = data.buffer;
28160
28160
  }
@@ -28236,8 +28236,8 @@ var IOBuffer = class _IOBuffer {
28236
28236
  * @param offset - The offset to move to.
28237
28237
  * @returns This.
28238
28238
  */
28239
- seek(offset) {
28240
- this.offset = offset;
28239
+ seek(offset2) {
28240
+ this.offset = offset2;
28241
28241
  return this;
28242
28242
  }
28243
28243
  /**
@@ -28274,11 +28274,11 @@ var IOBuffer = class _IOBuffer {
28274
28274
  * @returns This.
28275
28275
  */
28276
28276
  popMark() {
28277
- const offset = this._marks.pop();
28278
- if (offset === void 0) {
28277
+ const offset2 = this._marks.pop();
28278
+ if (offset2 === void 0) {
28279
28279
  throw new Error("Mark stack empty");
28280
28280
  }
28281
- this.seek(offset);
28281
+ this.seek(offset2);
28282
28282
  return this;
28283
28283
  }
28284
28284
  /**
@@ -28356,10 +28356,10 @@ var IOBuffer = class _IOBuffer {
28356
28356
  */
28357
28357
  readArray(size2, type) {
28358
28358
  const bytes = typedArrays[type].BYTES_PER_ELEMENT * size2;
28359
- const offset = this.byteOffset + this.offset;
28360
- const slice = this.buffer.slice(offset, offset + bytes);
28359
+ const offset2 = this.byteOffset + this.offset;
28360
+ const slice = this.buffer.slice(offset2, offset2 + bytes);
28361
28361
  if (this.littleEndian === hostBigEndian && type !== "uint8" && type !== "int8") {
28362
- const slice2 = new Uint8Array(this.buffer.slice(offset, offset + bytes));
28362
+ const slice2 = new Uint8Array(this.buffer.slice(offset2, offset2 + bytes));
28363
28363
  slice2.reverse();
28364
28364
  const returnArray2 = new typedArrays[type](slice2.buffer);
28365
28365
  this.offset += bytes;
@@ -33063,7 +33063,7 @@ function decodeInterlaceAdam7(params) {
33063
33063
  ];
33064
33064
  const bytesPerPixel = Math.ceil(depth / 8) * channels;
33065
33065
  const resultData = new Uint8Array(height * width * bytesPerPixel);
33066
- let offset = 0;
33066
+ let offset2 = 0;
33067
33067
  for (let passIndex = 0; passIndex < 7; passIndex++) {
33068
33068
  const pass = passes[passIndex];
33069
33069
  const passWidth = Math.ceil((width - pass.x) / pass.xStep);
@@ -33073,9 +33073,9 @@ function decodeInterlaceAdam7(params) {
33073
33073
  const passLineBytes = passWidth * bytesPerPixel;
33074
33074
  const prevLine = new Uint8Array(passLineBytes);
33075
33075
  for (let y3 = 0; y3 < passHeight; y3++) {
33076
- const filterType = data[offset++];
33077
- const currentLine = data.subarray(offset, offset + passLineBytes);
33078
- offset += passLineBytes;
33076
+ const filterType = data[offset2++];
33077
+ const currentLine = data.subarray(offset2, offset2 + passLineBytes);
33078
+ offset2 += passLineBytes;
33079
33079
  const newLine = new Uint8Array(passLineBytes);
33080
33080
  applyUnfilter(filterType, currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
33081
33081
  prevLine.set(newLine);
@@ -33117,13 +33117,13 @@ function decodeInterlaceNull(params) {
33117
33117
  const bytesPerLine = Math.ceil(depth / 8 * channels * width);
33118
33118
  const newData = new Uint8Array(height * bytesPerLine);
33119
33119
  let prevLine = empty;
33120
- let offset = 0;
33120
+ let offset2 = 0;
33121
33121
  let currentLine;
33122
33122
  let newLine;
33123
33123
  for (let i4 = 0; i4 < height; i4++) {
33124
- currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);
33124
+ currentLine = data.subarray(offset2 + 1, offset2 + 1 + bytesPerLine);
33125
33125
  newLine = newData.subarray(i4 * bytesPerLine, (i4 + 1) * bytesPerLine);
33126
- switch (data[offset]) {
33126
+ switch (data[offset2]) {
33127
33127
  case 0:
33128
33128
  unfilterNone(currentLine, newLine, bytesPerLine);
33129
33129
  break;
@@ -33140,10 +33140,10 @@ function decodeInterlaceNull(params) {
33140
33140
  unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
33141
33141
  break;
33142
33142
  default:
33143
- throw new Error(`Unsupported filter: ${data[offset]}`);
33143
+ throw new Error(`Unsupported filter: ${data[offset2]}`);
33144
33144
  }
33145
33145
  prevLine = newLine;
33146
- offset += bytesPerLine + 1;
33146
+ offset2 += bytesPerLine + 1;
33147
33147
  }
33148
33148
  if (depth === 16) {
33149
33149
  const uint16Data = new Uint16Array(newData.buffer);
@@ -33328,7 +33328,7 @@ var PngDecoder = class extends IOBuffer {
33328
33328
  }
33329
33329
  // https://www.w3.org/TR/PNG/#5Chunk-layout
33330
33330
  decodeChunk(length, type) {
33331
- const offset = this.offset;
33331
+ const offset2 = this.offset;
33332
33332
  switch (type) {
33333
33333
  // 11.2 Critical chunks
33334
33334
  case "IHDR":
@@ -33360,7 +33360,7 @@ var PngDecoder = class extends IOBuffer {
33360
33360
  this.skip(length);
33361
33361
  break;
33362
33362
  }
33363
- if (this.offset - offset !== length) {
33363
+ if (this.offset - offset2 !== length) {
33364
33364
  throw new Error(`Length mismatch while decoding chunk ${type}`);
33365
33365
  }
33366
33366
  if (this._checkCrc) {
@@ -33370,7 +33370,7 @@ var PngDecoder = class extends IOBuffer {
33370
33370
  }
33371
33371
  }
33372
33372
  decodeApngChunk(length, type) {
33373
- const offset = this.offset;
33373
+ const offset2 = this.offset;
33374
33374
  if (type !== "fdAT" && type !== "IDAT" && this._writingDataChunks) {
33375
33375
  this.pushDataToFrame();
33376
33376
  }
@@ -33386,10 +33386,10 @@ var PngDecoder = class extends IOBuffer {
33386
33386
  break;
33387
33387
  default:
33388
33388
  this.decodeChunk(length, type);
33389
- this.offset = offset + length;
33389
+ this.offset = offset2 + length;
33390
33390
  break;
33391
33391
  }
33392
- if (this.offset - offset !== length) {
33392
+ if (this.offset - offset2 !== length) {
33393
33393
  throw new Error(`Length mismatch while decoding chunk ${type}`);
33394
33394
  }
33395
33395
  if (this._checkCrc) {
@@ -42147,15 +42147,15 @@ async function downloadUrlToBase64(url) {
42147
42147
  if (!url) return null;
42148
42148
  if (!isNative) return null;
42149
42149
  try {
42150
- console.debug(`[tevrocsdk][fileoffline] downloadUrlToBase64 fetching`, url);
42150
+ debugLog(`[tevrocsdk][fileoffline] downloadUrlToBase64 fetching`, url);
42151
42151
  const res = await fetch(url, { cache: "no-store" });
42152
42152
  if (!res.ok) return null;
42153
42153
  const b2 = await res.blob();
42154
42154
  const base64 = await blobToBase642(b2).catch(() => null);
42155
- console.debug(`[tevrocsdk][fileoffline] downloadUrlToBase64 fetched -> base64 length`, base64 ? base64.length : 0);
42155
+ debugLog(`[tevrocsdk][fileoffline] downloadUrlToBase64 fetched -> base64 length`, base64 ? base64.length : 0);
42156
42156
  return base64;
42157
42157
  } catch (e2) {
42158
- console.warn(`[tevrocsdk][fileoffline] downloadUrlToBase64 failed`, e2);
42158
+ debugWarn(`[tevrocsdk][fileoffline] downloadUrlToBase64 failed`, e2);
42159
42159
  return null;
42160
42160
  }
42161
42161
  }
@@ -42173,34 +42173,34 @@ function deriveKeyFromUrl(url) {
42173
42173
  async function persistFileToNative(client, key, base64, contentType) {
42174
42174
  try {
42175
42175
  if (!isNative) return false;
42176
- console.debug("[tevrocsdk][fileoffline] persistFileToNative", { key, contentType, hasBase64: !!base64 });
42176
+ debugLog("[tevrocsdk][fileoffline] persistFileToNative", { key, contentType, hasBase64: !!base64 });
42177
42177
  if (!client?.native?.store || !base64) {
42178
- console.warn("[tevrocsdk][fileoffline] persistFileToNative skipped - missing native.store or base64");
42178
+ debugWarn("[tevrocsdk][fileoffline] persistFileToNative skipped - missing native.store or base64");
42179
42179
  return false;
42180
42180
  }
42181
42181
  const now = (/* @__PURE__ */ new Date()).toISOString();
42182
42182
  await client.native.store.set(`downloaded_files/${key}`, { data: base64, contentType: contentType || "application/octet-stream", key, updatedAt: now });
42183
- console.debug("[tevrocsdk][fileoffline] persistFileToNative stored", { key, updatedAt: now });
42183
+ debugLog("[tevrocsdk][fileoffline] persistFileToNative stored", { key, updatedAt: now });
42184
42184
  return true;
42185
42185
  } catch (e2) {
42186
- console.warn("[tevrocsdk][fileoffline] persistFileToNative error", e2);
42186
+ debugWarn("[tevrocsdk][fileoffline] persistFileToNative error", e2);
42187
42187
  return false;
42188
42188
  }
42189
42189
  }
42190
42190
  async function walkAndPersistFiles(client, obj) {
42191
42191
  if (!obj || typeof obj !== "object") return;
42192
42192
  if (!isNative || !client?.native?.store) return;
42193
- console.debug("[tevrocsdk][fileoffline] walkAndPersistFiles start");
42193
+ debugLog("[tevrocsdk][fileoffline] walkAndPersistFiles start");
42194
42194
  for (const k2 of Object.keys(obj)) {
42195
42195
  const v3 = obj[k2];
42196
42196
  if (typeof v3 === "string") {
42197
42197
  if (isDataUrl(v3)) {
42198
- console.debug("[tevrocsdk][fileoffline] walkAndPersistFiles found data URL at key", k2);
42198
+ debugLog("[tevrocsdk][fileoffline] walkAndPersistFiles found data URL at key", k2);
42199
42199
  const base64 = extractBase64FromDataUrl(v3);
42200
42200
  const key = deriveKeyFromUrl(k2) || `inline_${Date.now()}`;
42201
42201
  await persistFileToNative(client, key, base64, (v3.match(/^data:([^;]+);/) || [])[1] || "application/octet-stream");
42202
42202
  } else if (/^https?:\/\//.test(v3) || v3.startsWith("filebase://")) {
42203
- console.debug("[tevrocsdk][fileoffline] walkAndPersistFiles found URL at key", k2, v3);
42203
+ debugLog("[tevrocsdk][fileoffline] walkAndPersistFiles found URL at key", k2, v3);
42204
42204
  const url = v3.startsWith("filebase://") ? v3.replace(/^filebase:\/\//, "") : v3;
42205
42205
  const base64 = await downloadUrlToBase64(v3).catch(() => null);
42206
42206
  if (base64) {
@@ -42208,16 +42208,16 @@ async function walkAndPersistFiles(client, obj) {
42208
42208
  await persistFileToNative(client, key, base64, "application/octet-stream");
42209
42209
  }
42210
42210
  } else if (isLikelyBase64(v3)) {
42211
- console.debug("[tevrocsdk][fileoffline] walkAndPersistFiles found inline base64 at key", k2);
42211
+ debugLog("[tevrocsdk][fileoffline] walkAndPersistFiles found inline base64 at key", k2);
42212
42212
  const key = deriveKeyFromUrl(k2) || `inline_${Date.now()}`;
42213
42213
  await persistFileToNative(client, key, v3, "application/octet-stream");
42214
42214
  }
42215
42215
  } else if (v3 && typeof v3 === "object") {
42216
- console.debug("[tevrocsdk][fileoffline] walkAndPersistFiles recursing into", k2);
42216
+ debugLog("[tevrocsdk][fileoffline] walkAndPersistFiles recursing into", k2);
42217
42217
  await walkAndPersistFiles(client, v3);
42218
42218
  }
42219
42219
  }
42220
- console.debug("[tevrocsdk][fileoffline] walkAndPersistFiles end");
42220
+ debugLog("[tevrocsdk][fileoffline] walkAndPersistFiles end");
42221
42221
  }
42222
42222
  function createOfflineManager(client) {
42223
42223
  const store = createNativeStore(client.appId);
@@ -42723,10 +42723,13 @@ function createChatbotClient(options = {}) {
42723
42723
  var TevrocClient = class {
42724
42724
  constructor(options = {}) {
42725
42725
  const baseUrl = options.baseUrl ?? options.url;
42726
- const serviceUrl = options.serviceUrl ?? options.url;
42726
+ const serviceUrl = options.serviceUrl ?? options.url ?? baseUrl;
42727
+ const vpsUrl = options.vpsUrl ?? serviceUrl;
42727
42728
  if (!baseUrl) throw new TypeError("createClient requires a baseUrl");
42728
42729
  this.baseUrl = normalizeBaseUrl(baseUrl);
42729
42730
  this.serviceUrl = normalizeBaseUrl(serviceUrl);
42731
+ this.vpsUrl = normalizeBaseUrl(vpsUrl);
42732
+ this.vpsConfig = { ...options.vpsConfig || options.config || {} };
42730
42733
  this.appId = options.appId;
42731
42734
  this.appName = options.appName;
42732
42735
  this.payAccount = options.payAccount ?? "default";
@@ -42735,11 +42738,14 @@ var TevrocClient = class {
42735
42738
  throw new TypeError("No fetch implementation available");
42736
42739
  }
42737
42740
  this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
42741
+ this.axios = options.axios;
42738
42742
  this.defaultHeaders = normalizeHeaders(options.headers);
42739
42743
  this.token = options.token ?? null;
42740
42744
  this.debug = options.debug ?? false;
42741
42745
  setSdkDebug(this.debug);
42742
42746
  this.auth = createAuthApi(this);
42747
+ this.vps = createVpsApi(this);
42748
+ this.database = this.vps.database;
42743
42749
  this.entities = createEntityRegistry(this);
42744
42750
  this.functions = createFunctionRegistry(this);
42745
42751
  this.integrations = createIntegrationApi(this);
@@ -42796,7 +42802,15 @@ var TevrocClient = class {
42796
42802
  }
42797
42803
  clearToken() {
42798
42804
  this.token = null;
42799
- safeLocalStorage()?.removeItem("tevroc_access_token");
42805
+ const storage = safeLocalStorage();
42806
+ [
42807
+ "tevroc_access_token",
42808
+ "base44_access_token",
42809
+ "native_access_token",
42810
+ "token",
42811
+ "idToken",
42812
+ "user"
42813
+ ].forEach((key) => storage?.removeItem(key));
42800
42814
  return this;
42801
42815
  }
42802
42816
  setDebug(enabled) {
@@ -42808,7 +42822,8 @@ var TevrocClient = class {
42808
42822
  const method = (options.method ?? "GET").toUpperCase();
42809
42823
  const headers = new Headers(this.defaultHeaders);
42810
42824
  const query = options.query ? toSearchParams(options.query) : "";
42811
- const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}${query}`;
42825
+ const requestBaseUrl = options.baseUrl ?? this.baseUrl;
42826
+ const url = `${requestBaseUrl}${path.startsWith("/") ? path : `/${path}`}${query}`;
42812
42827
  const controller = new AbortController();
42813
42828
  const timeoutMsActual = options.timeoutMs || this.timeoutMs || 2500;
42814
42829
  let timeout = null;
@@ -42849,13 +42864,23 @@ var TevrocClient = class {
42849
42864
  debugWarn2(this, "[tevrocsdk] pending sync failed", err2);
42850
42865
  }
42851
42866
  }
42852
- let fetchPromise;
42853
- fetchPromise = this.fetch(url, {
42854
- method,
42855
- headers,
42856
- body,
42857
- signal: options.signal ?? controller.signal
42858
- });
42867
+ let requestPromise;
42868
+ if (this.axios?.request) {
42869
+ requestPromise = this.axios.request({
42870
+ url,
42871
+ method,
42872
+ headers: Object.fromEntries(headers.entries()),
42873
+ data: body,
42874
+ signal: options.signal ?? controller.signal
42875
+ }).then((response) => parseAxiosResponse(response, options.parseAs));
42876
+ } else {
42877
+ requestPromise = this.fetch(url, {
42878
+ method,
42879
+ headers,
42880
+ body,
42881
+ signal: options.signal ?? controller.signal
42882
+ }).then((response) => parseResponse(response, options.parseAs));
42883
+ }
42859
42884
  const timeoutPromise = new Promise((_3, reject) => {
42860
42885
  timeout = setTimeout(() => {
42861
42886
  try {
@@ -42865,8 +42890,7 @@ var TevrocClient = class {
42865
42890
  reject(new TevrocError("Request timed out", { code: "timeout" }));
42866
42891
  }, timeoutMsActual);
42867
42892
  });
42868
- const response = await Promise.race([fetchPromise, timeoutPromise]);
42869
- let ret = await parseResponse(response, options.parseAs);
42893
+ let ret = await Promise.race([requestPromise, timeoutPromise]);
42870
42894
  debugLog2(this, "Response from request:", ret);
42871
42895
  return ret;
42872
42896
  } catch (error) {
@@ -42879,6 +42903,67 @@ var TevrocClient = class {
42879
42903
  }
42880
42904
  }
42881
42905
  };
42906
+ function createVpsApi(client) {
42907
+ const request = (path, options = {}) => client.request(path, { ...options, baseUrl: client.vpsUrl });
42908
+ const withSession = (session, query = {}) => ({
42909
+ ...query,
42910
+ session: session ?? client.vpsConfig.session
42911
+ });
42912
+ const encodeSql = (sql) => {
42913
+ if (typeof sql !== "string" || !sql.trim()) throw new TypeError("sql must be a non-empty string");
42914
+ if (typeof btoa === "function") return btoa(unescape(encodeURIComponent(sql)));
42915
+ return Buffer.from(sql, "utf8").toString("base64");
42916
+ };
42917
+ const database = {
42918
+ dialect: () => request("/database/sql", { auth: false }),
42919
+ tables: (options = {}) => request("/database/tables", { query: withSession(options.session, options), auth: false }),
42920
+ table: (table, options = {}) => request("/database/table", {
42921
+ query: withSession(options.session, { ...options, table }),
42922
+ auth: false
42923
+ }),
42924
+ exec: (sql, options = {}) => request("/database/query/exec", {
42925
+ query: withSession(options.session, { ...options, query: encodeSql(sql) }),
42926
+ auth: false
42927
+ }),
42928
+ query: (sql, options = {}) => database.exec(sql, options)
42929
+ };
42930
+ const auth = {
42931
+ login: async (email, password, options = {}) => {
42932
+ const result = await request("/login", { query: { ...options, email, password }, auth: false });
42933
+ if (result?.session) client.setToken(result.session);
42934
+ return result;
42935
+ },
42936
+ verifyOtp: async (email, otp, options = {}) => {
42937
+ const result = await request("/auth-otp", { query: { ...options, email, otp }, auth: false });
42938
+ if (result?.session) client.setToken(result.session);
42939
+ return result;
42940
+ },
42941
+ register: (input, options = {}) => request(options.path || "/auth/register", { method: "POST", body: input, auth: false }),
42942
+ resetPassword: (input, options = {}) => request(options.path || "/auth/reset-password", { method: "POST", body: input, auth: false }),
42943
+ changePassword: (input, options = {}) => request(options.path || "/auth/change-password", { method: "POST", body: input }),
42944
+ session: (session = client.token, options = {}) => request("/session", { query: withSession(session, options), auth: false }),
42945
+ userType: (session = client.token, options = {}) => request("/get-usertype", { query: withSession(session, options), auth: false }),
42946
+ user: (session = client.token, options = {}) => request("/get-user", { query: withSession(session, options), auth: false }),
42947
+ hasOnboarded: (session = client.token, options = {}) => request("/has-onboarded", { query: withSession(session, options), auth: false }),
42948
+ hasVerified: (session = client.token, options = {}) => request("/has-verified", { query: withSession(session, options), auth: false }),
42949
+ updateProfile: (session, data, options = {}) => request("/update-profile", { query: withSession(session, { ...options, jsonObject: JSON.stringify(data) }), auth: false }),
42950
+ updateOnboarding: (session, data, options = {}) => request("/update-onboarding", { query: withSession(session, { ...options, jsonObject: JSON.stringify(data) }), auth: false }),
42951
+ logout: () => {
42952
+ client.clearToken();
42953
+ return Promise.resolve({ ok: true });
42954
+ }
42955
+ };
42956
+ return {
42957
+ request,
42958
+ auth,
42959
+ database,
42960
+ environment: () => request("/api/environment", { auth: false }),
42961
+ platform: () => request("/platform", { auth: false }),
42962
+ notifications: (options = {}) => request("/api/notifications", { query: options, auth: false }),
42963
+ accountContext: (session = client.token, options = {}) => request("/api/mobile/account-context", { query: withSession(session, options), auth: false }),
42964
+ avatarUrl: (options = {}) => `${client.vpsUrl}/api/avatar${toSearchParams(options)}`
42965
+ };
42966
+ }
42882
42967
  function createShiplogicApi(client) {
42883
42968
  return {
42884
42969
  getRates: (payload = {}) => client.request("/shiplogic/rates", { method: "POST", body: payload }),
@@ -43073,7 +43158,7 @@ function createAuthApi(client) {
43073
43158
  // base44
43074
43159
  loginWithProvider: async (provider, redirectTo, setToken = async () => {
43075
43160
  }) => {
43076
- console.log(client, "loginWithProvider called", { provider, redirectTo });
43161
+ debugLog2(client, "loginWithProvider called", { provider, redirectTo });
43077
43162
  if (provider === "google") {
43078
43163
  const { createGoogleLogin: createGoogleLogin2, subscribeGoogleLogin: subscribeGoogleLogin2 } = await getGoogleModule();
43079
43164
  debugLog2(client, {
@@ -43081,11 +43166,6 @@ function createAuthApi(client) {
43081
43166
  appId: client.appId,
43082
43167
  appName: client.appName
43083
43168
  });
43084
- await createGoogleLogin2({
43085
- serviceUrl: client.serviceUrl,
43086
- appId: client.appId,
43087
- appName: client.appName
43088
- });
43089
43169
  if (redirectTo) {
43090
43170
  const unsub = subscribeGoogleLogin2(async (user, err2) => {
43091
43171
  debugLog2(client, "Google callback:", user, err2);
@@ -43101,6 +43181,22 @@ function createAuthApi(client) {
43101
43181
  debugLog2(client, "Redirecting to:", redirectTo);
43102
43182
  window.location.href = redirectTo;
43103
43183
  });
43184
+ try {
43185
+ await createGoogleLogin2({
43186
+ serviceUrl: client.serviceUrl,
43187
+ appId: client.appId,
43188
+ appName: client.appName
43189
+ });
43190
+ } catch (error) {
43191
+ unsub();
43192
+ throw error;
43193
+ }
43194
+ } else {
43195
+ await createGoogleLogin2({
43196
+ serviceUrl: client.serviceUrl,
43197
+ appId: client.appId,
43198
+ appName: client.appName
43199
+ });
43104
43200
  }
43105
43201
  }
43106
43202
  if (provider === "facebook") {
@@ -43232,9 +43328,11 @@ function createAuthApi(client) {
43232
43328
  return result;
43233
43329
  },
43234
43330
  async logout() {
43235
- const result = await client.request("/auth/logout", { method: "POST", body: buildAuthPayload({}, client) });
43236
- client.clearToken();
43237
- return result;
43331
+ try {
43332
+ return await client.request("/auth/logout", { method: "POST", body: buildAuthPayload({}, client) });
43333
+ } finally {
43334
+ client.clearToken();
43335
+ }
43238
43336
  },
43239
43337
  inviteUser: (input) => client.request("/users/invite", { method: "POST", body: buildAuthPayload(input, client) }),
43240
43338
  acceptInvite: (input) => client.request("/auth/accept-invite", { method: "POST", body: buildAuthPayload(input, client), auth: false }),
@@ -43770,10 +43868,10 @@ async function blobToBase643(blob) {
43770
43868
  async function readCachedFileResponse(client, key) {
43771
43869
  if (!client.native?.store || !isNative) return null;
43772
43870
  const cached = (await client.native.store.get(`downloaded_files/${key}`)).val();
43773
- console.debug("[tevrocsdk][files] readCachedFileResponse", { key, hasCached: !!cached?.data });
43871
+ debugLog2(client, "[tevrocsdk][files] readCachedFileResponse", { key, hasCached: !!cached?.data });
43774
43872
  if (!cached?.data) return null;
43775
43873
  const blob = base64ToBlob(cached.data, cached.contentType || "application/octet-stream");
43776
- console.debug("[tevrocsdk][files] readCachedFileResponse built blob", { key, size: blob && blob.size });
43874
+ debugLog2(client, "[tevrocsdk][files] readCachedFileResponse built blob", { key, size: blob && blob.size });
43777
43875
  return new Response(blob, {
43778
43876
  headers: { "content-type": cached.contentType || "application/octet-stream" }
43779
43877
  });
@@ -43781,14 +43879,14 @@ async function readCachedFileResponse(client, key) {
43781
43879
  async function storeCachedFileResponse(client, key, response, fallbackContentType = "application/octet-stream") {
43782
43880
  if (!client.native?.store || !isNative || !key) return;
43783
43881
  try {
43784
- console.debug("[tevrocsdk][files] storeCachedFileResponse", { key });
43882
+ debugLog2(client, "[tevrocsdk][files] storeCachedFileResponse", { key });
43785
43883
  const clone2 = response instanceof Response ? response.clone() : null;
43786
43884
  const blob = clone2 ? await clone2.blob() : null;
43787
43885
  const contentType = clone2 && clone2.headers.get("content-type") || fallbackContentType;
43788
43886
  const data = blob ? await blobToBase643(blob) : "";
43789
- console.debug("[tevrocsdk][files] storeCachedFileResponse data length", { key, length: data ? data.length : 0, contentType });
43887
+ debugLog2(client, "[tevrocsdk][files] storeCachedFileResponse data length", { key, length: data ? data.length : 0, contentType });
43790
43888
  if (!data) {
43791
- console.warn("[tevrocsdk][files] storeCachedFileResponse no data to store", { key });
43889
+ debugWarn2(client, "[tevrocsdk][files] storeCachedFileResponse no data to store", { key });
43792
43890
  return;
43793
43891
  }
43794
43892
  await client.native.store.set(`downloaded_files/${key}`, {
@@ -43797,18 +43895,18 @@ async function storeCachedFileResponse(client, key, response, fallbackContentTyp
43797
43895
  key,
43798
43896
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
43799
43897
  });
43800
- console.debug("[tevrocsdk][files] storeCachedFileResponse stored", { key });
43898
+ debugLog2(client, "[tevrocsdk][files] storeCachedFileResponse stored", { key });
43801
43899
  } catch (error) {
43802
43900
  debugWarn2(client, "Failed to cache downloaded file", error);
43803
- console.warn("[tevrocsdk][files] storeCachedFileResponse error", error);
43901
+ debugWarn2(client, "[tevrocsdk][files] storeCachedFileResponse error", error);
43804
43902
  }
43805
43903
  }
43806
43904
  async function readCachedFileDataUrl(client, key) {
43807
43905
  if (!client.native?.store || !isNative || !key) return null;
43808
43906
  const cached = (await client.native.store.get(`downloaded_files/${key}`)).val();
43809
- console.debug("[tevrocsdk][files] readCachedFileDataUrl", { key, hasCached: !!cached?.data });
43907
+ debugLog2(client, "[tevrocsdk][files] readCachedFileDataUrl", { key, hasCached: !!cached?.data });
43810
43908
  if (!cached?.data) return null;
43811
- console.debug("[tevrocsdk][files] readCachedFileDataUrl returning data url", { key, length: cached.data.length });
43909
+ debugLog2(client, "[tevrocsdk][files] readCachedFileDataUrl returning data url", { key, length: cached.data.length });
43812
43910
  return `data:${cached.contentType || "application/octet-stream"};base64,${cached.data}`;
43813
43911
  }
43814
43912
  function base64ToBlob(base64, contentType = "application/octet-stream") {
@@ -43822,29 +43920,6 @@ function base64ToBlob(base64, contentType = "application/octet-stream") {
43822
43920
  }
43823
43921
  return new Blob([bytes], { type: contentType });
43824
43922
  }
43825
- function arrayBufferToBase64(buffer) {
43826
- let binary = "";
43827
- const bytes = new Uint8Array(buffer);
43828
- const chunkSize = 32768;
43829
- for (let i4 = 0; i4 < bytes.length; i4 += chunkSize) {
43830
- const chunk = bytes.subarray(i4, i4 + chunkSize);
43831
- binary += String.fromCharCode.apply(null, chunk);
43832
- }
43833
- return btoa(binary);
43834
- }
43835
- async function normalizeUploadBody(file) {
43836
- if (typeof Blob !== "undefined" && file instanceof Blob) {
43837
- return { data: await blobToBase643(file), contentType: file.type || "application/octet-stream", bodyIsBase64: true };
43838
- }
43839
- if (file && typeof file.arrayBuffer === "function") {
43840
- const buffer = await file.arrayBuffer();
43841
- return { data: arrayBufferToBase64(buffer), contentType: "application/octet-stream", bodyIsBase64: true };
43842
- }
43843
- if (typeof file === "string") {
43844
- return { data: file, contentType: "text/plain", bodyIsBase64: false };
43845
- }
43846
- return { data: JSON.stringify(file), contentType: "application/json", bodyIsBase64: false };
43847
- }
43848
43923
  function createFileApi(client) {
43849
43924
  return {
43850
43925
  url: async (key) => {
@@ -43863,7 +43938,7 @@ function createFileApi(client) {
43863
43938
  }
43864
43939
  rounds += 1;
43865
43940
  } while (rawKey !== prev && rawKey.includes("%25") && rounds < 5);
43866
- if (rounds > 0) console.debug("[tevrocsdk][files] iterative decode performed", { original: key, rawKey, rounds });
43941
+ if (rounds > 0) debugLog2(client, "[tevrocsdk][files] iterative decode performed", { original: key, rawKey, rounds });
43867
43942
  } catch (e2) {
43868
43943
  }
43869
43944
  debugLog2(client, "[tevrocsdk][files:url]", { key, rawKey, online, offline, isNative });
@@ -43893,7 +43968,7 @@ function createFileApi(client) {
43893
43968
  }
43894
43969
  rounds += 1;
43895
43970
  } while (rawKey !== prev && rawKey.includes("%25") && rounds < 5);
43896
- if (rounds > 0) console.debug("[tevrocsdk][files] iterative decode performed (privateUrl)", { original: key, rawKey, rounds });
43971
+ if (rounds > 0) debugLog2(client, "[tevrocsdk][files] iterative decode performed (privateUrl)", { original: key, rawKey, rounds });
43897
43972
  } catch (e2) {
43898
43973
  }
43899
43974
  debugLog2(client, "[tevrocsdk][files:privateUrl]", { key, rawKey, online, offline, isNative });
@@ -43933,7 +44008,7 @@ function createFileApi(client) {
43933
44008
  }
43934
44009
  rounds += 1;
43935
44010
  } while (rawKey !== prev && rawKey.includes("%25") && rounds < 5);
43936
- if (rounds > 0) console.debug("[tevrocsdk][files] iterative decode performed (get)", { original: key, rawKey, rounds });
44011
+ if (rounds > 0) debugLog2(client, "[tevrocsdk][files] iterative decode performed (get)", { original: key, rawKey, rounds });
43937
44012
  } catch (e2) {
43938
44013
  }
43939
44014
  debugLog2(client, "[tevrocsdk][files] get", { key, rawKey, isNative, online, offline });
@@ -43963,7 +44038,7 @@ function createFileApi(client) {
43963
44038
  }
43964
44039
  rounds += 1;
43965
44040
  } while (rawKey !== prev && rawKey.includes("%25") && rounds < 5);
43966
- if (rounds > 0) console.debug("[tevrocsdk][files] iterative decode performed (getPrivate)", { original: key, rawKey, rounds });
44041
+ if (rounds > 0) debugLog2(client, "[tevrocsdk][files] iterative decode performed (getPrivate)", { original: key, rawKey, rounds });
43967
44042
  } catch (e2) {
43968
44043
  }
43969
44044
  debugLog2(client, "[tevrocsdk][files] getPrivate", { key, rawKey, isNative, online, offline });
@@ -43980,34 +44055,191 @@ function createFileApi(client) {
43980
44055
  };
43981
44056
  }
43982
44057
  async function upload(client, path, file, options = {}) {
43983
- const headers = {};
43984
- if (options.filename) headers["x-filename"] = options.filename;
43985
- if (options.contentType) headers["content-type"] = options.contentType;
43986
- if (isNative && client.offline) {
43987
- const online = await client.offline.isOnline();
43988
- if (!online) {
43989
- const id = options.filename || `file_${Date.now()}`;
43990
- const normalized = await normalizeUploadBody(file);
43991
- const payload = {
43992
- path,
44058
+ const isElectron = await detectElectronEnvironment(client);
44059
+ if (isElectron) {
44060
+ return uploadViaElectronBridge(client, file, options);
44061
+ }
44062
+ return uploadViaGoogleStorage(client, file, { ...options, path });
44063
+ }
44064
+ async function detectElectronEnvironment(client) {
44065
+ try {
44066
+ const serviceUrl = String(client?.serviceUrl || "").replace(/\/$/, "");
44067
+ const response = await client.fetch(`${serviceUrl}/api/environment`, {
44068
+ method: "GET",
44069
+ headers: { Accept: "application/json" },
44070
+ cache: "no-store"
44071
+ });
44072
+ if (response && response.ok) {
44073
+ const data = await response.json();
44074
+ if (data && typeof data === "object" && "isElectron" in data) {
44075
+ return Boolean(data.isElectron);
44076
+ }
44077
+ }
44078
+ } catch (error) {
44079
+ debugLog2(client, "[tevrocsdk][env] /api/environment fallback", error);
44080
+ }
44081
+ if (typeof navigator !== "undefined") {
44082
+ const userAgent = navigator.userAgent || "";
44083
+ if (/electron/i.test(userAgent)) return true;
44084
+ }
44085
+ if (typeof window !== "undefined") {
44086
+ const bridge = window?.bridge || window?.electronBridge || window?.nativeBridge;
44087
+ if (bridge) return true;
44088
+ if (window.process && window.process.versions && window.process.versions.electron) return true;
44089
+ }
44090
+ return false;
44091
+ }
44092
+ async function uploadViaElectronBridge(client, file, options = {}) {
44093
+ const fileName = options.filename || "upload";
44094
+ const contentType = options.contentType || "application/octet-stream";
44095
+ const resolvedFile = file instanceof Blob ? file : new Blob([String(file ?? "")], { type: contentType });
44096
+ const dataUrl = resolvedFile instanceof Blob ? `data:${contentType};base64,${await blobToBase643(resolvedFile)}` : String(file);
44097
+ const packetSize = options.packetSize || 1024 * 1024;
44098
+ const packets = [];
44099
+ for (let offset2 = 0; offset2 < dataUrl.length; offset2 += packetSize) {
44100
+ const packetData2 = dataUrl.slice(offset2, offset2 + packetSize);
44101
+ packets.push({
44102
+ packetId: packets.length,
44103
+ packetData: encodeURIComponent(packetData2),
44104
+ isLastPacket: offset2 + packetSize >= dataUrl.length,
44105
+ filePanaroma: options.filePanaroma || "NO"
44106
+ });
44107
+ }
44108
+ if (!packets.length) throw new TevrocError("Cannot upload an empty file", { code: "empty_file" });
44109
+ let clientId = "";
44110
+ const endpoint = `${client.serviceUrl.replace(/\/$/, "")}/receivePacket`;
44111
+ for (const packet of packets) {
44112
+ const payload = {
44113
+ ...packet,
44114
+ clientId,
44115
+ tableName: options.tableName || "",
44116
+ tableIdx: options.tableIdx ?? "",
44117
+ tableGallery: options.gallery === true || options.gallery === "YES",
44118
+ fileName,
44119
+ fileSize: resolvedFile.size,
44120
+ fileMime: contentType,
44121
+ server: options.server || "test",
44122
+ session: options.session || client.token || ""
44123
+ };
44124
+ let result;
44125
+ const bridge = typeof window !== "undefined" ? window : null;
44126
+ if (bridge && typeof bridge.syncRequest === "function") {
44127
+ const rawResult = bridge.syncRequest(endpoint, "POST", payload);
44128
+ if (!rawResult) throw new TevrocError("Electron upload failed", { code: "electron_upload_failed" });
44129
+ try {
44130
+ result = JSON.parse(rawResult);
44131
+ } catch (error) {
44132
+ throw new TevrocError("Electron upload returned invalid JSON", { code: "electron_upload_failed" });
44133
+ }
44134
+ } else {
44135
+ const response = await client.fetch(endpoint, {
43993
44136
  method: "POST",
43994
- headers,
43995
- body: normalized.data,
43996
- contentType: normalized.contentType,
43997
- bodyIsBase64: normalized.bodyIsBase64,
43998
- filename: options.filename,
43999
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
44000
- };
44001
- const queued = await client.offline.queueOperation("files", "upload", id, payload);
44002
- debugLog2(client, "[tevrocsdk][files] upload queued offline", { path, id, queued });
44003
- return queued;
44137
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
44138
+ body: JSON.stringify(payload)
44139
+ });
44140
+ if (!response.ok) {
44141
+ const text2 = await response.text();
44142
+ throw new TevrocError(text2 || "Electron upload failed", { status: response.status, code: "electron_upload_failed" });
44143
+ }
44144
+ result = await response.json();
44145
+ }
44146
+ clientId = result.clientId || clientId;
44147
+ if (typeof options.onProgress === "function") {
44148
+ options.onProgress({ uploaded: Math.min(offset + packetData.length, dataUrl.length), total: dataUrl.length, progress: Math.round((offset + packetData.length) / dataUrl.length * 100) });
44004
44149
  }
44005
44150
  }
44006
- if (isNative && client.offline && typeof client.offline.syncPendingActions === "function") {
44007
- await client.offline.syncPendingActions();
44151
+ return { success: true, clientId, fileName, fileSize: resolvedFile.size, runtime: "electron" };
44152
+ }
44153
+ async function uploadViaGoogleStorage(client, file, options = {}) {
44154
+ const contentType = options.contentType || "application/octet-stream";
44155
+ const fileName = options.filename || "upload";
44156
+ const body = file instanceof Blob ? file : new Blob([String(file ?? "")], { type: contentType });
44157
+ const serviceUrl = client.serviceUrl.replace(/\/$/, "");
44158
+ const initResponse = await client.fetch(`${serviceUrl}/api/uploads/create`, {
44159
+ method: "POST",
44160
+ headers: {
44161
+ "Content-Type": "application/json",
44162
+ Accept: "application/json"
44163
+ },
44164
+ body: JSON.stringify({
44165
+ filename: fileName,
44166
+ contentType,
44167
+ size: body.size,
44168
+ userId: options.userId || "anon"
44169
+ })
44170
+ });
44171
+ if (!initResponse.ok) {
44172
+ const text2 = await initResponse.text();
44173
+ throw new TevrocError(text2 || "Create upload session failed", { status: initResponse.status, code: "gcs_create_failed" });
44174
+ }
44175
+ const init = await initResponse.json();
44176
+ const uploadUrl = init && init.uploadUrl ? init.uploadUrl : null;
44177
+ const uploadId = init && init.uploadId ? init.uploadId : null;
44178
+ if (!uploadUrl || !uploadId) {
44179
+ throw new TevrocError("Google storage upload session is missing uploadUrl or uploadId", { code: "gcs_invalid_session" });
44180
+ }
44181
+ const chunkSize = options.chunkSize || 10 * 1024 * 1024;
44182
+ for (let offset2 = 0; offset2 < body.size; offset2 += chunkSize) {
44183
+ const end = Math.min(offset2 + chunkSize, body.size) - 1;
44184
+ let uploadResponse;
44185
+ for (let attempt = 1; attempt <= (options.retries || 5); attempt += 1) {
44186
+ try {
44187
+ uploadResponse = await client.fetch(uploadUrl, {
44188
+ method: "PUT",
44189
+ body: body.slice(offset2, end + 1),
44190
+ headers: {
44191
+ "Content-Length": String(end - offset2 + 1),
44192
+ "Content-Range": `bytes ${offset2}-${end}/${body.size}`,
44193
+ "Content-Type": contentType
44194
+ }
44195
+ });
44196
+ if (uploadResponse.ok || uploadResponse.status === 308) break;
44197
+ throw new Error(`HTTP ${uploadResponse.status}`);
44198
+ } catch (error) {
44199
+ if (attempt === (options.retries || 5)) throw new TevrocError(error.message, { code: "gcs_upload_failed" });
44200
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3 * attempt));
44201
+ }
44202
+ }
44203
+ if (!uploadResponse || !uploadResponse.ok && uploadResponse.status !== 308) {
44204
+ throw new TevrocError("Google storage upload failed", { code: "gcs_upload_failed" });
44205
+ }
44206
+ if (typeof options.onProgress === "function") options.onProgress({ uploaded: end + 1, total: body.size, progress: Math.round((end + 1) / body.size * 100) });
44008
44207
  }
44009
- const result = await client.request(path, { method: "POST", body: file, headers, skipSync: true });
44010
- return result;
44208
+ const finalizeResponse = await client.fetch(`${serviceUrl}/api/uploads/${encodeURIComponent(uploadId)}/complete`, {
44209
+ method: "POST",
44210
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
44211
+ body: JSON.stringify({ storageKey: init.storageKey, userId: options.userId || "anon" })
44212
+ });
44213
+ if (!finalizeResponse.ok) {
44214
+ const text2 = await finalizeResponse.text();
44215
+ throw new TevrocError(text2 || "Finalize upload failed", { status: finalizeResponse.status, code: "gcs_finalize_failed" });
44216
+ }
44217
+ const result = await finalizeResponse.json();
44218
+ if (options.tableName && options.tableIdx !== void 0) {
44219
+ await client.fetch(`${serviceUrl}/api/files/gcs-store`, {
44220
+ method: "POST",
44221
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
44222
+ body: JSON.stringify({ storageKey: result.storageKey || init.storageKey, tableName: options.tableName, tableIdx: options.tableIdx, fileName, fileSize: body.size, fileMime: contentType, gallery: options.gallery ? "YES" : "NO", filePanaroma: options.filePanaroma || "NO" })
44223
+ });
44224
+ }
44225
+ return { ...result, runtime: "gcs" };
44226
+ }
44227
+ async function parseAxiosResponse(response, parseAs) {
44228
+ if (parseAs === "response") return response;
44229
+ const headers = response.headers ?? {};
44230
+ const contentType = typeof headers.get === "function" ? headers.get("content-type") ?? "" : String(headers["content-type"] ?? headers["Content-Type"] ?? "");
44231
+ const isJson = contentType.includes("application/json");
44232
+ const data = response.data;
44233
+ if (response.status < 200 || response.status >= 300) {
44234
+ const error = isJson && data?.error ? data.error : {};
44235
+ throw new TevrocError(error.message ?? response.statusText ?? "Request failed", {
44236
+ status: response.status,
44237
+ code: error.code ?? "api_error",
44238
+ details: error.details ?? data,
44239
+ response
44240
+ });
44241
+ }
44242
+ return data;
44011
44243
  }
44012
44244
  async function parseResponse(response, parseAs) {
44013
44245
  if (parseAs === "response") return response;
@@ -44045,13 +44277,13 @@ function normalizeHeaders(headers = {}) {
44045
44277
  return Object.fromEntries(new Headers(headers).entries());
44046
44278
  }
44047
44279
  function debugLog2(client, ...args) {
44048
- if (client?.debug) console.log(...args);
44280
+ debugLog(...args);
44049
44281
  }
44050
44282
  function debugWarn2(client, ...args) {
44051
- if (client?.debug) console.warn(...args);
44283
+ debugWarn(...args);
44052
44284
  }
44053
44285
  function debugError2(client, ...args) {
44054
- if (client?.debug) console.error(...args);
44286
+ debugError(...args);
44055
44287
  }
44056
44288
  function safeLocalStorage() {
44057
44289
  return typeof globalThis !== "undefined" ? globalThis.localStorage : void 0;
@@ -44277,3 +44509,4 @@ jspdf/dist/jspdf.es.min.js:
44277
44509
  * ====================================================================
44278
44510
  *)
44279
44511
  */
44512
+ //# sourceMappingURL=tevroc-sdk.esm.js.map