@stacksjs/desktop-build 0.75.551 → 0.75.555

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.
@@ -5,8 +5,29 @@ export declare function updateManifestKey(location: UpdateLocation): string;
5
5
  export declare function updateArtifactKey(location: UpdateLocation, version: string, fileName: string): string;
6
6
  /** The URL an app asks: `<feedUrl>/<platform>/<arch>`, with its channel and version so the feed can answer "nothing new". */
7
7
  export declare function updateFeedUrl(feedUrl: string, target: { platform: string, architecture: string }, query?: { channel?: string, currentVersion?: string }): string;
8
+ /**
9
+ * Where an artifact is downloaded from when nothing else serves the disk:
10
+ * `<feedUrl>/files/<channel>/<platform>-<arch>/<version>/<file>`, the route
11
+ * beside the feed. The folder on the disk (`prefix`) is not part of it.
12
+ */
13
+ export declare function updateArtifactUrl(feedUrl: string, location: UpdateLocation, version: string, fileName: string): string;
14
+ /**
15
+ * Why an artifact URL cannot be published, or null. A manifest is signed and
16
+ * read by apps on other machines: a loopback or development host in it is an
17
+ * update nobody can download.
18
+ */
19
+ export declare function artifactUrlProblem(url: string): string | null;
8
20
  /** A disk from `@stacksjs/storage` (`config/filesystems.ts`), as an `UpdateStore`. Default: the default disk. */
9
21
  export declare function storageUpdateStore(disk?: string): Promise<UpdateStore>;
22
+ /** Bytes `start` to `end` (inclusive) of a stream, read a chunk at a time. Works on any disk, whether or not it can seek. */
23
+ export declare function sliceStream(source: ReadableStream<Uint8Array>, start: number, end: number): ReadableStream<Uint8Array>;
24
+ /**
25
+ * The URL a published artifact is downloaded from: under `artifactBaseUrl`
26
+ * when a bucket or CDN serves the disk, else through the route beside the
27
+ * feed, which works for any disk. The disk's own public URL is the answer
28
+ * only when neither is known.
29
+ */
30
+ export declare function publishedArtifactUrl(options: UpdateLocation & { store: UpdateStore, artifactBaseUrl?: string, feedUrl?: string }, version: string, fileName: string): Promise<string>;
10
31
  /**
11
32
  * Publish one platform's update: the artifact first, then the signed manifest
12
33
  * that points at it. In that order, so the feed never names a file that is
@@ -20,6 +41,21 @@ export declare function publishDesktopUpdate(options: PublishDesktopUpdateOption
20
41
  * so the server holds no key and cannot alter what an app will accept.
21
42
  */
22
43
  export declare function serveUpdateFeed(options: UpdateLocation & { store: UpdateStore, currentVersion?: string | null }): Promise<Response>;
44
+ /** One `bytes=` range of a file of `size` bytes: the offsets, `null` for "send it all", or `false` when it cannot be satisfied. */
45
+ export declare function parseByteRange(header: string | null | undefined, size: number): { start: number, end: number } | null | false;
46
+ /**
47
+ * Stream one published artifact: what the URL in a manifest or release.json
48
+ * names when the route beside the feed serves the disk. Only a key of the
49
+ * artifact shape under the configured folder is ever read, so no path reaches
50
+ * another folder or another file on the disk. Streams, with a length and
51
+ * byte ranges, so a download can be resumed and nothing is held in memory.
52
+ */
53
+ export declare function serveUpdateArtifact(options: ServeUpdateArtifactOptions): Promise<Response>;
54
+ /**
55
+ * A published artifact of the app this project builds, as a route handler's
56
+ * answer: `GET /api/updates/files/{channel}/{target}/{version}/{file}`.
57
+ */
58
+ export declare function answerUpdateArtifact(options: AnswerUpdateArtifactOptions): Promise<Response>;
23
59
  /**
24
60
  * The update feed for the app this project builds, as a route handler's
25
61
  * answer: `GET /api/updates/{platform}/{arch}`. Reads the manifest
@@ -42,11 +78,17 @@ export declare interface UpdateLocation {
42
78
  channel?: string
43
79
  prefix?: string
44
80
  }
81
+ /** A stored file, opened for download. `start` and `end` are byte offsets, both inclusive. */
82
+ export declare interface StoredArtifact {
83
+ size: number
84
+ stream: (range?: { start: number, end: number }) => Promise<ReadableStream<Uint8Array>>
85
+ }
45
86
  /** As much of a storage disk as updates use. `storageUpdateStore()` adapts `@stacksjs/storage`. */
46
87
  export declare interface UpdateStore {
47
88
  read: (key: string) => Promise<string | null>
48
89
  write: (key: string, contents: string | Uint8Array) => Promise<void>
49
90
  publicUrl: (key: string) => Promise<string>
91
+ open?: (key: string) => Promise<StoredArtifact | null>
50
92
  }
51
93
  export declare interface PublishDesktopUpdateOptions extends UpdateLocation {
52
94
  store: UpdateStore
@@ -57,8 +99,24 @@ export declare interface PublishDesktopUpdateOptions extends UpdateLocation {
57
99
  keyId?: string
58
100
  notes?: string
59
101
  artifactBaseUrl?: string
102
+ feedUrl?: string
60
103
  publishedAt?: string
61
104
  }
105
+ export declare interface ServeUpdateArtifactOptions {
106
+ store: UpdateStore
107
+ prefix?: string
108
+ channel: string
109
+ target: string
110
+ version: string
111
+ file: string
112
+ range?: string | null
113
+ method?: string
114
+ }
115
+ export declare interface AnswerUpdateArtifactOptions extends Omit<ServeUpdateArtifactOptions, 'store' | 'prefix'> {
116
+ root?: string
117
+ updates?: UpdatesConfig
118
+ store?: UpdateStore
119
+ }
62
120
  export declare interface AnswerUpdateFeedOptions {
63
121
  platform: string
64
122
  architecture: string
@@ -68,3 +126,5 @@ export declare interface AnswerUpdateFeedOptions {
68
126
  updates?: { disk?: string, prefix?: string, channel?: string }
69
127
  store?: UpdateStore
70
128
  }
129
+ declare type UpdatesConfig = { disk?: string, prefix?: string, channel?: string }
130
+ export {};
@@ -1,2 +1,2 @@
1
- import{existsSync,readFileSync}from"node:fs";import{basename,join}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{describeArtifact,signUpdateManifest}from"./update-signing";import{compareVersions,validateUpdateManifest}from"./updater";export const UPDATE_PLATFORMS=["darwin","linux","win32"];export const DEFAULT_UPDATE_PREFIX="desktop-updates";function checkedLocation(location){const channel=location.channel||"stable";const prefix=(location.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"");if(!UPDATE_PLATFORMS.includes(location.platform))throw new Error(`Unknown desktop platform: ${location.platform}`);if(!/^[a-z0-9_]+$/.test(location.architecture))throw new Error(`Unknown desktop architecture: ${location.architecture}`);if(!/^[a-z0-9][a-z0-9._-]*$/i.test(channel))throw new Error(`Invalid release channel: ${channel}`);return{platform:location.platform,architecture:location.architecture,channel,prefix}}export function updateManifestKey(location){const at=checkedLocation(location);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/latest.json`}export function updateArtifactKey(location,version,fileName){const at=checkedLocation(location);if(!/^[\w.+-]+$/.test(version)||!/^[\w.+ -]+$/.test(fileName))throw new Error(`Invalid artifact name: ${version}/${fileName}`);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/${version}/${fileName}`}export function updateFeedUrl(feedUrl,target,query={}){const url=new URL(`${feedUrl.replace(/\/+$/,"")}/${target.platform}/${target.architecture}`);if(query.channel&&query.channel!=="stable")url.searchParams.set("channel",query.channel);if(query.currentVersion)url.searchParams.set("current",query.currentVersion);return url.toString()}export async function storageUpdateStore(disk){const{Storage}=await import("@stacksjs/storage");const adapter=Storage.disk(disk);return{read:async(key)=>await adapter.fileExists(key)?adapter.readToString(key):null,write:async(key,contents)=>{await adapter.write(key,typeof contents==="string"?contents:Buffer.from(contents))},publicUrl:(key)=>adapter.publicUrl(key)}}export async function publishDesktopUpdate(options){const{size,sha256}=await describeArtifact(options.artifact);const artifactKey=updateArtifactKey(options,options.version,basename(options.artifact));await options.store.write(artifactKey,readFileSync(options.artifact));const url=options.artifactBaseUrl?`${options.artifactBaseUrl.replace(/\/+$/,"")}/${artifactKey}`:await options.store.publicUrl(artifactKey);const unsigned={version:options.version,url,sha256,size,sourceRevision:options.sourceRevision,platform:options.platform,architecture:options.architecture,publishedAt:options.publishedAt??new Date().toISOString(),...options.notes?{notes:options.notes}:{}};const manifest=signUpdateManifest(unsigned,options.privateKey,options.keyId);await options.store.write(updateManifestKey(options),`${JSON.stringify(manifest,null,2)}
2
- `);return manifest}const feedHeaders={"content-type":"application/json; charset=utf-8","cache-control":"no-store"};export async function serveUpdateFeed(options){let key;try{key=updateManifestKey(options)}catch(error){return new Response(JSON.stringify({error:error instanceof Error?error.message:String(error)}),{status:404,headers:feedHeaders})}const stored=await options.store.read(key);if(!stored)return new Response(JSON.stringify({error:"No update has been published for this platform."}),{status:404,headers:feedHeaders});let manifest;try{manifest=validateUpdateManifest(JSON.parse(stored))}catch{return new Response(JSON.stringify({error:"The published update manifest is not valid."}),{status:500,headers:feedHeaders})}if(options.currentVersion){try{if(compareVersions(manifest.version,options.currentVersion)<=0)return new Response(null,{status:204,headers:{"cache-control":"no-store"}})}catch{}}return new Response(stored,{headers:feedHeaders})}export async function answerUpdateFeed(options){let updates=options.updates;if(!updates&&!options.store){const file=join(options.root??process.cwd(),"config/desktop.ts");updates=existsSync(file)?(await import(pathToFileURL(file).href)).default?.webview?.updates:undefined;if(!updates)return new Response(JSON.stringify({error:"This app publishes no desktop updates."}),{status:404,headers:feedHeaders})}return serveUpdateFeed({store:options.store??await storageUpdateStore(updates?.disk),platform:options.platform,architecture:options.architecture,channel:options.channel||updates?.channel,prefix:updates?.prefix,currentVersion:options.currentVersion})}
1
+ import{existsSync,readFileSync}from"node:fs";import{basename,join}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{describeArtifact,signUpdateManifest}from"./update-signing";import{compareVersions,validateUpdateManifest}from"./updater";export const UPDATE_PLATFORMS=["darwin","linux","win32"];export const DEFAULT_UPDATE_PREFIX="desktop-updates";function checkedLocation(location){const channel=location.channel||"stable";const prefix=(location.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"");if(!UPDATE_PLATFORMS.includes(location.platform))throw new Error(`Unknown desktop platform: ${location.platform}`);if(!/^[a-z0-9_]+$/.test(location.architecture))throw new Error(`Unknown desktop architecture: ${location.architecture}`);if(!/^[a-z0-9][a-z0-9._-]*$/i.test(channel))throw new Error(`Invalid release channel: ${channel}`);return{platform:location.platform,architecture:location.architecture,channel,prefix}}export function updateManifestKey(location){const at=checkedLocation(location);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/latest.json`}export function updateArtifactKey(location,version,fileName){const at=checkedLocation(location);if(!/^\w[\w.+-]*$/.test(version)||!/^\w[\w.+ -]*$/.test(fileName))throw new Error(`Invalid artifact name: ${version}/${fileName}`);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/${version}/${fileName}`}export function updateFeedUrl(feedUrl,target,query={}){const url=new URL(`${feedUrl.replace(/\/+$/,"")}/${target.platform}/${target.architecture}`);if(query.channel&&query.channel!=="stable")url.searchParams.set("channel",query.channel);if(query.currentVersion)url.searchParams.set("current",query.currentVersion);return url.toString()}export function updateArtifactUrl(feedUrl,location,version,fileName){const key=updateArtifactKey({...location,prefix:""},version,fileName);return`${feedUrl.replace(/\/+$/,"")}/files/${key.replace(/^\/+/,"").split("/").map(encodeURIComponent).join("/")}`}export function artifactUrlProblem(url){let parsed;try{parsed=new URL(url)}catch{return`${url} is not a URL`}if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return`${url} is not an http(s) URL`;const host=parsed.hostname.toLowerCase().replace(/^\[|\]$/g,"");const local=host==="localhost"||host.endsWith(".localhost")||host.endsWith(".test")||host.endsWith(".local")||host==="::1"||host==="0.0.0.0"||/^127\./.test(host);return local?`${url} is on this machine (${host}): no installed app could download it`:null}export async function storageUpdateStore(disk){const{Storage}=await import("@stacksjs/storage");const adapter=Storage.disk(disk);return{read:async(key)=>await adapter.fileExists(key)?adapter.readToString(key):null,write:async(key,contents)=>{await adapter.write(key,typeof contents==="string"?contents:Buffer.from(contents))},publicUrl:(key)=>adapter.publicUrl(key),open:async(key)=>{if(!await adapter.fileExists(key))return null;const size=await adapter.fileSize(key);return{size,stream:async(range)=>{const whole=typeof adapter.getStream==="function"?await adapter.getStream(key):new Blob([await adapter.readToUint8Array(key)]).stream();return range?sliceStream(whole,range.start,range.end):whole}}}}}export function sliceStream(source,start,end){const reader=source.getReader();let offset=0;return new ReadableStream({async pull(controller){while(true){if(offset>end){await reader.cancel();controller.close();return}const{done,value}=await reader.read();if(done){controller.close();return}const from=Math.max(start-offset,0);const to=Math.min(end+1-offset,value.byteLength);offset+=value.byteLength;if(to>from){controller.enqueue(value.subarray(from,to));return}}},cancel:(reason)=>reader.cancel(reason)})}export async function publishedArtifactUrl(options,version,fileName){const key=updateArtifactKey(options,version,fileName);if(options.artifactBaseUrl)return`${options.artifactBaseUrl.replace(/\/+$/,"")}/${key.split("/").map(encodeURIComponent).join("/")}`;if(options.feedUrl)return updateArtifactUrl(options.feedUrl,options,version,fileName);return options.store.publicUrl(key)}export async function publishDesktopUpdate(options){const{size,sha256}=await describeArtifact(options.artifact);const artifactKey=updateArtifactKey(options,options.version,basename(options.artifact));const url=await publishedArtifactUrl(options,options.version,basename(options.artifact));await options.store.write(artifactKey,readFileSync(options.artifact));const unsigned={version:options.version,url,sha256,size,sourceRevision:options.sourceRevision,platform:options.platform,architecture:options.architecture,publishedAt:options.publishedAt??new Date().toISOString(),...options.notes?{notes:options.notes}:{}};const manifest=signUpdateManifest(unsigned,options.privateKey,options.keyId);await options.store.write(updateManifestKey(options),`${JSON.stringify(manifest,null,2)}
2
+ `);return manifest}const feedHeaders={"content-type":"application/json; charset=utf-8","cache-control":"no-store"};export async function serveUpdateFeed(options){let key;try{key=updateManifestKey(options)}catch(error){return new Response(JSON.stringify({error:error instanceof Error?error.message:String(error)}),{status:404,headers:feedHeaders})}const stored=await options.store.read(key);if(!stored)return new Response(JSON.stringify({error:"No update has been published for this platform."}),{status:404,headers:feedHeaders});let manifest;try{manifest=validateUpdateManifest(JSON.parse(stored))}catch{return new Response(JSON.stringify({error:"The published update manifest is not valid."}),{status:500,headers:feedHeaders})}if(options.currentVersion){try{if(compareVersions(manifest.version,options.currentVersion)<=0)return new Response(null,{status:204,headers:{"cache-control":"no-store"}})}catch{}}return new Response(stored,{headers:feedHeaders})}const artifactTypes={zip:"application/zip",dmg:"application/x-apple-diskimage",msi:"application/x-msi",exe:"application/vnd.microsoft.portable-executable",appimage:"application/vnd.appimage",deb:"application/vnd.debian.binary-package",rpm:"application/x-rpm"};function refused(status,error,headers={}){return new Response(JSON.stringify({error}),{status,headers:{...feedHeaders,...headers}})}export function parseByteRange(header,size){if(!header)return null;const match=/^bytes=(\d*)-(\d*)$/.exec(header.trim());if(!match||!match[1]&&!match[2])return null;if(!match[1]){const last=Number(match[2]);if(!last||!size)return false;return{start:Math.max(size-last,0),end:size-1}}const start=Number(match[1]);const end=match[2]?Math.min(Number(match[2]),size-1):size-1;if(start>=size||start>end)return false;return{start,end}}export async function serveUpdateArtifact(options){const missing=()=>refused(404,"No such release artifact.");const split=/^([a-z0-9]+)-([a-z0-9_]+)$/.exec(options.target);if(!split)return missing();let key;try{key=updateArtifactKey({platform:split[1],architecture:split[2],channel:options.channel,prefix:options.prefix},options.version,options.file)}catch{return missing()}if(!options.store.open)return missing();const stored=await options.store.open(key);if(!stored)return missing();const range=parseByteRange(options.range,stored.size);if(range===false)return refused(416,"The requested range is outside the file.",{"content-range":`bytes */${stored.size}`});const length=range?range.end-range.start+1:stored.size;const headers={"content-type":artifactTypes[options.file.slice(options.file.lastIndexOf(".")+1).toLowerCase()]??"application/octet-stream","content-length":String(length),"content-disposition":`attachment; filename="${options.file}"`,"accept-ranges":"bytes","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff"};if(range)headers["content-range"]=`bytes ${range.start}-${range.end}/${stored.size}`;const body=options.method?.toUpperCase()==="HEAD"?null:await stored.stream(range??undefined);return new Response(body,{status:range?206:200,headers})}async function projectUpdates(root){const file=join(root??process.cwd(),"config/desktop.ts");return existsSync(file)?(await import(pathToFileURL(file).href)).default?.webview?.updates:undefined}export async function answerUpdateArtifact(options){const updates=options.updates??(options.store?undefined:await projectUpdates(options.root));if(!updates&&!options.store)return refused(404,"This app publishes no desktop updates.");return serveUpdateArtifact({...options,store:options.store??await storageUpdateStore(updates?.disk),prefix:updates?.prefix})}export async function answerUpdateFeed(options){let updates=options.updates;if(!updates&&!options.store){updates=await projectUpdates(options.root);if(!updates)return new Response(JSON.stringify({error:"This app publishes no desktop updates."}),{status:404,headers:feedHeaders})}return serveUpdateFeed({store:options.store??await storageUpdateStore(updates?.disk),platform:options.platform,architecture:options.architecture,channel:options.channel||updates?.channel,prefix:updates?.prefix,currentVersion:options.currentVersion})}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/desktop-build",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.551",
5
+ "version": "0.75.555",
6
6
  "description": "Build and launch Craft desktop applications for Stacks",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -73,17 +73,17 @@
73
73
  "prepublishOnly": "bun run build"
74
74
  },
75
75
  "dependencies": {
76
- "@stacksjs/config": "0.75.551",
77
- "@stacksjs/router": "0.75.551",
78
- "@stacksjs/server": "0.75.551",
79
- "@stacksjs/storage": "0.75.551",
76
+ "@stacksjs/config": "0.75.555",
77
+ "@stacksjs/router": "0.75.555",
78
+ "@stacksjs/server": "0.75.555",
79
+ "@stacksjs/storage": "0.75.555",
80
80
  "craft-native": ">=0.0.499"
81
81
  },
82
82
  "peerDependencies": {
83
- "@stacksjs/config": "0.75.551",
84
- "@stacksjs/router": "0.75.551",
85
- "@stacksjs/server": "0.75.551",
86
- "@stacksjs/storage": "0.75.551"
83
+ "@stacksjs/config": "0.75.555",
84
+ "@stacksjs/router": "0.75.555",
85
+ "@stacksjs/server": "0.75.555",
86
+ "@stacksjs/storage": "0.75.555"
87
87
  },
88
88
  "peerDependenciesMeta": {
89
89
  "@stacksjs/config": {
@@ -100,7 +100,7 @@
100
100
  }
101
101
  },
102
102
  "devDependencies": {
103
- "@stacksjs/build": "0.75.551",
103
+ "@stacksjs/build": "0.75.555",
104
104
  "better-dx": "^0.2.24"
105
105
  }
106
106
  }