@meacore/tauri-easy-updater 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -28,47 +28,75 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- UpdateBanner: () => UpdateBanner,
34
- UpdateModal: () => UpdateModal,
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ UpdaterClient: () => UpdaterClient,
34
+ UpdaterError: () => UpdaterError,
35
+ assertSafeRemoteUrl: () => assertSafeRemoteUrl,
36
+ assertValidGitHubIdent: () => assertValidGitHubIdent,
37
+ compareSemver: () => compareSemver,
35
38
  createGitHubProvider: () => createGitHubProvider,
36
39
  createHttpProvider: () => createHttpProvider,
37
40
  createS3Provider: () => createS3Provider,
41
+ createUpdaterClient: () => createUpdaterClient,
42
+ fetchWithTimeout: () => fetchWithTimeout,
38
43
  getCurrentPlatform: () => getCurrentPlatform,
44
+ getPlatformSummary: () => getPlatformSummary,
45
+ inferInstallerFormat: () => inferInstallerFormat,
46
+ isBelowMinVersion: () => isBelowMinVersion,
39
47
  isNewerVersion: () => isNewerVersion,
40
- useUpdateChecker: () => useUpdateChecker
48
+ isSafeRemoteUrl: () => isSafeRemoteUrl,
49
+ isTauriRuntime: () => isTauriRuntime,
50
+ normalizeArch: () => normalizeArch,
51
+ normalizeOs: () => normalizeOs,
52
+ parseSemver: () => parseSemver,
53
+ resolveArtifactsFromPlatform: () => resolveArtifactsFromPlatform,
54
+ selectPlatformFromManifest: () => selectPlatformFromManifest,
55
+ validateManifest: () => validateManifest
41
56
  });
42
- module.exports = __toCommonJS(index_exports);
57
+ module.exports = __toCommonJS(src_exports);
43
58
 
44
- // src/utils/platform.ts
45
- async function getCurrentPlatform() {
46
- if (typeof window === "undefined") {
47
- return "";
59
+ // src/types.ts
60
+ var UpdaterError = class _UpdaterError extends Error {
61
+ constructor(code, message) {
62
+ super(message);
63
+ this.name = "UpdaterError";
64
+ this.code = code;
48
65
  }
49
- try {
50
- const os = await import("@tauri-apps/api/os");
51
- const type = await os.type();
52
- const arch = await os.arch();
53
- const normalizedOs = normalizeOs(type);
54
- const normalizedArch = normalizeArch(arch);
55
- if (!normalizedOs || !normalizedArch) {
56
- return "";
57
- }
58
- return `${normalizedOs}-${normalizedArch}`;
59
- } catch {
60
- return "";
66
+ static fromUnknown(err) {
67
+ if (err instanceof _UpdaterError) {
68
+ return err;
69
+ }
70
+ if (err && typeof err === "object") {
71
+ const obj = err;
72
+ if (typeof obj.code === "string" && typeof obj.message === "string") {
73
+ return new _UpdaterError(obj.code, obj.message);
74
+ }
75
+ if (err instanceof Error) {
76
+ return new _UpdaterError("UNKNOWN_ERROR", err.message);
77
+ }
78
+ }
79
+ if (typeof err === "string") {
80
+ return new _UpdaterError("UNKNOWN_ERROR", err);
81
+ }
82
+ return new _UpdaterError("UNKNOWN_ERROR", "An unexpected updater error occurred");
61
83
  }
84
+ };
85
+
86
+ // src/utils/platform.ts
87
+ function isTauriRuntime() {
88
+ if (typeof window === "undefined") return false;
89
+ return "__TAURI_INTERNALS__" in window || "__TAURI__" in window;
62
90
  }
63
91
  function normalizeOs(os) {
64
- const lower = os.toLowerCase();
92
+ const lower = os.trim().toLowerCase();
65
93
  if (lower.startsWith("win")) return "windows";
66
- if (lower.startsWith("mac")) return "darwin";
94
+ if (lower.startsWith("darwin") || lower.startsWith("mac")) return "darwin";
67
95
  if (lower.startsWith("linux")) return "linux";
68
96
  return "";
69
97
  }
70
98
  function normalizeArch(arch) {
71
- const lower = arch.toLowerCase();
99
+ const lower = arch.trim().toLowerCase();
72
100
  if (lower === "x86_64" || lower === "x64" || lower === "amd64") {
73
101
  return "x86_64";
74
102
  }
@@ -77,703 +105,976 @@ function normalizeArch(arch) {
77
105
  }
78
106
  return "";
79
107
  }
80
-
81
- // src/utils/semver.ts
82
- function parseVersion(input) {
83
- let v = input.trim();
84
- if (v.startsWith("v") || v.startsWith("V")) {
85
- v = v.slice(1);
86
- }
87
- const [core, prerelease] = v.split("-", 2);
88
- const parts = core.split(".");
89
- if (parts.length < 2 || parts.length > 3) {
108
+ function inferInstallerFormat(urlOrFilename) {
109
+ const clean = urlOrFilename.split("?")[0]?.toLowerCase() ?? "";
110
+ if (clean.endsWith(".exe")) return "nsis";
111
+ if (clean.endsWith(".msi")) return "msi";
112
+ if (clean.endsWith(".dmg")) return "dmg";
113
+ if (clean.endsWith(".pkg")) return "pkg";
114
+ if (clean.endsWith(".appimage")) return "appimage";
115
+ if (clean.endsWith(".deb")) return "deb";
116
+ if (clean.endsWith(".rpm")) return "rpm";
117
+ return null;
118
+ }
119
+ async function getPlatformSummary() {
120
+ if (typeof window === "undefined") {
90
121
  return null;
91
122
  }
92
- const [majStr, minStr, patchStr = "0"] = parts;
93
- const major = Number(majStr);
94
- const minor = Number(minStr);
95
- const patch = Number(patchStr);
96
- if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) {
97
- return null;
123
+ if (isTauriRuntime()) {
124
+ try {
125
+ const { invoke } = await import("@tauri-apps/api/core");
126
+ return await invoke("plugin:easy-updater|get_platform");
127
+ } catch {
128
+ }
98
129
  }
130
+ const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
131
+ const platform = typeof navigator !== "undefined" ? navigator.platform : "";
132
+ const combined = `${platform} ${ua}`.toLowerCase();
133
+ let os = "";
134
+ if (combined.includes("win")) os = "windows";
135
+ else if (combined.includes("mac") || combined.includes("darwin")) os = "darwin";
136
+ else if (combined.includes("linux")) os = "linux";
137
+ if (!os) return null;
138
+ const isArm = combined.includes("arm64") || combined.includes("aarch64");
139
+ const arch = isArm ? "aarch64" : "x86_64";
140
+ const supportedFormats = os === "windows" ? ["nsis", "msi"] : os === "darwin" ? ["dmg", "pkg"] : ["appimage", "deb", "rpm"];
99
141
  return {
100
- major,
101
- minor,
102
- patch,
103
- prerelease: prerelease ?? null
142
+ os,
143
+ arch,
144
+ key: `${os}-${arch}`,
145
+ supportedFormats
104
146
  };
105
147
  }
106
- function comparePrerelease(a, b) {
107
- if (a === b) return 0;
108
- if (a === null) return 1;
109
- if (b === null) return -1;
110
- const aParts = a.split(".");
111
- const bParts = b.split(".");
112
- const len = Math.max(aParts.length, bParts.length);
113
- for (let i = 0; i < len; i += 1) {
114
- const ai = aParts[i];
115
- const bi = bParts[i];
116
- if (ai === void 0) return -1;
117
- if (bi === void 0) return 1;
118
- const aNum = Number(ai);
119
- const bNum = Number(bi);
120
- const aIsNum = Number.isFinite(aNum);
121
- const bIsNum = Number.isFinite(bNum);
122
- if (aIsNum && bIsNum) {
123
- if (aNum > bNum) return 1;
124
- if (aNum < bNum) return -1;
125
- } else if (aIsNum && !bIsNum) {
126
- return -1;
127
- } else if (!aIsNum && bIsNum) {
128
- return 1;
129
- } else {
130
- if (ai > bi) return 1;
131
- if (ai < bi) return -1;
132
- }
148
+ async function getCurrentPlatform() {
149
+ const summary = await getPlatformSummary();
150
+ return summary?.key ?? "";
151
+ }
152
+ function selectPlatformFromManifest(manifest, platformKey) {
153
+ if (!platformKey) return null;
154
+ const direct = manifest.platforms[platformKey];
155
+ if (direct) {
156
+ return { key: platformKey, entry: direct };
133
157
  }
134
- return 0;
158
+ if (platformKey.startsWith("darwin-") && manifest.platforms["darwin-universal"]) {
159
+ return { key: "darwin-universal", entry: manifest.platforms["darwin-universal"] };
160
+ }
161
+ return null;
135
162
  }
136
- function isNewerVersion(latest, current) {
137
- const a = parseVersion(latest);
138
- const b = parseVersion(current);
139
- if (!a || !b) return false;
140
- if (a.major !== b.major) return a.major > b.major;
141
- if (a.minor !== b.minor) return a.minor > b.minor;
142
- if (a.patch !== b.patch) return a.patch > b.patch;
143
- return comparePrerelease(a.prerelease, b.prerelease) > 0;
163
+ function resolveArtifactsFromPlatform(entry, preferredFormat) {
164
+ const defaultPrimary = {
165
+ format: entry.format ?? inferInstallerFormat(entry.url),
166
+ url: entry.url,
167
+ sha256: entry.sha256 ?? null,
168
+ size: entry.size ?? null,
169
+ signature: entry.signature ?? null
170
+ };
171
+ const all = (entry.artifacts ?? []).map((a) => ({
172
+ format: a.format,
173
+ url: a.url,
174
+ sha256: a.sha256 ?? null,
175
+ size: a.size ?? null,
176
+ signature: a.signature ?? null
177
+ }));
178
+ if (all.length === 0) {
179
+ all.push(defaultPrimary);
180
+ } else if (!all.some((a) => a.url === defaultPrimary.url)) {
181
+ all.unshift(defaultPrimary);
182
+ }
183
+ const primary = preferredFormat ? all.find((a) => a.format === preferredFormat) ?? defaultPrimary : defaultPrimary;
184
+ return { primary, all };
144
185
  }
145
186
 
146
- // src/providers/github.ts
147
- function createGitHubProvider(config) {
148
- const {
149
- owner,
150
- repo,
151
- manifestAssetName = "update-manifest.json",
152
- fallbackToReleaseApi = true
153
- } = config;
154
- const manifestUrl = `https://github.com/${owner}/${repo}/releases/latest/download/${manifestAssetName}`;
155
- const apiUrl = `https://api.github.com/repos/${owner}/${repo}/releases/latest`;
156
- const provider = {
157
- type: "github",
158
- async fetchManifest() {
159
- try {
160
- const res = await fetch(manifestUrl);
161
- if (res.ok) {
162
- const data = await res.json();
163
- return data;
164
- }
165
- if (!fallbackToReleaseApi || res.status !== 404) {
166
- throw new Error(`GitHub manifest request failed with status ${res.status}`);
167
- }
168
- } catch (err) {
169
- if (!fallbackToReleaseApi) {
170
- throw err instanceof Error ? err : new Error("Failed to fetch GitHub manifest");
171
- }
172
- }
173
- try {
174
- const res = await fetch(apiUrl, {
175
- headers: {
176
- Accept: "application/vnd.github+json"
177
- }
178
- });
179
- if (!res.ok) {
180
- throw new Error(`GitHub releases API failed with status ${res.status}`);
181
- }
182
- const release = await res.json();
183
- const platform = await getCurrentPlatform();
184
- let url = "";
185
- if (platform) {
186
- const asset = selectAssetForPlatform(release.assets, platform);
187
- if (asset) {
188
- url = asset.browser_download_url;
189
- }
190
- }
191
- const manifest = {
192
- version: release.tag_name,
193
- pub_date: release.published_at,
194
- notes: release.body ?? "",
195
- platforms: url ? {
196
- [platform]: {
197
- url
198
- }
199
- } : {}
200
- };
201
- return manifest;
202
- } catch (error) {
203
- throw error instanceof Error ? error : new Error("Failed to fetch GitHub release");
204
- }
205
- }
206
- };
207
- provider.__tauriParams = {
208
- github_owner: owner,
209
- github_repo: repo,
210
- manifest_url: manifestUrl
211
- };
212
- return provider;
187
+ // src/utils/security.ts
188
+ var FORBIDDEN_URL_SYMBOLS = /[\s&|^<>;"'`\\$(){}!]/;
189
+ var GITHUB_IDENT_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
190
+ var SHA256_HEX_RE = /^[a-fA-F0-9]{64}$/;
191
+ function hasForbiddenUrlChars(rawUrl) {
192
+ if (FORBIDDEN_URL_SYMBOLS.test(rawUrl)) return true;
193
+ for (let i = 0; i < rawUrl.length; i += 1) {
194
+ const code = rawUrl.charCodeAt(i);
195
+ if (code <= 31 || code === 127) return true;
196
+ }
197
+ return false;
213
198
  }
214
- function selectAssetForPlatform(assets, platform) {
215
- if (!platform) return void 0;
216
- const lowerPlatform = platform.toLowerCase();
217
- return assets.find((asset) => {
218
- const name = asset.name.toLowerCase();
219
- if (lowerPlatform === "windows-x86_64") {
220
- return name.endsWith(".exe") || name.endsWith(".msi");
221
- }
222
- if (lowerPlatform === "darwin-x86_64") {
223
- return name.endsWith(".dmg") && !name.includes("arm64") && !name.includes("aarch64");
199
+ function isSafeRemoteUrl(rawUrl, allowInsecureHttp = false) {
200
+ if (typeof rawUrl !== "string" || rawUrl.length === 0) return false;
201
+ if (rawUrl.startsWith("-")) return false;
202
+ if (hasForbiddenUrlChars(rawUrl)) return false;
203
+ try {
204
+ const parsed = new URL(rawUrl);
205
+ const schemeAllowed = parsed.protocol === "https:" || allowInsecureHttp && parsed.protocol === "http:";
206
+ if (!schemeAllowed) return false;
207
+ if (parsed.username || parsed.password) return false;
208
+ if (!parsed.hostname) return false;
209
+ return true;
210
+ } catch {
211
+ return false;
212
+ }
213
+ }
214
+ function assertSafeRemoteUrl(rawUrl, allowInsecureHttp = false) {
215
+ if (!isSafeRemoteUrl(rawUrl, allowInsecureHttp)) {
216
+ throw new UpdaterError(
217
+ rawUrl.startsWith("http://") ? "INSECURE_SCHEME" : "INVALID_URL",
218
+ `Blocked unsafe or non-HTTPS URL: ${rawUrl.slice(0, 120)}`
219
+ );
220
+ }
221
+ return rawUrl;
222
+ }
223
+ function assertValidGitHubIdent(value, fieldName) {
224
+ if (typeof value !== "string" || !GITHUB_IDENT_RE.test(value) || value === "." || value === ".." || value.includes("..")) {
225
+ throw new UpdaterError(
226
+ "INVALID_INPUT",
227
+ `Invalid GitHub ${fieldName}: must match [A-Za-z0-9][A-Za-z0-9_.-]* without '..'`
228
+ );
229
+ }
230
+ }
231
+ function validateManifest(data, allowInsecureHttp = false) {
232
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
233
+ throw new UpdaterError("INVALID_MANIFEST", "Manifest must be a JSON object");
234
+ }
235
+ const obj = data;
236
+ if (typeof obj.version !== "string" || !obj.version.trim()) {
237
+ throw new UpdaterError("INVALID_MANIFEST", 'Manifest is missing a valid "version" string');
238
+ }
239
+ if (!obj.platforms || typeof obj.platforms !== "object" || Array.isArray(obj.platforms)) {
240
+ throw new UpdaterError("INVALID_MANIFEST", 'Manifest is missing a valid "platforms" map');
241
+ }
242
+ const platforms = obj.platforms;
243
+ for (const [key, entry] of Object.entries(platforms)) {
244
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
245
+ throw new UpdaterError("INVALID_MANIFEST", `Platform "${key}" must be an object`);
224
246
  }
225
- if (lowerPlatform === "darwin-aarch64") {
226
- return name.endsWith(".dmg") && (name.includes("arm64") || name.includes("aarch64"));
247
+ const p = entry;
248
+ if (typeof p.url !== "string" || !isSafeRemoteUrl(p.url, allowInsecureHttp)) {
249
+ throw new UpdaterError(
250
+ "INVALID_MANIFEST",
251
+ `Platform "${key}" has an invalid or non-HTTPS download URL`
252
+ );
227
253
  }
228
- if (lowerPlatform === "linux-x86_64") {
229
- return name.endsWith(".appimage") || name.endsWith(".AppImage") || name.endsWith(".deb") || name.endsWith(".rpm");
254
+ if (p.sha256 !== void 0 && (typeof p.sha256 !== "string" || !SHA256_HEX_RE.test(p.sha256))) {
255
+ throw new UpdaterError(
256
+ "INVALID_MANIFEST",
257
+ `Platform "${key}" has an invalid sha256 digest`
258
+ );
230
259
  }
231
- return false;
232
- });
260
+ }
261
+ return data;
233
262
  }
234
-
235
- // src/providers/http.ts
236
- function createHttpProvider(config) {
237
- const { manifestUrl, headers } = config;
238
- const provider = {
239
- type: "http",
240
- async fetchManifest() {
241
- const init = {
242
- method: "GET",
243
- headers
244
- };
245
- try {
246
- const res = await fetch(manifestUrl, init);
247
- if (!res.ok) {
248
- throw new Error(`HTTP ${res.status}`);
249
- }
250
- const data = await res.json();
251
- return data;
252
- } catch (error) {
253
- throw error instanceof Error ? error : new Error("Failed to fetch update manifest");
254
- }
263
+ async function fetchWithTimeout(url, init = {}, timeoutMs = 15e3) {
264
+ const controller = new AbortController();
265
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
266
+ try {
267
+ return await fetch(url, {
268
+ ...init,
269
+ signal: controller.signal
270
+ });
271
+ } catch (err) {
272
+ if (err instanceof Error && err.name === "AbortError") {
273
+ throw new UpdaterError("TIMEOUT", `Request timed out after ${timeoutMs}ms`);
255
274
  }
256
- };
257
- provider.__tauriParams = { manifest_url: manifestUrl };
258
- return provider;
275
+ throw new UpdaterError(
276
+ "NETWORK_ERROR",
277
+ err instanceof Error ? err.message : "Network request failed"
278
+ );
279
+ } finally {
280
+ clearTimeout(timer);
281
+ }
259
282
  }
260
283
 
261
- // src/providers/s3.ts
262
- function createS3Provider(config) {
263
- const { bucketUrl, manifestPath = "latest/update-manifest.json" } = config;
264
- const manifestUrl = `${bucketUrl.replace(/\/+$/, "")}/${manifestPath.replace(/^\/+/, "")}`;
265
- const httpProvider = createHttpProvider({ manifestUrl });
266
- const provider = {
267
- type: "s3",
268
- async fetchManifest() {
269
- return httpProvider.fetchManifest();
284
+ // src/utils/semver.ts
285
+ var STRICT_SEMVER_RE = /^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
286
+ var NUMERIC_IDENT_RE = /^(0|[1-9]\d*)$/;
287
+ function parseSemver(input) {
288
+ if (typeof input !== "string") return null;
289
+ const trimmed = input.trim();
290
+ const match = STRICT_SEMVER_RE.exec(trimmed);
291
+ if (!match) return null;
292
+ const major = Number(match[1]);
293
+ const minor = Number(match[2]);
294
+ const patch = Number(match[3]);
295
+ if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
296
+ return null;
297
+ }
298
+ const prerelease = match[4] ? match[4].split(".") : [];
299
+ const build = match[5] ?? null;
300
+ return { major, minor, patch, prerelease, build };
301
+ }
302
+ function comparePrerelease(a, b) {
303
+ const aEmpty = a.length === 0;
304
+ const bEmpty = b.length === 0;
305
+ if (aEmpty && bEmpty) return 0;
306
+ if (aEmpty) return 1;
307
+ if (bEmpty) return -1;
308
+ const len = Math.max(a.length, b.length);
309
+ for (let i = 0; i < len; i += 1) {
310
+ const ai = a[i];
311
+ const bi = b[i];
312
+ if (ai === void 0) return -1;
313
+ if (bi === void 0) return 1;
314
+ if (ai === bi) continue;
315
+ const aNum = NUMERIC_IDENT_RE.test(ai);
316
+ const bNum = NUMERIC_IDENT_RE.test(bi);
317
+ if (aNum && bNum) {
318
+ const av = BigInt(ai);
319
+ const bv = BigInt(bi);
320
+ if (av > bv) return 1;
321
+ if (av < bv) return -1;
322
+ } else if (aNum && !bNum) {
323
+ return -1;
324
+ } else if (!aNum && bNum) {
325
+ return 1;
326
+ } else {
327
+ return ai > bi ? 1 : -1;
270
328
  }
271
- };
272
- provider.__tauriParams = { manifest_url: manifestUrl };
273
- return provider;
329
+ }
330
+ return 0;
331
+ }
332
+ function compareSemver(a, b) {
333
+ const pa = parseSemver(a);
334
+ const pb = parseSemver(b);
335
+ if (!pa || !pb) return null;
336
+ if (pa.major !== pb.major) return pa.major > pb.major ? 1 : -1;
337
+ if (pa.minor !== pb.minor) return pa.minor > pb.minor ? 1 : -1;
338
+ if (pa.patch !== pb.patch) return pa.patch > pb.patch ? 1 : -1;
339
+ const pre = comparePrerelease(pa.prerelease, pb.prerelease);
340
+ if (pre > 0) return 1;
341
+ if (pre < 0) return -1;
342
+ return 0;
343
+ }
344
+ function isNewerVersion(latest, current) {
345
+ return compareSemver(latest, current) === 1;
346
+ }
347
+ function isBelowMinVersion(current, minVersion) {
348
+ return compareSemver(current, minVersion) === -1;
274
349
  }
275
350
 
276
- // src/hooks/useUpdateChecker.ts
277
- var import_react = require("react");
351
+ // src/client.ts
278
352
  var SESSION_DISMISS_KEY = "tauri-easy-updater:dismissed-version";
279
- function getDismissedVersion() {
353
+ var PROGRESS_EVENT_NAME = "easy-updater://download-progress";
354
+ function defaultStorage() {
280
355
  if (typeof window === "undefined") return null;
281
356
  try {
282
- return window.sessionStorage.getItem(SESSION_DISMISS_KEY);
357
+ return window.sessionStorage;
283
358
  } catch {
284
359
  return null;
285
360
  }
286
361
  }
287
- function setDismissedVersion(version) {
288
- if (typeof window === "undefined") return;
289
- try {
290
- window.sessionStorage.setItem(SESSION_DISMISS_KEY, version);
291
- } catch {
362
+ var UpdaterClient = class {
363
+ constructor(config = {}) {
364
+ this.listeners = /* @__PURE__ */ new Set();
365
+ this.state = {
366
+ status: "idle",
367
+ updateInfo: null,
368
+ progress: null,
369
+ downloadResult: null,
370
+ error: null,
371
+ isDismissed: false,
372
+ lastCheckedAt: null
373
+ };
374
+ this.inFlightCheck = null;
375
+ this.activeDownloadId = null;
376
+ this.pollTimer = null;
377
+ this.unlistenProgress = null;
378
+ this.disposed = false;
379
+ this.config = config;
380
+ this.storage = config.storage ?? defaultStorage();
292
381
  }
293
- }
294
- function buildParamsFromProvider(provider, currentVersion) {
295
- const anyProvider = provider;
296
- const base = {
297
- current_version: currentVersion,
298
- manifest_url: ""
299
- };
300
- if (!anyProvider.__tauriParams) {
301
- return null;
382
+ /** Returns the current immutable state snapshot. */
383
+ getState() {
384
+ return this.state;
302
385
  }
303
- const { manifest_url, github_owner, github_repo } = anyProvider.__tauriParams;
304
- if (github_owner && github_repo) {
305
- return {
306
- ...base,
307
- manifest_url: manifest_url ?? "",
308
- github_owner,
309
- github_repo
386
+ /** Subscribes to state transitions. Returns an unsubscribe function. */
387
+ subscribe(listener) {
388
+ this.listeners.add(listener);
389
+ return () => {
390
+ this.listeners.delete(listener);
310
391
  };
311
392
  }
312
- if (manifest_url) {
313
- return {
314
- ...base,
315
- manifest_url,
316
- github_owner: null,
317
- github_repo: null
318
- };
393
+ /** Starts periodic update checks (`intervalMs > 0`). */
394
+ startPolling(intervalMs) {
395
+ this.stopPolling();
396
+ if (intervalMs <= 0 || this.disposed) return;
397
+ this.pollTimer = setInterval(() => {
398
+ void this.check();
399
+ }, intervalMs);
319
400
  }
320
- return null;
321
- }
322
- function useUpdateChecker(config) {
323
- const {
324
- currentVersion,
325
- provider,
326
- checkOnStartup = true,
327
- checkIntervalMs = 0,
328
- silent = false
329
- } = config;
330
- const [updateInfo, setUpdateInfo] = (0, import_react.useState)(null);
331
- const [isChecking, setIsChecking] = (0, import_react.useState)(false);
332
- const [error, setError] = (0, import_react.useState)(null);
333
- const [isDismissed, setIsDismissed] = (0, import_react.useState)(false);
334
- const intervalRef = (0, import_react.useRef)(null);
335
- const mountedRef = (0, import_react.useRef)(true);
336
- (0, import_react.useEffect)(() => {
337
- mountedRef.current = true;
338
- const dismissed = getDismissedVersion();
339
- if (dismissed) {
340
- setIsDismissed(true);
401
+ /** Stops periodic update checks. */
402
+ stopPolling() {
403
+ if (this.pollTimer !== null) {
404
+ clearInterval(this.pollTimer);
405
+ this.pollTimer = null;
341
406
  }
342
- return () => {
343
- mountedRef.current = false;
344
- if (intervalRef.current !== null && typeof window !== "undefined") {
345
- window.clearInterval(intervalRef.current);
407
+ }
408
+ /** Releases timers and Tauri event listeners. */
409
+ dispose() {
410
+ this.disposed = true;
411
+ this.stopPolling();
412
+ this.detachProgressListener();
413
+ this.listeners.clear();
414
+ }
415
+ /**
416
+ * Checks for an available update. Concurrent calls share the same in-flight promise.
417
+ */
418
+ async check() {
419
+ if (this.disposed) return null;
420
+ if (this.inFlightCheck) {
421
+ return this.inFlightCheck;
422
+ }
423
+ const promise = this.performCheck().finally(() => {
424
+ this.inFlightCheck = null;
425
+ });
426
+ this.inFlightCheck = promise;
427
+ return promise;
428
+ }
429
+ async performCheck() {
430
+ this.setState({
431
+ status: "checking",
432
+ error: null
433
+ });
434
+ try {
435
+ const info = await this.fetchUpdateInfo();
436
+ if (this.disposed) return null;
437
+ const dismissedVersion = this.readDismissedVersion();
438
+ const isDismissed = !info.mandatory && Boolean(dismissedVersion) && dismissedVersion === info.latestVersion;
439
+ this.setState({
440
+ status: info.hasUpdate ? "available" : "up-to-date",
441
+ updateInfo: info,
442
+ isDismissed,
443
+ error: null,
444
+ lastCheckedAt: Date.now()
445
+ });
446
+ return info;
447
+ } catch (rawErr) {
448
+ if (this.disposed) return null;
449
+ const err = UpdaterError.fromUnknown(rawErr);
450
+ if (this.config.silent) {
451
+ this.setState({
452
+ status: this.state.updateInfo?.hasUpdate ? "available" : "idle",
453
+ error: null
454
+ });
455
+ } else {
456
+ this.setState({
457
+ status: "error",
458
+ error: err
459
+ });
346
460
  }
347
- };
348
- }, []);
349
- const canUseTauri = typeof window !== "undefined";
350
- const checkNow = (0, import_react.useCallback)(async () => {
351
- if (!canUseTauri) {
352
- return;
461
+ return null;
353
462
  }
354
- const params = buildParamsFromProvider(provider, currentVersion);
355
- if (!params) {
356
- try {
357
- setIsChecking(true);
358
- setError(null);
359
- const manifest = await provider.fetchManifest();
360
- const platformInfo = Object.values(manifest.platforms)[0];
361
- if (!platformInfo) {
362
- if (!silent) {
363
- setError(new Error("No platform information in manifest"));
364
- }
365
- setUpdateInfo(null);
366
- return;
367
- }
368
- const info = {
369
- hasUpdate: true,
370
- currentVersion,
371
- latestVersion: manifest.version,
372
- downloadUrl: platformInfo.url,
373
- releaseNotes: manifest.notes,
374
- pubDate: manifest.pub_date
375
- };
376
- if (!mountedRef.current) return;
377
- setUpdateInfo(info);
378
- } catch (e) {
379
- if (!mountedRef.current) return;
380
- if (!silent) {
381
- setError(e instanceof Error ? e : new Error("Failed to check for updates"));
382
- }
383
- } finally {
384
- if (mountedRef.current) {
385
- setIsChecking(false);
386
- }
463
+ }
464
+ async fetchUpdateInfo() {
465
+ const provider = this.config.provider;
466
+ const useTauriPlugin = isTauriRuntime() && (!provider || Boolean(provider.tauriParams));
467
+ if (useTauriPlugin) {
468
+ const { invoke } = await import("@tauri-apps/api/core");
469
+ const params = {
470
+ ...provider?.tauriParams ?? {}
471
+ };
472
+ if (this.config.currentVersion) {
473
+ params.currentVersion = this.config.currentVersion;
387
474
  }
388
- return;
475
+ if (this.config.channel) {
476
+ params.channel = this.config.channel;
477
+ }
478
+ if (this.config.preferredFormat) {
479
+ params.preferredFormat = this.config.preferredFormat;
480
+ }
481
+ return await invoke("plugin:easy-updater|check_update", { params });
482
+ }
483
+ if (!provider) {
484
+ throw new UpdaterError(
485
+ "INVALID_INPUT",
486
+ "A provider is required when running outside a Tauri v2 runtime"
487
+ );
389
488
  }
489
+ if (!this.config.currentVersion) {
490
+ throw new UpdaterError(
491
+ "INVALID_INPUT",
492
+ "currentVersion is required when using pure JS fallback outside Tauri"
493
+ );
494
+ }
495
+ const manifest = await provider.fetchManifest();
496
+ const currentVersion = this.config.currentVersion;
497
+ const cmp = compareSemver(manifest.version, currentVersion);
498
+ if (cmp === null) {
499
+ throw new UpdaterError(
500
+ "INVALID_VERSION",
501
+ `Unable to compare versions "${manifest.version}" and "${currentVersion}"`
502
+ );
503
+ }
504
+ if (cmp < 0) {
505
+ throw new UpdaterError(
506
+ "DOWNGRADE_BLOCKED",
507
+ `Downgrade blocked: target ${manifest.version} is older than ${currentVersion}`
508
+ );
509
+ }
510
+ const hasUpdate = isNewerVersion(manifest.version, currentVersion);
511
+ const belowMin = manifest.min_version ? isBelowMinVersion(currentVersion, manifest.min_version) : false;
512
+ const mandatory = hasUpdate && (Boolean(manifest.mandatory) || belowMin);
513
+ const platformKey = await getCurrentPlatform();
514
+ const matched = selectPlatformFromManifest(manifest, platformKey);
515
+ if (!matched) {
516
+ if (hasUpdate) {
517
+ throw new UpdaterError(
518
+ "PLATFORM_NOT_FOUND",
519
+ `No update artifact available for platform "${platformKey || "unknown"}"`
520
+ );
521
+ }
522
+ return {
523
+ hasUpdate: false,
524
+ currentVersion,
525
+ latestVersion: manifest.version,
526
+ channel: manifest.channel ?? this.config.channel ?? "stable",
527
+ mandatory: false,
528
+ minVersion: manifest.min_version ?? null,
529
+ platform: platformKey,
530
+ downloadUrl: null,
531
+ sha256: null,
532
+ size: null,
533
+ format: null,
534
+ signature: null,
535
+ verifiedManifest: false,
536
+ artifacts: [],
537
+ releaseNotes: manifest.notes ?? "",
538
+ pubDate: manifest.pub_date ?? ""
539
+ };
540
+ }
541
+ const { primary, all } = resolveArtifactsFromPlatform(
542
+ matched.entry,
543
+ this.config.preferredFormat
544
+ );
545
+ assertSafeRemoteUrl(primary.url, Boolean(this.config.allowInsecureHttp));
546
+ return {
547
+ hasUpdate,
548
+ currentVersion,
549
+ latestVersion: manifest.version,
550
+ channel: manifest.channel ?? this.config.channel ?? "stable",
551
+ mandatory,
552
+ minVersion: manifest.min_version ?? null,
553
+ platform: matched.key,
554
+ downloadUrl: primary.url,
555
+ sha256: primary.sha256,
556
+ size: primary.size,
557
+ format: primary.format,
558
+ signature: primary.signature,
559
+ verifiedManifest: false,
560
+ artifacts: all,
561
+ releaseNotes: manifest.notes ?? "",
562
+ pubDate: manifest.pub_date ?? ""
563
+ };
564
+ }
565
+ /**
566
+ * Downloads and verifies the currently available update inside Tauri (streaming + SHA-256/Ed25519).
567
+ */
568
+ async download(overrideInfo) {
569
+ const info = overrideInfo ?? this.state.updateInfo;
570
+ if (!info?.downloadUrl) {
571
+ throw new UpdaterError("INVALID_INPUT", "No downloadable update is currently available");
572
+ }
573
+ if (!isTauriRuntime()) {
574
+ throw new UpdaterError(
575
+ "INVALID_INPUT",
576
+ "In-app verified downloads require the Tauri v2 runtime; use openDownloadUrl() on the web"
577
+ );
578
+ }
579
+ const downloadId = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `dl-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
580
+ this.activeDownloadId = downloadId;
581
+ this.setState({
582
+ status: "downloading",
583
+ error: null,
584
+ downloadResult: null,
585
+ progress: {
586
+ downloadId,
587
+ downloadedBytes: 0,
588
+ totalBytes: info.size,
589
+ percent: info.size ? 0 : null,
590
+ stage: "started"
591
+ }
592
+ });
593
+ await this.attachProgressListener(downloadId);
390
594
  try {
391
- setIsChecking(true);
392
- setError(null);
393
- const { invoke } = await import("@tauri-apps/api/tauri");
394
- const result = await invoke("plugin:easy-updater|check_update", {
395
- params
595
+ const { invoke } = await import("@tauri-apps/api/core");
596
+ const result = await invoke("plugin:easy-updater|download_update", {
597
+ params: {
598
+ url: info.downloadUrl,
599
+ version: info.latestVersion,
600
+ platform: info.platform,
601
+ sha256: info.sha256,
602
+ expectedSize: info.size,
603
+ signature: info.signature,
604
+ format: info.format,
605
+ downloadId
606
+ }
396
607
  });
397
- if (!mountedRef.current) return;
398
- const dismissed = getDismissedVersion();
399
- if (dismissed && dismissed === result.latestVersion) {
400
- setIsDismissed(true);
401
- setUpdateInfo(result);
402
- return;
608
+ if (!this.disposed) {
609
+ this.setState({
610
+ status: "ready",
611
+ downloadResult: result,
612
+ progress: {
613
+ downloadId: result.downloadId,
614
+ downloadedBytes: result.size,
615
+ totalBytes: result.size,
616
+ percent: 100,
617
+ stage: "completed"
618
+ },
619
+ error: null
620
+ });
403
621
  }
404
- setUpdateInfo(result);
405
- } catch (e) {
406
- if (!mountedRef.current) return;
407
- if (!silent) {
408
- setError(e instanceof Error ? e : new Error("Failed to check for updates"));
622
+ return result;
623
+ } catch (rawErr) {
624
+ const err = UpdaterError.fromUnknown(rawErr);
625
+ if (!this.disposed) {
626
+ if (err.code === "DOWNLOAD_CANCELLED") {
627
+ this.setState({
628
+ status: "available",
629
+ progress: null,
630
+ error: null
631
+ });
632
+ } else {
633
+ this.setState({
634
+ status: "error",
635
+ error: err
636
+ });
637
+ }
409
638
  }
639
+ throw err;
410
640
  } finally {
411
- if (mountedRef.current) {
412
- setIsChecking(false);
641
+ this.activeDownloadId = null;
642
+ this.detachProgressListener();
643
+ }
644
+ }
645
+ /**
646
+ * Cancels an active in-app download cleanly.
647
+ */
648
+ async cancelDownload() {
649
+ if (!this.activeDownloadId || !isTauriRuntime()) {
650
+ return false;
651
+ }
652
+ const { invoke } = await import("@tauri-apps/api/core");
653
+ return await invoke("plugin:easy-updater|cancel_download", {
654
+ downloadId: this.activeDownloadId
655
+ });
656
+ }
657
+ /**
658
+ * Launches the previously downloaded & verified installer (anti-TOCTOU re-verified in Rust).
659
+ */
660
+ async install(downloadId) {
661
+ const id = downloadId ?? this.state.downloadResult?.downloadId;
662
+ if (!id) {
663
+ throw new UpdaterError("DOWNLOAD_NOT_FOUND", "No verified download is ready to install");
664
+ }
665
+ if (!isTauriRuntime()) {
666
+ throw new UpdaterError("INSTALL_FAILED", "Native installation requires Tauri v2 runtime");
667
+ }
668
+ this.setState({ status: "installing", error: null });
669
+ try {
670
+ const { invoke } = await import("@tauri-apps/api/core");
671
+ await invoke("plugin:easy-updater|install_update", { downloadId: id });
672
+ if (!this.disposed) {
673
+ this.setState({ status: "ready" });
674
+ }
675
+ } catch (rawErr) {
676
+ const err = UpdaterError.fromUnknown(rawErr);
677
+ if (!this.disposed) {
678
+ this.setState({ status: "error", error: err });
413
679
  }
680
+ throw err;
414
681
  }
415
- }, [canUseTauri, provider, currentVersion, silent]);
416
- (0, import_react.useEffect)(() => {
417
- if (!checkOnStartup) {
682
+ }
683
+ /**
684
+ * Opens the verified HTTPS update URL in the user's default browser (lightweight mode).
685
+ */
686
+ async openDownloadUrl(urlOverride) {
687
+ const url = urlOverride ?? this.state.updateInfo?.downloadUrl;
688
+ if (!url) {
689
+ throw new UpdaterError("INVALID_URL", "No download URL available");
690
+ }
691
+ assertSafeRemoteUrl(url, Boolean(this.config.allowInsecureHttp));
692
+ if (isTauriRuntime()) {
693
+ const { invoke } = await import("@tauri-apps/api/core");
694
+ await invoke("plugin:easy-updater|open_url", { url });
418
695
  return;
419
696
  }
420
- void checkNow();
421
- }, [checkOnStartup, checkNow]);
422
- (0, import_react.useEffect)(() => {
423
- if (checkIntervalMs <= 0 || typeof window === "undefined") {
697
+ if (typeof window !== "undefined" && isSafeRemoteUrl(url, Boolean(this.config.allowInsecureHttp))) {
698
+ window.open(url, "_blank", "noopener,noreferrer");
699
+ }
700
+ }
701
+ /**
702
+ * Applies the available update according to the configured `mode` (`hybrid`, `download`, or `browser`).
703
+ */
704
+ async applyUpdate(modeOverride) {
705
+ const mode = modeOverride ?? this.config.mode ?? "hybrid";
706
+ const info = this.state.updateInfo;
707
+ if (!info?.downloadUrl) {
708
+ throw new UpdaterError("INVALID_INPUT", "No update available to apply");
709
+ }
710
+ if (mode === "browser") {
711
+ await this.openDownloadUrl(info.downloadUrl);
424
712
  return;
425
713
  }
426
- const id = window.setInterval(() => {
427
- void checkNow();
428
- }, checkIntervalMs);
429
- intervalRef.current = id;
430
- return () => {
431
- window.clearInterval(id);
432
- };
433
- }, [checkIntervalMs, checkNow]);
434
- const dismiss = (0, import_react.useCallback)(() => {
435
- if (updateInfo) {
436
- setDismissedVersion(updateInfo.latestVersion);
437
- }
438
- setIsDismissed(true);
439
- }, [updateInfo]);
440
- const value = (0, import_react.useMemo)(
441
- () => ({
442
- updateInfo,
443
- isChecking,
444
- error,
445
- checkNow,
446
- dismiss,
447
- isDismissed
448
- }),
449
- [updateInfo, isChecking, error, checkNow, dismiss, isDismissed]
450
- );
451
- return value;
452
- }
453
-
454
- // src/components/UpdateBanner.tsx
455
- var import_jsx_runtime = require("react/jsx-runtime");
456
- function resolveTheme(theme = "auto") {
457
- if (theme === "auto" && typeof window !== "undefined" && "matchMedia" in window) {
714
+ if (mode === "download") {
715
+ const result = this.state.downloadResult ?? await this.download(info);
716
+ await this.install(result.downloadId);
717
+ return;
718
+ }
719
+ if (isTauriRuntime() && info.sha256) {
720
+ const result = this.state.downloadResult ?? await this.download(info);
721
+ await this.install(result.downloadId);
722
+ } else {
723
+ await this.openDownloadUrl(info.downloadUrl);
724
+ }
725
+ }
726
+ /**
727
+ * Dismisses the currently available update for this session.
728
+ * Ignored if the update is `mandatory`.
729
+ */
730
+ dismiss() {
731
+ const info = this.state.updateInfo;
732
+ if (info?.mandatory) {
733
+ return;
734
+ }
735
+ if (info) {
736
+ this.writeDismissedVersion(info.latestVersion);
737
+ }
738
+ this.setState({ isDismissed: true });
739
+ }
740
+ async attachProgressListener(downloadId) {
741
+ this.detachProgressListener();
742
+ if (!isTauriRuntime()) return;
458
743
  try {
459
- if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
460
- return "dark";
744
+ const { listen } = await import("@tauri-apps/api/event");
745
+ const unlisten = await listen(PROGRESS_EVENT_NAME, (event) => {
746
+ if (this.disposed) return;
747
+ const payload = event.payload;
748
+ if (!payload || payload.downloadId !== downloadId) return;
749
+ const nextStatus = payload.stage === "verifying" ? "verifying" : payload.stage === "completed" ? "ready" : "downloading";
750
+ this.setState({
751
+ status: nextStatus,
752
+ progress: payload
753
+ });
754
+ });
755
+ this.unlistenProgress = unlisten;
756
+ } catch {
757
+ }
758
+ }
759
+ detachProgressListener() {
760
+ if (this.unlistenProgress) {
761
+ try {
762
+ this.unlistenProgress();
763
+ } catch {
461
764
  }
765
+ this.unlistenProgress = null;
766
+ }
767
+ }
768
+ readDismissedVersion() {
769
+ try {
770
+ return this.storage?.getItem(SESSION_DISMISS_KEY) ?? null;
462
771
  } catch {
772
+ return null;
463
773
  }
464
774
  }
465
- return theme === "auto" ? "light" : theme;
466
- }
467
- async function openUrl(url) {
468
- if (typeof window === "undefined") return;
469
- try {
470
- const { invoke } = await import("@tauri-apps/api/tauri");
471
- await invoke("plugin:easy-updater|open_url", { url });
472
- } catch {
775
+ writeDismissedVersion(version) {
473
776
  try {
474
- window.open(url, "_blank", "noopener,noreferrer");
777
+ this.storage?.setItem(SESSION_DISMISS_KEY, version);
475
778
  } catch {
476
779
  }
477
780
  }
781
+ setState(partial) {
782
+ this.state = {
783
+ ...this.state,
784
+ ...partial
785
+ };
786
+ for (const listener of this.listeners) {
787
+ listener(this.state);
788
+ }
789
+ }
790
+ };
791
+ function createUpdaterClient(config = {}) {
792
+ return new UpdaterClient(config);
478
793
  }
479
- function UpdateBanner(props) {
480
- const { updateInfo, onDismiss, position = "bottom", theme = "auto", className } = props;
481
- const resolvedTheme = resolveTheme(theme);
482
- const base = {
483
- position: "fixed",
484
- left: 0,
485
- right: 0,
486
- display: "flex",
487
- alignItems: "center",
488
- justifyContent: "space-between",
489
- padding: "0.75rem 1rem",
490
- fontSize: "0.875rem",
491
- zIndex: 50
492
- };
493
- const positionStyle = position === "top" ? {
494
- top: 0
495
- } : {
496
- bottom: 0
497
- };
498
- const themeStyle = resolvedTheme === "dark" ? {
499
- backgroundColor: "rgba(15,23,42,0.95)",
500
- color: "white",
501
- borderTop: position === "bottom" ? "1px solid rgba(148,163,184,0.5)" : void 0,
502
- borderBottom: position === "top" ? "1px solid rgba(148,163,184,0.5)" : void 0
503
- } : {
504
- backgroundColor: "rgba(248,250,252,0.98)",
505
- color: "#020617",
506
- borderTop: position === "bottom" ? "1px solid #e2e8f0" : void 0,
507
- borderBottom: position === "top" ? "1px solid #e2e8f0" : void 0
508
- };
509
- const buttonStyle = resolvedTheme === "dark" ? {
510
- backgroundColor: "#22c55e",
511
- color: "#022c22"
512
- } : {
513
- backgroundColor: "#16a34a",
514
- color: "white"
515
- };
516
- const secondaryButtonStyle = resolvedTheme === "dark" ? {
517
- color: "#e5e7eb"
518
- } : {
519
- color: "#4b5563"
520
- };
521
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...base, ...positionStyle, ...themeStyle }, className, children: [
522
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { display: "flex", flexDirection: "column", gap: "0.125rem" }, children: [
523
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { style: { fontWeight: 500 }, children: [
524
- "Nueva versi\xF3n ",
525
- updateInfo.latestVersion,
526
- " disponible"
527
- ] }),
528
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { style: { opacity: 0.8 }, children: [
529
- "Est\xE1s usando la versi\xF3n ",
530
- updateInfo.currentVersion,
531
- ". Descarga la \xFAltima actualizaci\xF3n."
532
- ] })
533
- ] }),
534
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: "0.5rem" }, children: [
535
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
536
- "button",
537
- {
538
- type: "button",
539
- style: {
540
- ...buttonStyle,
541
- borderRadius: "9999px",
542
- padding: "0.4rem 0.9rem",
543
- border: "none",
544
- cursor: "pointer",
545
- fontSize: "0.875rem",
546
- fontWeight: 500
547
- },
548
- onClick: () => {
549
- void openUrl(updateInfo.downloadUrl);
550
- },
551
- children: "Actualizar ahora"
794
+
795
+ // src/providers/github.ts
796
+ function createGitHubProvider(config) {
797
+ const {
798
+ owner,
799
+ repo,
800
+ manifestAssetName = "update-manifest.json",
801
+ fallbackToReleaseApi = true,
802
+ channel = "stable",
803
+ preferredFormat,
804
+ timeoutMs = 15e3
805
+ } = config;
806
+ assertValidGitHubIdent(owner, "owner");
807
+ assertValidGitHubIdent(repo, "repo");
808
+ if (!manifestAssetName || manifestAssetName.includes("/") || manifestAssetName.includes("\\") || manifestAssetName.includes("..")) {
809
+ throw new UpdaterError("INVALID_INPUT", `Unsafe manifestAssetName: "${manifestAssetName}"`);
810
+ }
811
+ const manifestUrl = `https://github.com/${owner}/${repo}/releases/latest/download/${manifestAssetName}`;
812
+ const isPrereleaseChannel = channel !== "stable";
813
+ const fingerprint = JSON.stringify([
814
+ "github",
815
+ owner,
816
+ repo,
817
+ manifestAssetName,
818
+ fallbackToReleaseApi,
819
+ channel,
820
+ preferredFormat ?? null
821
+ ]);
822
+ return {
823
+ type: "github",
824
+ fingerprint,
825
+ tauriParams: {
826
+ githubOwner: owner,
827
+ githubRepo: repo,
828
+ manifestAssetName,
829
+ fallbackToReleaseApi,
830
+ channel,
831
+ preferredFormat
832
+ },
833
+ async fetchManifest() {
834
+ if (!isPrereleaseChannel) {
835
+ try {
836
+ const res2 = await fetchWithTimeout(manifestUrl, { method: "GET" }, timeoutMs);
837
+ if (res2.ok) {
838
+ const json = await res2.json();
839
+ return validateManifest(json);
840
+ }
841
+ if (!fallbackToReleaseApi || res2.status !== 404) {
842
+ throw new UpdaterError(
843
+ "NETWORK_ERROR",
844
+ `GitHub manifest request failed with HTTP ${res2.status}`
845
+ );
846
+ }
847
+ } catch (err) {
848
+ if (err instanceof UpdaterError && err.code === "INVALID_MANIFEST") {
849
+ throw err;
850
+ }
851
+ if (!fallbackToReleaseApi) {
852
+ throw UpdaterError.fromUnknown(err);
853
+ }
552
854
  }
553
- ),
554
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
555
- "button",
855
+ }
856
+ const apiUrl = isPrereleaseChannel ? `https://api.github.com/repos/${owner}/${repo}/releases?per_page=20` : `https://api.github.com/repos/${owner}/${repo}/releases/latest`;
857
+ const res = await fetchWithTimeout(
858
+ apiUrl,
556
859
  {
557
- type: "button",
558
- "aria-label": "Cerrar",
559
- style: {
560
- ...secondaryButtonStyle,
561
- background: "transparent",
562
- border: "none",
563
- cursor: "pointer",
564
- fontSize: "1rem",
565
- lineHeight: 1
566
- },
567
- onClick: onDismiss,
568
- children: "\xD7"
860
+ headers: {
861
+ Accept: "application/vnd.github+json",
862
+ "X-GitHub-Api-Version": "2022-11-28"
863
+ }
864
+ },
865
+ timeoutMs
866
+ );
867
+ if (!res.ok) {
868
+ throw new UpdaterError(
869
+ "NETWORK_ERROR",
870
+ `GitHub Releases API failed with HTTP ${res.status}`
871
+ );
872
+ }
873
+ const raw = await res.json();
874
+ const release = isPrereleaseChannel ? selectReleaseForChannel(Array.isArray(raw) ? raw : [], channel) : raw;
875
+ if (!release) {
876
+ throw new UpdaterError(
877
+ "INVALID_MANIFEST",
878
+ `No matching GitHub release found for channel "${channel}"`
879
+ );
880
+ }
881
+ const assets = release.assets ?? [];
882
+ const manifestAsset = assets.find((a) => a.name === manifestAssetName);
883
+ if (manifestAsset) {
884
+ const assetRes = await fetchWithTimeout(
885
+ manifestAsset.browser_download_url,
886
+ { method: "GET" },
887
+ timeoutMs
888
+ );
889
+ if (assetRes.ok) {
890
+ return validateManifest(await assetRes.json());
569
891
  }
570
- )
571
- ] })
572
- ] });
573
- }
574
-
575
- // src/components/UpdateModal.tsx
576
- var import_jsx_runtime2 = require("react/jsx-runtime");
577
- function resolveTheme2(theme = "auto") {
578
- if (theme === "auto" && typeof window !== "undefined" && "matchMedia" in window) {
579
- try {
580
- if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
581
- return "dark";
582
892
  }
583
- } catch {
893
+ if (!fallbackToReleaseApi) {
894
+ throw new UpdaterError(
895
+ "INVALID_MANIFEST",
896
+ `Manifest asset "${manifestAssetName}" not found in release "${release.tag_name}"`
897
+ );
898
+ }
899
+ const platform = await getCurrentPlatform();
900
+ const asset = platform ? selectAssetForPlatform(assets, platform, preferredFormat) : void 0;
901
+ const manifest = {
902
+ schema_version: 1,
903
+ version: release.tag_name,
904
+ channel,
905
+ pub_date: release.published_at ?? "",
906
+ notes: release.body ?? "",
907
+ platforms: asset && platform ? {
908
+ [platform]: {
909
+ url: asset.browser_download_url,
910
+ size: asset.size,
911
+ format: inferInstallerFormat(asset.name) ?? void 0
912
+ }
913
+ } : {}
914
+ };
915
+ return validateManifest(manifest);
584
916
  }
585
- }
586
- return theme === "auto" ? "light" : theme;
917
+ };
587
918
  }
588
- async function openUrl2(url) {
589
- if (typeof window === "undefined") return;
590
- try {
591
- const { invoke } = await import("@tauri-apps/api/tauri");
592
- await invoke("plugin:easy-updater|open_url", { url });
593
- } catch {
594
- try {
595
- window.open(url, "_blank", "noopener,noreferrer");
596
- } catch {
919
+ function selectReleaseForChannel(releases, channel) {
920
+ const published = releases.filter((r) => !r.draft);
921
+ const needle = channel.toLowerCase();
922
+ return published.find((r) => {
923
+ const tag = r.tag_name.toLowerCase();
924
+ return tag.includes(`-${needle}`) || tag.includes(`.${needle}`);
925
+ }) ?? published.find((r) => Boolean(r.prerelease)) ?? published[0];
926
+ }
927
+ function selectAssetForPlatform(assets, platform, preferredFormat) {
928
+ const [os, arch] = platform.toLowerCase().split("-");
929
+ if (!os || !arch) return void 0;
930
+ const scored = [];
931
+ for (const asset of assets) {
932
+ const name = asset.name.toLowerCase();
933
+ const fmt = inferInstallerFormat(name);
934
+ if (!fmt) continue;
935
+ const osOk = os === "windows" && (fmt === "nsis" || fmt === "msi") || os === "darwin" && (fmt === "dmg" || fmt === "pkg") || os === "linux" && (fmt === "appimage" || fmt === "deb" || fmt === "rpm");
936
+ if (!osOk) continue;
937
+ const isArm = name.includes("arm64") || name.includes("aarch64");
938
+ const isX64 = name.includes("x86_64") || name.includes("x64") || name.includes("amd64");
939
+ const isUniversal = name.includes("universal");
940
+ let score = 0;
941
+ if (arch === "aarch64") {
942
+ if (isArm) score = 3;
943
+ else if (isUniversal && os === "darwin") score = 2;
944
+ else continue;
945
+ } else if (arch === "x86_64") {
946
+ if (isX64) score = 3;
947
+ else if (isUniversal && os === "darwin") score = 2;
948
+ else if (!isArm) score = 1;
949
+ else continue;
950
+ } else {
951
+ continue;
952
+ }
953
+ if (preferredFormat && fmt === preferredFormat) {
954
+ score += 10;
597
955
  }
956
+ scored.push({ asset, score });
598
957
  }
958
+ scored.sort((a, b) => b.score - a.score);
959
+ return scored[0]?.asset;
599
960
  }
600
- function UpdateModal(props) {
601
- const { updateInfo, onDismiss, appName, theme = "auto", className } = props;
602
- const resolvedTheme = resolveTheme2(theme);
603
- const overlayStyle = {
604
- position: "fixed",
605
- inset: 0,
606
- backgroundColor: "rgba(15,23,42,0.6)",
607
- display: "flex",
608
- alignItems: "center",
609
- justifyContent: "center",
610
- zIndex: 60
611
- };
612
- const modalStyle = resolvedTheme === "dark" ? {
613
- backgroundColor: "#020617",
614
- color: "#e5e7eb",
615
- borderRadius: "0.75rem",
616
- padding: "1.5rem",
617
- maxWidth: "28rem",
618
- width: "100%",
619
- boxShadow: "0 20px 25px -5px rgba(15,23,42,0.8)"
620
- } : {
621
- backgroundColor: "white",
622
- color: "#0f172a",
623
- borderRadius: "0.75rem",
624
- padding: "1.5rem",
625
- maxWidth: "28rem",
626
- width: "100%",
627
- boxShadow: "0 20px 25px -5px rgba(15,23,42,0.2)"
628
- };
629
- const primaryButtonStyle = resolvedTheme === "dark" ? {
630
- backgroundColor: "#22c55e",
631
- color: "#022c22"
632
- } : {
633
- backgroundColor: "#16a34a",
634
- color: "white"
635
- };
636
- const secondaryButtonStyle = resolvedTheme === "dark" ? {
637
- borderColor: "#4b5563",
638
- color: "#e5e7eb"
639
- } : {
640
- borderColor: "#cbd5f5",
641
- color: "#1f2937"
642
- };
643
- const textMuted = {
644
- opacity: 0.8,
645
- fontSize: "0.875rem"
646
- };
647
- const title = appName ? `${appName} tiene una nueva versi\xF3n` : "Nueva actualizaci\xF3n disponible";
648
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: overlayStyle, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: modalStyle, className, children: [
649
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
650
- "div",
651
- {
652
- style: {
653
- display: "flex",
654
- justifyContent: "space-between",
655
- alignItems: "flex-start",
656
- marginBottom: "0.75rem"
657
- },
658
- children: [
659
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
660
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
661
- "h2",
662
- {
663
- style: {
664
- fontSize: "1.125rem",
665
- fontWeight: 600,
666
- margin: 0,
667
- marginBottom: "0.25rem"
668
- },
669
- children: title
670
- }
671
- ),
672
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { style: textMuted, children: [
673
- "Versi\xF3n actual ",
674
- updateInfo.currentVersion,
675
- " \xB7 Nueva versi\xF3n ",
676
- updateInfo.latestVersion
677
- ] })
678
- ] }),
679
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
680
- "button",
681
- {
682
- type: "button",
683
- "aria-label": "Cerrar",
684
- onClick: onDismiss,
685
- style: {
686
- background: "transparent",
687
- border: "none",
688
- cursor: "pointer",
689
- fontSize: "1rem",
690
- lineHeight: 1,
691
- marginLeft: "0.5rem"
692
- },
693
- children: "\xD7"
694
- }
695
- )
696
- ]
697
- }
698
- ),
699
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
700
- "div",
701
- {
702
- style: {
703
- marginTop: "0.75rem",
704
- marginBottom: "1rem",
705
- maxHeight: "12rem",
706
- overflowY: "auto",
707
- padding: "0.5rem",
708
- borderRadius: "0.5rem",
709
- backgroundColor: resolvedTheme === "dark" ? "#020617" : "#f1f5f9",
710
- fontSize: "0.875rem",
711
- whiteSpace: "pre-wrap"
712
- },
713
- children: updateInfo.releaseNotes || "Esta actualizaci\xF3n incluye mejoras y correcciones de errores."
714
- }
715
- ),
716
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
717
- "div",
718
- {
719
- style: {
720
- display: "flex",
721
- justifyContent: "flex-end",
722
- gap: "0.5rem",
723
- marginTop: "0.5rem"
961
+
962
+ // src/providers/http.ts
963
+ function createHttpProvider(config) {
964
+ const {
965
+ manifestUrl,
966
+ headers,
967
+ channel,
968
+ preferredFormat,
969
+ allowInsecureHttp = false,
970
+ timeoutMs = 15e3
971
+ } = config;
972
+ assertSafeRemoteUrl(manifestUrl, allowInsecureHttp);
973
+ const sortedHeaders = headers ? Object.keys(headers).sort().map((k) => [k, headers[k]]) : [];
974
+ const fingerprint = JSON.stringify([
975
+ "http",
976
+ manifestUrl,
977
+ sortedHeaders,
978
+ channel ?? null,
979
+ preferredFormat ?? null,
980
+ allowInsecureHttp
981
+ ]);
982
+ return {
983
+ type: "http",
984
+ fingerprint,
985
+ tauriParams: {
986
+ manifestUrl,
987
+ headers,
988
+ channel,
989
+ preferredFormat
990
+ },
991
+ async fetchManifest() {
992
+ const res = await fetchWithTimeout(
993
+ manifestUrl,
994
+ {
995
+ method: "GET",
996
+ headers
724
997
  },
725
- children: [
726
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
727
- "button",
728
- {
729
- type: "button",
730
- onClick: onDismiss,
731
- style: {
732
- ...secondaryButtonStyle,
733
- background: "transparent",
734
- padding: "0.45rem 0.9rem",
735
- borderRadius: "9999px",
736
- borderWidth: 1,
737
- borderStyle: "solid",
738
- cursor: "pointer",
739
- fontSize: "0.875rem"
740
- },
741
- children: "Recordarme despu\xE9s"
742
- }
743
- ),
744
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
745
- "button",
746
- {
747
- type: "button",
748
- onClick: () => {
749
- void openUrl2(updateInfo.downloadUrl);
750
- },
751
- style: {
752
- ...primaryButtonStyle,
753
- padding: "0.45rem 0.9rem",
754
- borderRadius: "9999px",
755
- border: "none",
756
- cursor: "pointer",
757
- fontSize: "0.875rem",
758
- fontWeight: 500
759
- },
760
- children: "Descargar ahora"
761
- }
762
- )
763
- ]
998
+ timeoutMs
999
+ );
1000
+ if (!res.ok) {
1001
+ throw new UpdaterError("NETWORK_ERROR", `Manifest endpoint returned HTTP ${res.status}`);
764
1002
  }
765
- )
766
- ] }) });
1003
+ const json = await res.json();
1004
+ return validateManifest(json, allowInsecureHttp);
1005
+ }
1006
+ };
1007
+ }
1008
+
1009
+ // src/providers/s3.ts
1010
+ function createS3Provider(config) {
1011
+ const {
1012
+ bucketUrl,
1013
+ manifestPath,
1014
+ channel = "stable",
1015
+ preferredFormat,
1016
+ headers,
1017
+ allowInsecureHttp = false,
1018
+ timeoutMs = 15e3
1019
+ } = config;
1020
+ assertSafeRemoteUrl(bucketUrl, allowInsecureHttp);
1021
+ const resolvedPath = manifestPath?.replace(/^\/+/, "") || (channel === "stable" ? "latest/update-manifest.json" : `${channel}/update-manifest.json`);
1022
+ const manifestUrl = `${bucketUrl.replace(/\/+$/, "")}/${resolvedPath}`;
1023
+ const httpProvider = createHttpProvider({
1024
+ manifestUrl,
1025
+ headers,
1026
+ channel,
1027
+ preferredFormat,
1028
+ allowInsecureHttp,
1029
+ timeoutMs
1030
+ });
1031
+ const fingerprint = JSON.stringify([
1032
+ "s3",
1033
+ bucketUrl.replace(/\/+$/, ""),
1034
+ resolvedPath,
1035
+ channel,
1036
+ preferredFormat ?? null,
1037
+ allowInsecureHttp
1038
+ ]);
1039
+ return {
1040
+ type: "s3",
1041
+ fingerprint,
1042
+ tauriParams: {
1043
+ s3BucketUrl: bucketUrl,
1044
+ s3ManifestPath: resolvedPath,
1045
+ headers,
1046
+ channel,
1047
+ preferredFormat
1048
+ },
1049
+ fetchManifest() {
1050
+ return httpProvider.fetchManifest();
1051
+ }
1052
+ };
767
1053
  }
768
1054
  // Annotate the CommonJS export names for ESM import in node:
769
1055
  0 && (module.exports = {
770
- UpdateBanner,
771
- UpdateModal,
1056
+ UpdaterClient,
1057
+ UpdaterError,
1058
+ assertSafeRemoteUrl,
1059
+ assertValidGitHubIdent,
1060
+ compareSemver,
772
1061
  createGitHubProvider,
773
1062
  createHttpProvider,
774
1063
  createS3Provider,
1064
+ createUpdaterClient,
1065
+ fetchWithTimeout,
775
1066
  getCurrentPlatform,
1067
+ getPlatformSummary,
1068
+ inferInstallerFormat,
1069
+ isBelowMinVersion,
776
1070
  isNewerVersion,
777
- useUpdateChecker
1071
+ isSafeRemoteUrl,
1072
+ isTauriRuntime,
1073
+ normalizeArch,
1074
+ normalizeOs,
1075
+ parseSemver,
1076
+ resolveArtifactsFromPlatform,
1077
+ selectPlatformFromManifest,
1078
+ validateManifest
778
1079
  });
779
1080
  //# sourceMappingURL=index.js.map