@limrun/api 0.79.6 → 0.80.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.
Files changed (127) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/client.d.mts +4 -1
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +4 -1
  5. package/client.d.ts.map +1 -1
  6. package/client.js +1 -1
  7. package/client.js.map +1 -1
  8. package/client.mjs +1 -1
  9. package/client.mjs.map +1 -1
  10. package/exec-client.d.mts +64 -15
  11. package/exec-client.d.mts.map +1 -1
  12. package/exec-client.d.ts +64 -15
  13. package/exec-client.d.ts.map +1 -1
  14. package/exec-client.js.map +1 -1
  15. package/exec-client.mjs.map +1 -1
  16. package/folder-sync.d.mts +2 -0
  17. package/folder-sync.d.mts.map +1 -1
  18. package/folder-sync.d.ts +2 -0
  19. package/folder-sync.d.ts.map +1 -1
  20. package/folder-sync.js +1 -1
  21. package/folder-sync.js.map +1 -1
  22. package/folder-sync.mjs +1 -1
  23. package/folder-sync.mjs.map +1 -1
  24. package/index.d.mts +2 -2
  25. package/index.d.mts.map +1 -1
  26. package/index.d.ts +2 -2
  27. package/index.d.ts.map +1 -1
  28. package/index.js.map +1 -1
  29. package/index.mjs.map +1 -1
  30. package/instance-client.d.mts +7 -2
  31. package/instance-client.d.mts.map +1 -1
  32. package/instance-client.d.ts +7 -2
  33. package/instance-client.d.ts.map +1 -1
  34. package/instance-client.js +27 -55
  35. package/instance-client.js.map +1 -1
  36. package/instance-client.mjs +27 -55
  37. package/instance-client.mjs.map +1 -1
  38. package/internal/asset-source.d.mts +11 -0
  39. package/internal/asset-source.d.mts.map +1 -0
  40. package/internal/asset-source.d.ts +11 -0
  41. package/internal/asset-source.d.ts.map +1 -0
  42. package/internal/asset-source.js +15 -0
  43. package/internal/asset-source.js.map +1 -0
  44. package/internal/asset-source.mjs +12 -0
  45. package/internal/asset-source.mjs.map +1 -0
  46. package/internal/file-transfer.d.mts +43 -0
  47. package/internal/file-transfer.d.mts.map +1 -0
  48. package/internal/file-transfer.d.ts +43 -0
  49. package/internal/file-transfer.d.ts.map +1 -0
  50. package/internal/file-transfer.js +270 -0
  51. package/internal/file-transfer.js.map +1 -0
  52. package/internal/file-transfer.mjs +261 -0
  53. package/internal/file-transfer.mjs.map +1 -0
  54. package/ios-client.d.mts +23 -4
  55. package/ios-client.d.mts.map +1 -1
  56. package/ios-client.d.ts +23 -4
  57. package/ios-client.d.ts.map +1 -1
  58. package/ios-client.js +11 -2
  59. package/ios-client.js.map +1 -1
  60. package/ios-client.mjs +11 -2
  61. package/ios-client.mjs.map +1 -1
  62. package/lib/workload-credentials.d.mts +2 -1
  63. package/lib/workload-credentials.d.mts.map +1 -1
  64. package/lib/workload-credentials.d.ts +2 -1
  65. package/lib/workload-credentials.d.ts.map +1 -1
  66. package/lib/workload-credentials.js +3 -0
  67. package/lib/workload-credentials.js.map +1 -1
  68. package/lib/workload-credentials.mjs +3 -0
  69. package/lib/workload-credentials.mjs.map +1 -1
  70. package/package.json +2 -1
  71. package/resources/access-tokens.d.mts +17 -0
  72. package/resources/access-tokens.d.mts.map +1 -1
  73. package/resources/access-tokens.d.ts +17 -0
  74. package/resources/access-tokens.d.ts.map +1 -1
  75. package/resources/access-tokens.js +39 -3
  76. package/resources/access-tokens.js.map +1 -1
  77. package/resources/access-tokens.mjs +36 -2
  78. package/resources/access-tokens.mjs.map +1 -1
  79. package/resources/index.d.mts +1 -1
  80. package/resources/index.d.mts.map +1 -1
  81. package/resources/index.d.ts +1 -1
  82. package/resources/index.d.ts.map +1 -1
  83. package/resources/index.js.map +1 -1
  84. package/resources/index.mjs.map +1 -1
  85. package/resources/macos-instances-helpers.d.mts +83 -0
  86. package/resources/macos-instances-helpers.d.mts.map +1 -1
  87. package/resources/macos-instances-helpers.d.ts +83 -0
  88. package/resources/macos-instances-helpers.d.ts.map +1 -1
  89. package/resources/macos-instances-helpers.js +89 -0
  90. package/resources/macos-instances-helpers.js.map +1 -1
  91. package/resources/macos-instances-helpers.mjs +88 -0
  92. package/resources/macos-instances-helpers.mjs.map +1 -1
  93. package/resources/scoped-tokens.d.mts +2 -2
  94. package/resources/scoped-tokens.d.mts.map +1 -1
  95. package/resources/scoped-tokens.d.ts +2 -2
  96. package/resources/scoped-tokens.d.ts.map +1 -1
  97. package/resources/scoped-tokens.js +9 -2
  98. package/resources/scoped-tokens.js.map +1 -1
  99. package/resources/scoped-tokens.mjs +9 -2
  100. package/resources/scoped-tokens.mjs.map +1 -1
  101. package/resources/xcode-instances-helpers.d.mts +33 -18
  102. package/resources/xcode-instances-helpers.d.mts.map +1 -1
  103. package/resources/xcode-instances-helpers.d.ts +33 -18
  104. package/resources/xcode-instances-helpers.d.ts.map +1 -1
  105. package/resources/xcode-instances-helpers.js +5 -2
  106. package/resources/xcode-instances-helpers.js.map +1 -1
  107. package/resources/xcode-instances-helpers.mjs +5 -2
  108. package/resources/xcode-instances-helpers.mjs.map +1 -1
  109. package/src/client.ts +5 -2
  110. package/src/exec-client.ts +77 -22
  111. package/src/folder-sync.ts +3 -1
  112. package/src/index.ts +9 -0
  113. package/src/instance-client.ts +38 -59
  114. package/src/internal/asset-source.ts +13 -0
  115. package/src/internal/file-transfer.ts +284 -0
  116. package/src/ios-client.ts +43 -6
  117. package/src/lib/workload-credentials.ts +6 -1
  118. package/src/resources/access-tokens.ts +39 -2
  119. package/src/resources/index.ts +4 -0
  120. package/src/resources/macos-instances-helpers.ts +197 -0
  121. package/src/resources/scoped-tokens.ts +14 -3
  122. package/src/resources/xcode-instances-helpers.ts +49 -19
  123. package/src/version.ts +1 -1
  124. package/version.d.mts +1 -1
  125. package/version.d.ts +1 -1
  126. package/version.js +1 -1
  127. package/version.mjs +1 -1
@@ -113,15 +113,16 @@ export type XcodeBuildExecRequest = {
113
113
  certificatePassword?: string;
114
114
  /** One profile per embedded bundle. */
115
115
  provisioningProfilesBase64?: string[];
116
+ /** Secret read by the build instead of the inline certificate fields. */
117
+ certificateSecret?: string;
118
+ /** Profile secrets the build adds to provisioningProfilesBase64. */
119
+ provisioningProfileSecrets?: string[];
116
120
  };
117
121
  cloudSigning?: {
118
122
  method: 'app-store-connect' | 'release-testing' | 'debugging';
119
123
  teamId: string;
120
- apiKeyId: string;
121
- apiIssuerId: string;
122
- apiPrivateKeyBase64: string;
123
124
  entitlements?: Record<string, string>;
124
- };
125
+ } & AppStoreConnectTeamKey;
125
126
  /** Wire name retained for compatibility with the limbuild exec API. */
126
127
  testflight?: AppStoreUploadConfig;
127
128
  buildSettings?: Record<string, string>;
@@ -136,8 +137,8 @@ export type XcodeBuildExecRequest = {
136
137
  fileFromSecret?: Record<string, string>;
137
138
  gitInit?: boolean;
138
139
  /**
139
- * Build a Debug simulator app that later builds with this option can update
140
- * in place while it runs. See XcodeBuildOptions.hotReload.
140
+ * Build a Debug simulator or Mac app that later builds with this option can
141
+ * update in place while it runs. See XcodeBuildOptions.hotReload.
141
142
  */
142
143
  hotReload?: boolean;
143
144
  /** How xcodebuild stdout is processed before streaming. Defaults to 'xcbeautify'. */
@@ -225,13 +226,29 @@ export type GradleReactNativeConfig = {
225
226
  * passwords live only for the build's duration and never appear in
226
227
  * streamed output.
227
228
  */
228
- export type GradleSigningConfig = {
229
- /** Base64-encoded PKCS12 or JKS upload keystore. */
230
- keystoreBase64: string;
231
- keystorePassword: string;
232
- keyAlias: string;
233
- keyPassword: string;
234
- };
229
+ export type GradleSigningConfig =
230
+ | {
231
+ /** Base64-encoded PKCS12 or JKS upload keystore. */
232
+ keystoreBase64: string;
233
+ keystorePassword: string;
234
+ keyAlias: string;
235
+ keyPassword: string;
236
+ keystoreSecret?: never;
237
+ }
238
+ | {
239
+ /**
240
+ * Secret ID or name/<exact name> holding the upload key, read by the
241
+ * build itself. The value is the JSON saved for an androidSigningKey:
242
+ * keystoreBase64, keystorePassword, keyAlias and keyPassword. The
243
+ * instance role needs `secret:<target>:read`. Requires a server with
244
+ * credential secret support.
245
+ */
246
+ keystoreSecret: string;
247
+ keystoreBase64?: never;
248
+ keystorePassword?: never;
249
+ keyAlias?: never;
250
+ keyPassword?: never;
251
+ };
235
252
 
236
253
  export type GradleBuildExecRequest = {
237
254
  command: 'gradlebuild';
@@ -259,8 +276,8 @@ export type GradleBuildExecRequest = {
259
276
 
260
277
  /**
261
278
  * Publish the built AAB to a Google Play track after a successful build.
262
- * Requires signing. Exactly one of accessToken or serviceAccountJsonBase64
263
- * must be set; the credential is held in memory for the build duration
279
+ * Requires signing. Exactly one of accessToken, serviceAccountJsonBase64 or
280
+ * credentialsSecret must be set; the credential is held in memory for the build duration
264
281
  * only. Progress and failure causes stream as `playstore` SSE events.
265
282
  */
266
283
  export type GradlePlaystoreConfig = {
@@ -268,6 +285,15 @@ export type GradlePlaystoreConfig = {
268
285
  accessToken?: string;
269
286
  /** Base64-encoded service-account JSON key invited in Play Console. */
270
287
  serviceAccountJsonBase64?: string;
288
+ /**
289
+ * Secret ID or name/<exact name> holding the Play credential, read by the
290
+ * build itself: serviceAccountJsonBase64 as saved for a
291
+ * googlePlayServiceAccount, or clientId, clientSecret and refreshToken
292
+ * from a Google sign-in. The build refreshes a sign-in's access token
293
+ * itself. The instance role needs `secret:<target>:read`. Requires a
294
+ * server with credential secret support.
295
+ */
296
+ credentialsSecret?: string;
271
297
  /**
272
298
  * Play track ID, passed to Google verbatim: internal (default), alpha,
273
299
  * beta, production, or a custom closed-testing track. Publishing
@@ -424,6 +450,41 @@ export type PlaystoreEvent = {
424
450
  message?: string;
425
451
  };
426
452
 
453
+ /**
454
+ * An App Store Connect API key passed inline. Prefer {@link AppStoreConnectKeySecret}
455
+ * so the private key stays in Limrun secret storage.
456
+ */
457
+ export type AppStoreConnectInlineKey = {
458
+ /** App Store Connect API key ID, e.g. 2X9R4HXF34. */
459
+ apiKeyId: string;
460
+ /** Issuer ID for team API keys. Omit for individual API keys. */
461
+ apiIssuerId?: string;
462
+ /** Base64-encoded content of the .p8 private key file. */
463
+ apiPrivateKeyBase64: string;
464
+ apiKeySecret?: never;
465
+ };
466
+
467
+ /**
468
+ * An App Store Connect API key read from Limrun secret storage by the build
469
+ * itself. The value is the JSON saved for an appStoreConnectApiKey: keyId,
470
+ * privateKeyP8Base64 and, for team keys, issuerId. The instance role needs
471
+ * `secret:<target>:read`. Requires a server with credential secret support.
472
+ */
473
+ export type AppStoreConnectKeySecret = {
474
+ /** Secret ID or name/<exact name>, e.g. name/VMBY3VYW4U/APP_STORE_CONNECT_API_KEY. */
475
+ apiKeySecret: string;
476
+ apiKeyId?: never;
477
+ apiIssuerId?: never;
478
+ apiPrivateKeyBase64?: never;
479
+ };
480
+
481
+ export type AppStoreConnectKey = AppStoreConnectInlineKey | AppStoreConnectKeySecret;
482
+
483
+ /** Cloud signing needs a team key, which always has an issuer ID. */
484
+ export type AppStoreConnectTeamKey =
485
+ | (AppStoreConnectInlineKey & { apiIssuerId: string })
486
+ | AppStoreConnectKeySecret;
487
+
427
488
  export type AppStoreUploadConfig = {
428
489
  /**
429
490
  * Optional App Store Connect app ID. Its bundle ID must exactly match the
@@ -431,12 +492,6 @@ export type AppStoreUploadConfig = {
431
492
  * exact bundle-ID match automatically.
432
493
  */
433
494
  appId?: string;
434
- /** App Store Connect API key ID, e.g. 2X9R4HXF34. */
435
- apiKeyId: string;
436
- /** Issuer ID for team API keys. Omit for individual API keys. */
437
- apiIssuerId?: string;
438
- /** Base64-encoded content of the .p8 private key file. */
439
- apiPrivateKeyBase64: string;
440
495
  /**
441
496
  * How long the server watches for App Store Connect's processing verdict
442
497
  * after the upload. A FAILED verdict within the window fails the build;
@@ -451,7 +506,7 @@ export type AppStoreUploadConfig = {
451
506
  * App Store Connect before upload.
452
507
  */
453
508
  autoIncrementBuildNumber?: boolean;
454
- };
509
+ } & AppStoreConnectKey;
455
510
 
456
511
  type DataListener = (chunk: string) => void;
457
512
  type CloseListener = () => void;
@@ -65,6 +65,8 @@ export type FolderSyncOptions = {
65
65
  compression?: 'zstd' | 'gzip' | 'identity';
66
66
  /** Folder the files sync into on the instance. Defaults to the local folder's name. */
67
67
  rootName?: string;
68
+ /** Endpoint the batches post to. Defaults to `${apiUrl}/sync`. */
69
+ url?: string;
68
70
  /**
69
71
  * Called after every successful sync: the one-shot sync, the initial sync
70
72
  * in watch mode, and each watch-triggered re-sync.
@@ -215,7 +217,7 @@ async function httpFolderSyncBatch(
215
217
  payloadFiles: { filePath: string }[],
216
218
  compression: 'zstd' | 'gzip' | 'identity',
217
219
  ): Promise<FolderSyncHttpResponse> {
218
- const url = folderSyncHttpUrl(opts.apiUrl);
220
+ const url = opts.url ?? folderSyncHttpUrl(opts.apiUrl);
219
221
  const headers: Record<string, string> = {
220
222
  // OpenAPI route expects application/octet-stream.
221
223
  'Content-Type': 'application/octet-stream',
package/src/index.ts CHANGED
@@ -113,6 +113,10 @@ export {
113
113
  type ExecResult,
114
114
  type ExecChildProcess,
115
115
  type AppStoreEvent,
116
+ type AppStoreConnectInlineKey,
117
+ type AppStoreConnectKey,
118
+ type AppStoreConnectKeySecret,
119
+ type AppStoreConnectTeamKey,
116
120
  type AppStoreUploadConfig,
117
121
  type PlaystoreEvent,
118
122
  type WebhookConfig,
@@ -189,6 +193,11 @@ export {
189
193
  type MacosLaunchMode,
190
194
  type MacosLaunchAppOptions,
191
195
  type MacosLaunchAppResult,
196
+ type MacosInstalledApp,
197
+ type MacosSyncOptions,
198
+ type MacosSyncResult,
199
+ type MacosFileEntry,
200
+ type PullResult,
192
201
  } from './resources/macos-instances-helpers';
193
202
  export { type AssetUploadOptions } from './resources/daemon-client-shared';
194
203
  export {
@@ -1,3 +1,5 @@
1
+ import { assetSourceFields, type AssetSource } from './internal/asset-source';
2
+ export type { AssetSource } from './internal/asset-source';
1
3
  import { WebSocket, Data } from 'ws';
2
4
  import { execFile } from 'node:child_process';
3
5
  import fs from 'fs';
@@ -420,11 +422,15 @@ export type InstanceClient = {
420
422
  /** The names the emulator cannot resolve. */
421
423
  getBlockedDomains: () => Promise<string[]>;
422
424
  /**
423
- * Send an asset URL to the instance. The instance will download the asset
425
+ * Send a URL or { assetName } to the instance. Names require delegated asset read permission.
426
+ * The instance will download the asset
424
427
  * and process it (currently APK install is supported). Resolves on success,
425
428
  * rejects with an Error on failure.
426
429
  */
427
- sendAsset: (url: string, timeoutMs?: number) => Promise<void>;
430
+ sendAsset: (source: AssetSource, timeoutMs?: number) => Promise<void>;
431
+
432
+ /** Install an APK by exact asset name using the instance role. */
433
+ installAppByName: (assetName: string, timeoutMs?: number) => Promise<void>;
428
434
 
429
435
  /**
430
436
  * Delta-sync a local APK to the instance and install it.
@@ -770,15 +776,14 @@ type ScreenshotErrorResponse = {
770
776
  id: string;
771
777
  };
772
778
 
773
- type AssetRequest = {
774
- type: 'asset';
775
- url: string;
776
- };
779
+ type AssetRequest = { type: 'asset'; id: string } & ({ url: string } | { assetName: string });
777
780
 
778
781
  type AssetResultResponse = {
779
782
  type: 'assetResult';
780
783
  result: 'success' | 'failure' | string;
781
- url: string;
784
+ url?: string;
785
+ assetName?: string;
786
+ id?: string;
782
787
  message?: string;
783
788
  };
784
789
 
@@ -1113,7 +1118,7 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
1113
1118
  let intentionalDisconnect = false;
1114
1119
  let lastError: string | undefined;
1115
1120
  const pendingRequests: Map<string, PendingRequest<unknown>> = new Map();
1116
- const pendingAssetRequestsByUrl: Map<string, Array<PendingRequest<void>>> = new Map();
1121
+ const pendingAssetRequests: Map<string, PendingRequest<void> & { url?: string }> = new Map();
1117
1122
  // App exit callbacks are keyed by execId. They intentionally survive transient
1118
1123
  // WebSocket reconnects and are one-shot once a matching appExit is processed.
1119
1124
  const appExitCallbacks: Map<string, LaunchAppExitCallback> = new Map();
@@ -1156,13 +1161,11 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
1156
1161
  request.reject(new Error(reason));
1157
1162
  });
1158
1163
  pendingRequests.clear();
1159
- pendingAssetRequestsByUrl.forEach((requests) => {
1160
- requests.forEach((request) => {
1161
- clearTimeout(request.timeout);
1162
- request.reject(new Error(reason));
1163
- });
1164
+ pendingAssetRequests.forEach((request) => {
1165
+ clearTimeout(request.timeout);
1166
+ request.reject(new Error(reason));
1164
1167
  });
1165
- pendingAssetRequestsByUrl.clear();
1168
+ pendingAssetRequests.clear();
1166
1169
  };
1167
1170
 
1168
1171
  const cleanup = (): void => {
@@ -1434,18 +1437,17 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
1434
1437
  }
1435
1438
  case 'assetResult': {
1436
1439
  logger.debug('Received assetResult:', message);
1437
- const url = message.url as string;
1438
- const queue = pendingAssetRequestsByUrl.get(url);
1439
- if (!queue || queue.length === 0) {
1440
- logger.warn(`Received assetResult for unknown or already handled url: ${message.url}`);
1441
- break;
1440
+ let id = message.id;
1441
+ // Old servers omit id. Only those replies may fall back to the oldest matching URL.
1442
+ if (id === undefined && typeof message.url === 'string') {
1443
+ id = [...pendingAssetRequests].find(([, request]) => request.url === message.url)?.[0];
1442
1444
  }
1443
- const request = queue.shift()!;
1444
- if (queue.length === 0) {
1445
- pendingAssetRequestsByUrl.delete(url);
1446
- } else {
1447
- pendingAssetRequestsByUrl.set(url, queue);
1445
+ const request = typeof id === 'string' ? pendingAssetRequests.get(id) : undefined;
1446
+ if (!request || typeof id !== 'string') {
1447
+ logger.warn('Received assetResult for an unknown or completed request');
1448
+ break;
1448
1449
  }
1450
+ pendingAssetRequests.delete(id);
1449
1451
  clearTimeout(request.timeout);
1450
1452
  if (message.result === 'success') {
1451
1453
  logger.debug('Asset result is success');
@@ -1568,6 +1570,7 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
1568
1570
  setBlockedDomains,
1569
1571
  getBlockedDomains,
1570
1572
  sendAsset,
1573
+ installAppByName: (assetName, timeoutMs) => sendAsset({ assetName }, timeoutMs),
1571
1574
  syncApp,
1572
1575
  getConnectionState,
1573
1576
  onConnectionStateChange,
@@ -2040,53 +2043,29 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
2040
2043
  const getBlockedDomains = (): Promise<string[]> =>
2041
2044
  requestBlockedDomains(androidBlockedDomainsUrl(requireAdbUrl('read blocked domains')), options.token);
2042
2045
 
2043
- const sendAsset = async (url: string, timeoutMs?: number): Promise<void> => {
2046
+ const sendAsset = async (source: AssetSource, timeoutMs?: number): Promise<void> => {
2044
2047
  if (!ws || ws.readyState !== WebSocket.OPEN) {
2045
2048
  return Promise.reject(new Error('WebSocket is not connected or connection is not open.'));
2046
2049
  }
2047
- const assetRequest: AssetRequest = {
2048
- type: 'asset',
2049
- url,
2050
- };
2050
+ const fields = assetSourceFields(source);
2051
+ const id = crypto.randomUUID();
2052
+ const assetRequest: AssetRequest = { type: 'asset', ...fields, id };
2051
2053
  return new Promise<void>((resolve, reject) => {
2052
- let request: PendingRequest<void>;
2053
2054
  const timeout = setTimeout(() => {
2054
- const queue = pendingAssetRequestsByUrl.get(url);
2055
- if (!queue) {
2056
- return;
2057
- }
2058
- const idx = queue.indexOf(request);
2059
- if (idx >= 0) {
2060
- queue.splice(idx, 1);
2061
- reject(new Error(`Request asset timed out for url: ${url}`));
2062
- }
2063
- if (queue.length === 0) {
2064
- pendingAssetRequestsByUrl.delete(url);
2065
- } else {
2066
- pendingAssetRequestsByUrl.set(url, queue);
2055
+ if (pendingAssetRequests.delete(id)) {
2056
+ reject(new Error(`Request asset timed out for id: ${id}`));
2067
2057
  }
2068
2058
  }, timeoutMs ?? 120_000);
2069
- request = {
2059
+ pendingAssetRequests.set(id, {
2070
2060
  resolve,
2071
- reject: (reason: Error) => reject(reason),
2061
+ reject,
2072
2062
  timeout,
2073
- };
2074
- const queue = pendingAssetRequestsByUrl.get(url) ?? [];
2075
- queue.push(request);
2076
- pendingAssetRequestsByUrl.set(url, queue);
2063
+ ...('url' in fields && { url: fields.url }),
2064
+ });
2077
2065
  ws!.send(JSON.stringify(assetRequest), (err?: Error) => {
2078
2066
  if (err) {
2079
2067
  clearTimeout(timeout);
2080
- const queued = pendingAssetRequestsByUrl.get(url) ?? [];
2081
- const idx = queued.indexOf(request);
2082
- if (idx >= 0) {
2083
- queued.splice(idx, 1);
2084
- }
2085
- if (queued.length === 0) {
2086
- pendingAssetRequestsByUrl.delete(url);
2087
- } else {
2088
- pendingAssetRequestsByUrl.set(url, queued);
2089
- }
2068
+ pendingAssetRequests.delete(id);
2090
2069
  logger.error('Failed to send asset request:', err);
2091
2070
  reject(err);
2092
2071
  }
@@ -0,0 +1,13 @@
1
+ /** A download URL, or an asset the instance has delegated permission to read. */
2
+ export type AssetSource = string | { assetName: string; url?: never };
3
+
4
+ export function assetSourceFields(source: AssetSource): { url: string } | { assetName: string } {
5
+ if (typeof source === 'string') {
6
+ if (!source) throw new Error('url must not be empty');
7
+ return { url: source };
8
+ }
9
+ if (!source || typeof source.assetName !== 'string' || !source.assetName || 'url' in source) {
10
+ throw new Error('Provide a URL string or { assetName: <non-empty name> }');
11
+ }
12
+ return { assetName: source.assetName };
13
+ }
@@ -0,0 +1,284 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { Readable } from 'stream';
4
+ import * as zlib from 'zlib';
5
+ import * as tarStream from 'tar-stream';
6
+
7
+ import { nodeProxyTransport } from './proxy-transport';
8
+
9
+ /** The Content-Type of a folder an instance sends as a tar. */
10
+ export const TAR_CONTENT_TYPE = 'application/x-tar';
11
+
12
+ /**
13
+ * The header saying a pull's body is zstd-compressed. A pull asks for it with `compression=zstd`;
14
+ * a server that predates it sends neither. It is not Content-Encoding, so fetch never decodes the
15
+ * body on its own.
16
+ */
17
+ export const COMPRESSION_HEADER = 'x-limrun-compression';
18
+
19
+ // Node has zstd from 22.15; an older Node pulls and pushes uncompressed.
20
+ const zstdCompress = (zlib as any).createZstdCompress as
21
+ | ((options?: object) => NodeJS.ReadWriteStream)
22
+ | undefined;
23
+ const zstdDecompress = (zlib as any).createZstdDecompress as (() => NodeJS.ReadWriteStream) | undefined;
24
+
25
+ /** pullQuery is the query a pull adds to its URL: a folder as a tar, compressed when Node can read it. */
26
+ export function pullQuery(): string {
27
+ return zstdDecompress ? 'archive=tar&compression=zstd' : 'archive=tar';
28
+ }
29
+
30
+ /**
31
+ * pushFile PUTs a local file to `url`, compressed with zstd as it is read when `compress` is set
32
+ * and Node has zstd, and returns the `path` the instance answers with.
33
+ */
34
+ export async function pushFile(
35
+ url: string,
36
+ token: string,
37
+ localPath: string,
38
+ compress: boolean,
39
+ ): Promise<string> {
40
+ const size = (await fs.promises.stat(localPath)).size;
41
+ const file = fs.createReadStream(localPath);
42
+ const zstd =
43
+ compress && zstdCompress ?
44
+ zstdCompress({ params: { [(zlib as any).constants.ZSTD_c_compressionLevel]: 3 } })
45
+ : undefined;
46
+ const headers: Record<string, string> = {
47
+ 'Content-Type': 'application/octet-stream',
48
+ Authorization: `Bearer ${token}`,
49
+ };
50
+ let body: Readable = file;
51
+ if (zstd) {
52
+ headers['Content-Encoding'] = 'zstd';
53
+ file.on('error', (err) => (zstd as any).destroy(err));
54
+ body = file.pipe(zstd) as unknown as Readable;
55
+ } else {
56
+ headers['Content-Length'] = String(size);
57
+ }
58
+ try {
59
+ const response = await nodeProxyTransport.fetch(url, {
60
+ method: 'PUT',
61
+ headers,
62
+ body: body as any,
63
+ duplex: 'half',
64
+ } as any);
65
+ if (!response.ok) {
66
+ const errorBody = await response.text();
67
+ throw new Error(`Upload of '${localPath}' failed: ${response.status} ${errorBody}`);
68
+ }
69
+ return ((await response.json()) as { path: string }).path;
70
+ } finally {
71
+ file.destroy();
72
+ }
73
+ }
74
+
75
+ /** What a pull wrote. */
76
+ export type PullResult = {
77
+ /** The absolute local path of the file or folder written. */
78
+ path: string;
79
+ /** True when the remote was a folder, unpacked into `path`. */
80
+ isDirectory: boolean;
81
+ };
82
+
83
+ /**
84
+ * pullTarget is where a pull of `remote` into `local` writes: `local`, or `remote`'s base name
85
+ * inside it when `local` is an existing folder. Without `local`, the base name in the current
86
+ * directory.
87
+ */
88
+ export async function pullTarget(remote: string, local?: string): Promise<string> {
89
+ const name = path.posix.basename(remote.replace(/\/+$/, ''));
90
+ const nameless = name === '' || name === '.' || name === '..' || name === '~';
91
+ if (local === undefined || local === '') {
92
+ if (nameless)
93
+ throw new Error(`"${remote}" has no name to save it under; pass the local path to write to`);
94
+ return path.resolve(name);
95
+ }
96
+ const target = path.resolve(local);
97
+ const stat = await fs.promises.stat(target).catch(() => null);
98
+ if (!stat?.isDirectory()) return target;
99
+ if (nameless) {
100
+ throw new Error(
101
+ `${target} is a folder and "${remote}" has no name to put inside it; pass the local path to write to`,
102
+ );
103
+ }
104
+ return path.join(target, name);
105
+ }
106
+
107
+ /**
108
+ * pullToLocalPath GETs `url`, whose query ends with {@link pullQuery}, and writes the answer to `target`: a
109
+ * tar is unpacked into the folder `target`, anything else is written to the file `target` through
110
+ * a temporary file renamed into place.
111
+ */
112
+ export async function pullToLocalPath(
113
+ url: string,
114
+ token: string,
115
+ remote: string,
116
+ target: string,
117
+ ): Promise<PullResult> {
118
+ const response = await nodeProxyTransport.fetch(url, {
119
+ method: 'GET',
120
+ headers: { Authorization: `Bearer ${token}` },
121
+ });
122
+ if (!response.ok) {
123
+ const errorBody = await response.text();
124
+ throw new Error(`Pull of '${remote}' failed: ${response.status} ${errorBody}`);
125
+ }
126
+ if (!response.body) throw new Error(`Pull of '${remote}' failed: the response has no body`);
127
+ let source: AsyncIterable<Buffer> = Readable.fromWeb(response.body as any);
128
+ const compression = response.headers.get(COMPRESSION_HEADER);
129
+ if (compression) {
130
+ if (compression !== 'zstd' || !zstdDecompress) {
131
+ throw new Error(
132
+ `Pull of '${remote}' failed: the body is compressed with ${compression}, which this Node cannot read`,
133
+ );
134
+ }
135
+ const raw = source as Readable;
136
+ const decompress = zstdDecompress();
137
+ raw.on('error', (err) => (decompress as any).destroy(err));
138
+ source = raw.pipe(decompress) as unknown as AsyncIterable<Buffer>;
139
+ }
140
+ const mediaType = (response.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase();
141
+ if (mediaType === TAR_CONTENT_TYPE) {
142
+ await fs.promises.mkdir(target, { recursive: true });
143
+ await unpackTar(source, target);
144
+ return { path: target, isDirectory: true };
145
+ }
146
+ await writeFileAtomically(source, target);
147
+ return { path: target, isDirectory: false };
148
+ }
149
+
150
+ async function writeFileAtomically(source: AsyncIterable<Buffer>, target: string): Promise<void> {
151
+ const dir = path.dirname(target);
152
+ await fs.promises.mkdir(dir, { recursive: true });
153
+ const temporary = path.join(
154
+ dir,
155
+ `.lim-pull-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,
156
+ );
157
+ const handle = await fs.promises.open(temporary, 'wx', 0o644);
158
+ try {
159
+ try {
160
+ for await (const chunk of source) await handle.write(chunk);
161
+ } finally {
162
+ await handle.close();
163
+ }
164
+ await fs.promises.rename(temporary, target);
165
+ } catch (err) {
166
+ await fs.promises.rm(temporary, { force: true });
167
+ throw err;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * unpackTar extracts a tar into `dir`, an existing folder. Entries are relative to `dir`: an
173
+ * absolute name or one with a `..` component fails the unpack. Symlinks keep their targets, as tar
174
+ * keeps them, wherever they point: they are created after every file and folder, and nothing is
175
+ * written through a symlink, so a target outside `dir` is never written to. Entries other than
176
+ * files, folders and symlinks are skipped.
177
+ */
178
+ export async function unpackTar(source: AsyncIterable<Buffer>, dir: string): Promise<void> {
179
+ const extract = tarStream.extract();
180
+ const input = Readable.from(source);
181
+ input.on('error', (err) => extract.destroy(err));
182
+ input.pipe(extract);
183
+ const links: { name: string; target: string }[] = [];
184
+ const folders: { path: string; mode: number; mtime: Date | undefined }[] = [];
185
+ try {
186
+ for await (const entry of extract) {
187
+ const header = entry.header;
188
+ const name = entryName(header.name);
189
+ const dst = name === '' ? dir : path.join(dir, ...name.split('/'));
190
+ const mode = (header.mode ?? 0o644) & 0o7777;
191
+ if (header.type === 'file' || header.type === 'contiguous-file') {
192
+ if (name === '') throw new Error('the tar has a file entry for its own folder');
193
+ await makeDirs(dir, path.posix.dirname(name));
194
+ await writeEntry(dst, entry as unknown as AsyncIterable<Buffer>, mode, header.mtime);
195
+ continue;
196
+ }
197
+ entry.resume();
198
+ if (name === '') continue;
199
+ if (header.type === 'directory') {
200
+ await makeDirs(dir, name);
201
+ folders.push({ path: dst, mode, mtime: header.mtime });
202
+ } else if (header.type === 'symlink') {
203
+ if (!header.linkname) throw new Error(`the tar has a symlink "${name}" without a target`);
204
+ links.push({ name, target: header.linkname });
205
+ }
206
+ }
207
+ } finally {
208
+ input.unpipe(extract);
209
+ input.destroy();
210
+ }
211
+
212
+ for (const link of links) {
213
+ await makeDirs(dir, path.posix.dirname(link.name));
214
+ const dst = path.join(dir, ...link.name.split('/'));
215
+ await removeEntry(dst);
216
+ await fs.promises.symlink(link.target, dst);
217
+ }
218
+ // Folders get their modes and times last: writing into them changes their times, and a
219
+ // read-only folder could not be written into.
220
+ for (const folder of folders.reverse()) {
221
+ await fs.promises.chmod(folder.path, folder.mode | 0o700);
222
+ if (folder.mtime) await fs.promises.utimes(folder.path, folder.mtime, folder.mtime).catch(() => {});
223
+ }
224
+ }
225
+
226
+ /** entryName returns an entry's name as a clean relative slash path, '' for the folder itself. */
227
+ function entryName(raw: string): string {
228
+ if (raw.startsWith('/') || path.isAbsolute(raw) || /^[A-Za-z]:/.test(raw)) {
229
+ throw new Error(`the tar has an absolute entry "${raw}"`);
230
+ }
231
+ const parts = raw.split('/');
232
+ if (parts.includes('..') || raw.includes('\\'))
233
+ throw new Error(`the tar has an entry outside its folder: "${raw}"`);
234
+ return parts.filter((part) => part !== '' && part !== '.').join('/');
235
+ }
236
+
237
+ /** makeDirs creates the folders of `rel` under `root` one at a time, refusing links and files. */
238
+ async function makeDirs(root: string, rel: string): Promise<void> {
239
+ if (rel === '' || rel === '.') return;
240
+ let current = root;
241
+ for (const part of rel.split('/')) {
242
+ current = path.join(current, part);
243
+ const stat = await fs.promises.lstat(current).catch((err: NodeJS.ErrnoException) => {
244
+ if (err.code === 'ENOENT') return null;
245
+ throw err;
246
+ });
247
+ if (!stat) {
248
+ await fs.promises.mkdir(current, 0o755);
249
+ } else if (stat.isSymbolicLink()) {
250
+ throw new Error(`refusing to write through the symlink ${current}`);
251
+ } else if (!stat.isDirectory()) {
252
+ throw new Error(`${current} is a file, not a folder`);
253
+ }
254
+ }
255
+ }
256
+
257
+ /** removeEntry removes a file or symlink so a new entry replaces it rather than writing through it. */
258
+ async function removeEntry(dst: string): Promise<void> {
259
+ const stat = await fs.promises.lstat(dst).catch((err: NodeJS.ErrnoException) => {
260
+ if (err.code === 'ENOENT') return null;
261
+ throw err;
262
+ });
263
+ if (!stat) return;
264
+ if (stat.isDirectory()) throw new Error(`${dst} is a folder, not a file`);
265
+ await fs.promises.rm(dst);
266
+ }
267
+
268
+ async function writeEntry(
269
+ dst: string,
270
+ chunks: AsyncIterable<Buffer>,
271
+ mode: number,
272
+ mtime: Date | undefined,
273
+ ): Promise<void> {
274
+ await removeEntry(dst);
275
+ // 'wx' fails rather than follow a symlink that appeared at dst.
276
+ const handle = await fs.promises.open(dst, 'wx', mode | 0o200);
277
+ try {
278
+ for await (const chunk of chunks) await handle.write(chunk);
279
+ } finally {
280
+ await handle.close();
281
+ }
282
+ if ((mode & 0o200) === 0) await fs.promises.chmod(dst, mode);
283
+ if (mtime) await fs.promises.utimes(dst, mtime, mtime).catch(() => {});
284
+ }