@uru-intelligence/app 2.2.1 → 2.2.5

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/uploads.js CHANGED
@@ -114,6 +114,8 @@ function grantFrom(value) {
114
114
  for (const [name, headerValue] of Object.entries(headers)) {
115
115
  requiredHeaders[name] = string(headerValue);
116
116
  }
117
+ if (requiredHeaders['if-none-match'] !== '*')
118
+ invalid();
117
119
  return {
118
120
  uploadId,
119
121
  uploadUrl,
@@ -148,6 +150,34 @@ function resultFrom(value) {
148
150
  cleanupFailed: row['cleanupFailed'] === true,
149
151
  };
150
152
  }
153
+ function statusFrom(value) {
154
+ const row = object(value);
155
+ const state = string(row['state']);
156
+ const outcome = row['outcome'];
157
+ const sizeBytes = row['sizeBytes'];
158
+ if (!UUID.test(string(row['uploadId'])) ||
159
+ !['granted', 'verified', 'rejected', 'expired'].includes(state) ||
160
+ (outcome !== null && (typeof outcome !== 'string' || !OUTCOMES.includes(outcome))) ||
161
+ (sizeBytes !== null && (typeof sizeBytes !== 'number' || !Number.isSafeInteger(sizeBytes))) ||
162
+ typeof row['cleanupFailed'] !== 'boolean')
163
+ invalid();
164
+ return {
165
+ uploadId: string(row['uploadId']),
166
+ state: state,
167
+ outcome: outcome,
168
+ filename: string(row['filename']),
169
+ contentType: string(row['contentType']),
170
+ sizeBytes: sizeBytes,
171
+ expiresAt: string(row['expiresAt']),
172
+ cleanupFailed: row['cleanupFailed'],
173
+ };
174
+ }
175
+ function requestKey(value) {
176
+ const key = value.trim();
177
+ if (key.trim().length < 1 || key.trim().length > 128)
178
+ invalid();
179
+ return key.trim();
180
+ }
151
181
  /**
152
182
  * Read the response body into a `Blob`, refusing anything above the platform's
153
183
  * own per-file ceiling.
@@ -196,10 +226,48 @@ export function createUploadsContext(options) {
196
226
  // costs nothing on a runtime whose `fetch` arrives later, and so the global
197
227
  // is always called with the global as its receiver.
198
228
  const doFetch = async (...args) => await resolveRuntimeFetch(options)(...args);
199
- const post = async (path, payload, signal) => {
229
+ const generatedRequestKeys = new Map();
230
+ const generatedFileIds = new WeakMap();
231
+ const fileFingerprint = (file, contentType) => {
232
+ let fileId = generatedFileIds.get(file);
233
+ if (fileId === undefined) {
234
+ fileId = globalThis.crypto.randomUUID();
235
+ generatedFileIds.set(file, fileId);
236
+ }
237
+ return JSON.stringify([
238
+ fileId,
239
+ file.name,
240
+ contentType,
241
+ file.size,
242
+ typeof file.lastModified === 'number' ? file.lastModified : 0,
243
+ ]);
244
+ };
245
+ const keyFor = (value, fingerprint) => {
246
+ if (value !== undefined)
247
+ return { key: requestKey(value), generated: false };
248
+ const existing = generatedRequestKeys.get(fingerprint);
249
+ if (existing !== undefined)
250
+ return { key: existing, generated: true };
251
+ const key = requestKey(globalThis.crypto.randomUUID());
252
+ if (generatedRequestKeys.size >= 128) {
253
+ const oldest = generatedRequestKeys.keys().next().value;
254
+ if (typeof oldest === 'string')
255
+ generatedRequestKeys.delete(oldest);
256
+ }
257
+ generatedRequestKeys.set(fingerprint, key);
258
+ return { key, generated: true };
259
+ };
260
+ const forgetGeneratedKey = (fingerprint, key) => {
261
+ if (generatedRequestKeys.get(fingerprint) === key) {
262
+ generatedRequestKeys.delete(fingerprint);
263
+ }
264
+ };
265
+ const post = async (path, payload, signal, idempotencyKey) => {
200
266
  const headers = new Headers(await resolveHeaders(options.headers));
201
267
  if (payload !== undefined)
202
268
  headers.set('content-type', 'application/json');
269
+ if (idempotencyKey !== undefined)
270
+ headers.set('Idempotency-Key', idempotencyKey);
203
271
  const response = await doFetch(`${base}${path}`, {
204
272
  method: 'POST',
205
273
  headers,
@@ -209,15 +277,23 @@ export function createUploadsContext(options) {
209
277
  : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
210
278
  });
211
279
  if (!response.ok) {
212
- await response.body?.cancel();
280
+ // The answer's body goes with the error, null when it is not JSON. The
281
+ // job runner reads its error code: a 500 with Uru's code ends the job,
282
+ // and a 500 with none came from an edge, so a retry-safe job gets its
283
+ // next attempt.
284
+ const body = await readJson(response).catch(() => null);
213
285
  throw new UruAppRuntimeError('Upload request was not accepted.', {
214
286
  status: response.status,
215
- body: null,
287
+ body,
216
288
  });
217
289
  }
218
290
  return readJson(response);
219
291
  };
220
- const request = async (input) => {
292
+ const requestResponse = async (input, fingerprint = JSON.stringify([
293
+ input.filename,
294
+ input.contentType,
295
+ input.sizeBytes,
296
+ ])) => {
221
297
  if (typeof input.filename !== 'string' ||
222
298
  input.filename.trim().length < 1 ||
223
299
  input.filename.length > 255 ||
@@ -229,12 +305,29 @@ export function createUploadsContext(options) {
229
305
  input.sizeBytes > URU_UPLOAD_MAX_BYTES) {
230
306
  invalid();
231
307
  }
232
- return grantFrom(await post('', {
233
- filename: input.filename,
234
- contentType: input.contentType,
235
- sizeBytes: input.sizeBytes,
236
- }, input.signal));
308
+ const { key, generated } = keyFor(input.idempotencyKey, fingerprint);
309
+ return {
310
+ row: object(await post('', {
311
+ filename: input.filename,
312
+ contentType: input.contentType,
313
+ sizeBytes: input.sizeBytes,
314
+ }, input.signal, key)),
315
+ key,
316
+ generated,
317
+ fingerprint,
318
+ };
319
+ };
320
+ const request = async (input) => {
321
+ const response = await requestResponse(input);
322
+ if (response.row['state'] !== undefined && response.row['state'] !== 'granted') {
323
+ throw new UruAppRuntimeError('This upload request is finished. Read its saved status with the same request key.', { status: 409, body: null });
324
+ }
325
+ const grant = grantFrom(response.row);
326
+ if (response.generated)
327
+ forgetGeneratedKey(response.fingerprint, response.key);
328
+ return grant;
237
329
  };
330
+ const status = async (idempotencyKey, options) => statusFrom(await post('/status', undefined, options?.signal, requestKey(idempotencyKey)));
238
331
  const complete = async (uploadId, settings) => {
239
332
  if (typeof uploadId !== 'string' || !UUID.test(uploadId))
240
333
  invalid();
@@ -254,16 +347,18 @@ export function createUploadsContext(options) {
254
347
  : AbortSignal.any([settings.signal, AbortSignal.timeout(300_000)]),
255
348
  });
256
349
  if (!response.ok) {
257
- await response.body?.cancel();
350
+ // Uru's answer, not the file: its body goes with the error, as above.
351
+ const body = await readJson(response).catch(() => null);
258
352
  throw new UruAppRuntimeError('Upload could not be read.', {
259
353
  status: response.status,
260
- body: null,
354
+ body,
261
355
  });
262
356
  }
263
357
  return readBlob(response);
264
358
  };
265
359
  return {
266
360
  request,
361
+ status,
267
362
  complete,
268
363
  read,
269
364
  upload: async (file, settings) => {
@@ -275,30 +370,79 @@ export function createUploadsContext(options) {
275
370
  const contentType = typeof file.type === 'string' && file.type.trim() !== ''
276
371
  ? file.type
277
372
  : 'application/octet-stream';
278
- const grant = await request({
373
+ const response = await requestResponse({
279
374
  filename: file.name,
280
375
  contentType,
281
376
  sizeBytes: file.size,
377
+ ...(settings?.idempotencyKey === undefined
378
+ ? {}
379
+ : { idempotencyKey: settings.idempotencyKey }),
282
380
  ...(settings?.signal === undefined ? {} : { signal: settings.signal }),
283
- });
284
- const put = await doFetch(grant.uploadUrl, {
285
- method: 'PUT',
286
- // Exactly the headers the grant was SIGNED with. Adding or altering one
287
- // changes the canonical request the provider rebuilds, and the PUT is
288
- // refused with a signature error that names nothing.
289
- headers: new Headers(grant.requiredHeaders),
290
- body: file,
291
- ...(settings?.signal === undefined ? {} : { signal: settings.signal }),
292
- });
381
+ }, fileFingerprint(file, contentType));
382
+ const row = response.row;
383
+ if (row['state'] === 'verified' ||
384
+ row['state'] === 'rejected' ||
385
+ row['state'] === 'expired') {
386
+ // A prior call may have finished after its response was lost. The
387
+ // completion read is idempotent and returns the stored verdict.
388
+ const result = await complete(string(row['uploadId']), settings);
389
+ if (response.generated)
390
+ forgetGeneratedKey(response.fingerprint, response.key);
391
+ return result;
392
+ }
393
+ const grant = grantFrom(row);
394
+ const completeIfStored = async () => {
395
+ if (settings?.signal?.aborted === true)
396
+ return null;
397
+ try {
398
+ const recovered = await complete(grant.uploadId, settings);
399
+ return recovered.state === 'granted' && recovered.outcome === 'pending'
400
+ ? null
401
+ : recovered;
402
+ }
403
+ catch {
404
+ return null;
405
+ }
406
+ };
407
+ let put;
408
+ try {
409
+ put = await doFetch(grant.uploadUrl, {
410
+ method: 'PUT',
411
+ // Exactly the headers the grant was SIGNED with. Adding or altering one
412
+ // changes the canonical request the provider rebuilds, and the PUT is
413
+ // refused with a signature error that names nothing.
414
+ headers: new Headers(grant.requiredHeaders),
415
+ body: file,
416
+ ...(settings?.signal === undefined ? {} : { signal: settings.signal }),
417
+ });
418
+ }
419
+ catch (error) {
420
+ const recovered = await completeIfStored();
421
+ if (recovered !== null) {
422
+ if (response.generated)
423
+ forgetGeneratedKey(response.fingerprint, response.key);
424
+ return recovered;
425
+ }
426
+ throw error;
427
+ }
293
428
  if (!put.ok) {
294
429
  await put.body?.cancel();
430
+ const recovered = await completeIfStored();
431
+ if (recovered !== null) {
432
+ if (response.generated)
433
+ forgetGeneratedKey(response.fingerprint, response.key);
434
+ return recovered;
435
+ }
295
436
  throw new UruAppRuntimeError('Upload was refused by object storage.', {
296
437
  status: put.status,
297
438
  body: null,
298
439
  });
299
440
  }
300
441
  await put.body?.cancel();
301
- return complete(grant.uploadId, settings?.signal === undefined ? undefined : { signal: settings.signal });
442
+ const result = await complete(grant.uploadId, settings?.signal === undefined ? undefined : { signal: settings.signal });
443
+ if (response.generated)
444
+ forgetGeneratedKey(response.fingerprint, response.key);
445
+ return result;
302
446
  },
303
447
  };
304
448
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.2.1",
3
+ "version": "2.2.5",
4
4
  "private": false,
5
5
  "description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
6
6
  "keywords": [
@@ -28,11 +28,34 @@
28
28
  "sideEffects": false,
29
29
  "main": "./dist/index.js",
30
30
  "types": "./dist/index.d.ts",
31
+ "typesVersions": {
32
+ "*": {
33
+ "examples/customer-workflows/*": [
34
+ "dist/examples/customer-workflows/*"
35
+ ]
36
+ }
37
+ },
31
38
  "exports": {
32
39
  ".": {
33
40
  "types": "./dist/index.d.ts",
34
41
  "default": "./dist/index.js"
35
42
  },
43
+ "./examples/customer-workflows/scheduled-collector": {
44
+ "types": "./dist/examples/customer-workflows/scheduled-collector.d.ts",
45
+ "default": "./dist/examples/customer-workflows/scheduled-collector.js"
46
+ },
47
+ "./examples/customer-workflows/review-only-draft": {
48
+ "types": "./dist/examples/customer-workflows/review-only-draft.d.ts",
49
+ "default": "./dist/examples/customer-workflows/review-only-draft.js"
50
+ },
51
+ "./examples/customer-workflows/file-processor": {
52
+ "types": "./dist/examples/customer-workflows/file-processor.d.ts",
53
+ "default": "./dist/examples/customer-workflows/file-processor.js"
54
+ },
55
+ "./examples/customer-workflows/approved-external-write": {
56
+ "types": "./dist/examples/customer-workflows/approved-external-write.d.ts",
57
+ "default": "./dist/examples/customer-workflows/approved-external-write.js"
58
+ },
36
59
  "./package.json": "./package.json"
37
60
  },
38
61
  "publishConfig": {
@@ -40,16 +63,18 @@
40
63
  "provenance": false
41
64
  },
42
65
  "scripts": {
43
- "build": "tsc -p tsconfig.build.json",
66
+ "build": "tsc -p tsconfig.build.json && tsc -p tsconfig.examples.build.json",
44
67
  "clean": "rm -rf dist",
45
68
  "prepack": "bun run clean && bun run build",
46
- "type-check": "tsc --noEmit",
47
- "lint": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts .",
69
+ "type-check": "tsc --noEmit && tsc -p tsconfig.examples.json --noEmit",
70
+ "lint": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts . && node ../../scripts/checks/check-bun-test-integrity.mjs",
48
71
  "lint:fix": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts --fix .",
49
- "test": "bun test",
50
- "test:unit": "bun test",
72
+ "test": "bun run test:safety",
73
+ "test:unit": "bun run test:safety",
74
+ "test:safety": "node ../../scripts/ci/run-named-test-files.mjs bun test --files-from test-lists/test-safety.txt",
51
75
  "check:package": "node ../../scripts/checks/check-app-package-publishable.mjs",
52
- "check:node-floor": "node ../../scripts/checks/check-app-package-node-floor.mjs"
76
+ "check:node-floor": "node ../../scripts/checks/check-app-package-node-floor.mjs",
77
+ "test:focused": "node ../../scripts/ci/run-named-test-files.mjs bun test --files"
53
78
  },
54
79
  "devDependencies": {
55
80
  "@types/node": "24.13.3",