@uru-intelligence/app 1.0.0 → 2.1.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/types.d.ts CHANGED
@@ -9,12 +9,17 @@
9
9
  * the barrel. Publishing turns barrel exports into permanent promises, so the
10
10
  * cycle was broken instead of documented.
11
11
  *
12
- * The only edge out of this module is a type-only import of the damper options
13
- * from `./dampers.js`, which imports nothing.
12
+ * All imports are type-only. JSON values belong to the HTTP edge, not to a
13
+ * domain model's inheritance hierarchy.
14
14
  */
15
- import type { UruRunawayDamperOptions } from './dampers.js';
15
+ import type { UruRunawayDamperOptions } from "./dampers.js";
16
+ import type { RuntimeJsonObject, RuntimeJsonValue } from "./transport-json.js";
17
+ /** Parse an untrusted result. Throw when the value does not match its model. */
18
+ export type UruResultDecoder<TResult> = (value: unknown) => TResult;
19
+ /** Transport only calls fetch; runtime-specific properties are not required. */
20
+ type RuntimeFetch = (...args: Parameters<typeof fetch>) => ReturnType<typeof fetch>;
16
21
  /** The kinds of capability a Uru app can declare and this client can invoke. */
17
- export type UruAppRuntimeCapabilityType = 'query' | 'action' | 'job' | 'endpoint' | 'server_function';
22
+ export type UruAppRuntimeCapabilityType = "query" | "action" | "job" | "endpoint" | "server_function";
18
23
  /**
19
24
  * Normalized lifecycle state of one invocation.
20
25
  *
@@ -22,15 +27,15 @@ export type UruAppRuntimeCapabilityType = 'query' | 'action' | 'job' | 'endpoint
22
27
  * may add a state before this package knows about it, and a client that threw
23
28
  * on an unrecognised state would break on a backend deploy.
24
29
  */
25
- export type UruAppRuntimeState = 'idle' | 'queued' | 'running' | 'polling' | 'cached' | 'stale' | 'refreshing' | 'refreshed' | 'succeeded' | 'failed' | 'rate_limited' | 'budget_blocked' | 'service_unavailable' | 'canceled';
30
+ export type UruAppRuntimeState = "idle" | "queued" | "running" | "polling" | "cached" | "stale" | "refreshing" | "refreshed" | "succeeded" | "failed" | "rate_limited" | "budget_blocked" | "service_unavailable" | "canceled";
26
31
  /** Lifecycle transitions reported to `onEvent` / `onStatus`. */
27
- export type UruAppRuntimeEventType = 'started' | 'status' | 'completed' | 'failed' | 'canceled';
32
+ export type UruAppRuntimeEventType = "started" | "status" | "completed" | "failed" | "canceled";
28
33
  /** One lifecycle notification for an in-flight invocation. */
29
34
  export interface UruAppRuntimeEvent<TResult = unknown> {
30
35
  type: UruAppRuntimeEventType;
31
- state: UruAppRuntimeState | string;
36
+ state: string;
32
37
  deploymentId: string;
33
- capabilityType?: UruAppRuntimeCapabilityType | string | undefined;
38
+ capabilityType?: string | undefined;
34
39
  capabilityName?: string | undefined;
35
40
  executionId?: string | null | undefined;
36
41
  requestId?: string | null | undefined;
@@ -38,7 +43,7 @@ export interface UruAppRuntimeEvent<TResult = unknown> {
38
43
  error?: string | null | undefined;
39
44
  retryAfterSeconds?: number | null | undefined;
40
45
  cacheStatus?: string | null | undefined;
41
- diagnostics?: Record<string, unknown> | undefined;
46
+ diagnostics?: RuntimeJsonObject | undefined;
42
47
  }
43
48
  /** Per-call options accepted by every capability method. */
44
49
  export interface UruAppRuntimeInvocationOptions {
@@ -48,19 +53,24 @@ export interface UruAppRuntimeInvocationOptions {
48
53
  requestId?: string;
49
54
  onEvent?: (event: UruAppRuntimeEvent) => void;
50
55
  onStatus?: (event: UruAppRuntimeEvent) => void;
56
+ decodeResult?: UruResultDecoder<unknown>;
57
+ }
58
+ /** A typed result requires runtime proof supplied by the caller. */
59
+ export interface UruDecodedInvocationOptions<TResult> extends UruAppRuntimeInvocationOptions {
60
+ decodeResult: UruResultDecoder<TResult>;
51
61
  }
52
62
  /** The normalized envelope every capability invocation resolves to. */
53
63
  export interface UruAppRuntimeInvocationResponse<TResult = unknown> {
54
64
  ok: boolean;
55
- status: 'succeeded' | 'running' | 'failed' | string;
56
- state: UruAppRuntimeState | string;
65
+ status: string;
66
+ state: string;
57
67
  deploymentId: string;
58
- capabilityType: UruAppRuntimeCapabilityType | string;
68
+ capabilityType: string;
59
69
  capabilityName: string;
60
70
  result?: TResult | null;
61
71
  executionId?: string | null;
62
72
  pending: boolean;
63
- diagnostics: Record<string, unknown>;
73
+ diagnostics: RuntimeJsonObject;
64
74
  }
65
75
  /** The normalized envelope a job-status poll resolves to. */
66
76
  export interface UruAppRuntimeExecutionStatus<TResult = unknown> {
@@ -68,7 +78,7 @@ export interface UruAppRuntimeExecutionStatus<TResult = unknown> {
68
78
  pending?: boolean;
69
79
  result?: TResult | null;
70
80
  error?: string | null;
71
- state?: UruAppRuntimeState | string;
81
+ state?: string;
72
82
  status?: string | null;
73
83
  executionId?: string | null;
74
84
  statusUrl?: string | null;
@@ -77,28 +87,45 @@ export interface UruAppRuntimeExecutionStatus<TResult = unknown> {
77
87
  executor?: string | null;
78
88
  executorKind?: string | null;
79
89
  }
90
+ /** Input is untrusted until the transport validates it as a JSON object. */
91
+ export interface UruCapabilityInvoker {
92
+ <TResult>(name: string, input: unknown, options: UruDecodedInvocationOptions<TResult>): Promise<UruAppRuntimeInvocationResponse<TResult>>;
93
+ (name: string, input?: unknown, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse>;
94
+ }
95
+ export interface UruJobStatusInvoker {
96
+ <TResult>(executionId: string, options: UruDecodedInvocationOptions<TResult>): Promise<UruAppRuntimeExecutionStatus<TResult>>;
97
+ (executionId: string, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeExecutionStatus>;
98
+ }
99
+ export interface UruCancelJobInvoker {
100
+ <TResult>(executionId: string, options: UruDecodedInvocationOptions<TResult>): Promise<UruAppRuntimeInvocationResponse<TResult>>;
101
+ (executionId: string, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse>;
102
+ }
103
+ export interface UruActionInvoker {
104
+ <TResult>(name: string, input: unknown, options: UruDecodedInvocationOptions<TResult>): Promise<TResult | null | undefined>;
105
+ (name: string, input?: unknown, options?: UruAppRuntimeInvocationOptions): Promise<unknown>;
106
+ }
80
107
  /** The capability-invocation client returned by `createUruAppRuntimeClient`. */
81
108
  export interface UruAppRuntimeClient {
82
- query<TResult = unknown>(name: string, input?: Record<string, unknown>, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse<TResult>>;
83
- action<TResult = unknown>(name: string, input?: Record<string, unknown>, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse<TResult>>;
84
- job<TResult = unknown>(name: string, input?: Record<string, unknown>, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse<TResult>>;
85
- endpoint<TResult = unknown>(name: string, input?: Record<string, unknown>, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse<TResult>>;
86
- serverFunction<TResult = unknown>(name: string, input?: Record<string, unknown>, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse<TResult>>;
87
- jobStatus<TResult = unknown>(executionId: string, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeExecutionStatus<TResult>>;
88
- cancelJob(executionId: string, options?: UruAppRuntimeInvocationOptions): Promise<UruAppRuntimeInvocationResponse>;
109
+ query: UruCapabilityInvoker;
110
+ action: UruCapabilityInvoker;
111
+ job: UruCapabilityInvoker;
112
+ endpoint: UruCapabilityInvoker;
113
+ serverFunction: UruCapabilityInvoker;
114
+ jobStatus: UruJobStatusInvoker;
115
+ cancelJob: UruCancelJobInvoker;
89
116
  }
90
117
  /** Comparison operators accepted by a Dataset `where` clause. */
91
- export type UruDatasetWhereOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'ilike' | 'in' | 'nin' | 'is_null';
118
+ export type UruDatasetWhereOperator = "eq" | "neq" | "ne" | "gt" | "gte" | "lt" | "lte" | "ilike" | "in" | "nin" | "not_in" | "is_null";
92
119
  /** One server-side filter condition. */
93
120
  export interface UruDatasetWhereClause {
94
121
  field: string;
95
- op: UruDatasetWhereOperator | string;
96
- value?: unknown;
122
+ op: string;
123
+ value?: RuntimeJsonValue;
97
124
  }
98
125
  /** One server-side sort condition. */
99
126
  export interface UruDatasetSortClause {
100
127
  field: string;
101
- direction: 'asc' | 'desc';
128
+ direction: "asc" | "desc";
102
129
  }
103
130
  /**
104
131
  * A server-side Dataset read.
@@ -114,21 +141,25 @@ export interface UruDatasetQuery {
114
141
  includeDeleted?: boolean;
115
142
  select?: readonly string[];
116
143
  search?: string;
117
- filter?: Record<string, unknown>;
144
+ filter?: RuntimeJsonObject;
118
145
  where?: readonly UruDatasetWhereClause[];
119
146
  sort?: readonly UruDatasetSortClause[];
120
- aggregate?: Record<string, unknown>;
147
+ aggregate?: RuntimeJsonObject;
121
148
  before?: string;
122
149
  cursor?: string;
123
150
  }
124
151
  /** One page of Dataset rows, plus the total when `includeTotal` asked for it. */
125
- export interface UruDatasetRowsResult<TRow extends Record<string, unknown> = Record<string, unknown>> {
152
+ export interface UruDatasetRowsResult<TRow = UruDatasetRow> {
126
153
  rows: TRow[];
127
154
  total?: number | null;
128
- source_meta?: Record<string, unknown> | null;
155
+ limit?: number;
156
+ offset?: number;
157
+ aggregates?: RuntimeJsonObject | null;
158
+ nextCursor?: string | null;
159
+ sourceMeta?: RuntimeJsonObject | null;
129
160
  }
130
- /** One Dataset row. Column types are the Dataset's, so values stay `unknown`. */
131
- export type UruDatasetRow = Record<string, unknown>;
161
+ /** One validated wire row. A caller can decode it into a domain model. */
162
+ export type UruDatasetRow = RuntimeJsonObject;
132
163
  /** The envelope every Dataset write resolves to. */
133
164
  export interface UruDatasetMutationResult<TResult = unknown> {
134
165
  ok: boolean;
@@ -136,7 +167,7 @@ export interface UruDatasetMutationResult<TResult = unknown> {
136
167
  deploymentId?: string;
137
168
  datasetId?: string | null;
138
169
  result: TResult;
139
- diagnostics?: Record<string, unknown>;
170
+ diagnostics?: RuntimeJsonObject;
140
171
  }
141
172
  /** Bounds and targets for a `datasets.sqlWrite` statement. */
142
173
  export interface UruDatasetSqlWriteOptions {
@@ -151,24 +182,138 @@ export interface UruDatasetSqlWriteOptions {
151
182
  maxAffected?: number;
152
183
  timeoutMs?: number;
153
184
  }
185
+ export interface UruDatasetQueryRows {
186
+ <TRow>(datasetRef: string, query: UruDatasetQuery | undefined, decodeRow: UruResultDecoder<TRow>): Promise<UruDatasetRowsResult<TRow>>;
187
+ (datasetRef: string, query?: UruDatasetQuery): Promise<UruDatasetRowsResult>;
188
+ }
189
+ export interface UruDatasetRowMutation {
190
+ <TResult>(datasetRef: string, rows: readonly unknown[], decodeResult: UruResultDecoder<TResult>): Promise<UruDatasetMutationResult<TResult>>;
191
+ (datasetRef: string, rows: readonly unknown[]): Promise<UruDatasetMutationResult>;
192
+ }
193
+ export interface UruDatasetIdMutation {
194
+ <TResult>(datasetRef: string, rowIds: readonly string[], decodeResult: UruResultDecoder<TResult>): Promise<UruDatasetMutationResult<TResult>>;
195
+ (datasetRef: string, rowIds: readonly string[]): Promise<UruDatasetMutationResult>;
196
+ }
197
+ export interface UruDatasetSqlWrite {
198
+ <TResult>(sql: string, options: UruDatasetSqlWriteOptions, decodeResult: UruResultDecoder<TResult>): Promise<UruDatasetMutationResult<TResult>>;
199
+ (sql: string, options: UruDatasetSqlWriteOptions): Promise<UruDatasetMutationResult>;
200
+ }
154
201
  /** The Dataset read/write surface hung off a server context. */
155
202
  export interface UruDatasetsContext {
156
- queryRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(datasetRef: string, query?: UruDatasetQuery) => Promise<UruDatasetRowsResult<TRow>>;
157
- insertRows: <TResult = unknown>(datasetRef: string, rows: readonly UruDatasetRow[]) => Promise<UruDatasetMutationResult<TResult>>;
158
- upsertRows: <TResult = unknown>(datasetRef: string, rows: readonly UruDatasetRow[]) => Promise<UruDatasetMutationResult<TResult>>;
159
- deleteRows: <TResult = unknown>(datasetRef: string, rowIds: readonly string[]) => Promise<UruDatasetMutationResult<TResult>>;
160
- restoreRows: <TResult = unknown>(datasetRef: string, rowIds: readonly string[]) => Promise<UruDatasetMutationResult<TResult>>;
161
- sqlWrite: <TResult = unknown>(sql: string, options: UruDatasetSqlWriteOptions) => Promise<UruDatasetMutationResult<TResult>>;
203
+ queryRows: UruDatasetQueryRows;
204
+ insertRows: UruDatasetRowMutation;
205
+ upsertRows: UruDatasetRowMutation;
206
+ deleteRows: UruDatasetIdMutation;
207
+ restoreRows: UruDatasetIdMutation;
208
+ sqlWrite: UruDatasetSqlWrite;
209
+ }
210
+ export interface UruFileMetadata {
211
+ readonly fileId: string;
212
+ readonly filename: string;
213
+ readonly contentType: string;
214
+ readonly sizeBytes: number;
215
+ readonly sha256: string;
216
+ }
217
+ export interface UruFileContent extends UruFileMetadata {
218
+ readonly content: Uint8Array;
219
+ }
220
+ export interface UruFileOutput extends UruFileMetadata {
221
+ readonly outputId: string;
222
+ readonly createdAt: string;
223
+ }
224
+ export interface UruFileOutputSummary extends UruFileOutput {
225
+ readonly releaseId: string | null;
226
+ readonly buildId: string | null;
227
+ }
228
+ export interface UruFilesContext {
229
+ read(fileId: string, options?: {
230
+ signal?: AbortSignal;
231
+ }): Promise<UruFileContent>;
232
+ readOutput(outputId: string, options?: {
233
+ signal?: AbortSignal;
234
+ }): Promise<UruFileContent>;
235
+ createOutput(input: {
236
+ name: string;
237
+ contentType: string;
238
+ content: Uint8Array;
239
+ idempotencyKey: string;
240
+ sha256?: string;
241
+ signal?: AbortSignal;
242
+ }): Promise<UruFileOutput>;
243
+ listOutputs(options?: {
244
+ cursor?: string;
245
+ limit?: number;
246
+ signal?: AbortSignal;
247
+ }): Promise<{
248
+ items: readonly UruFileOutputSummary[];
249
+ nextCursor: string | null;
250
+ }>;
251
+ }
252
+ /** Every conclusion the platform can reach about one upload. */
253
+ export type UruUploadOutcome = "verified" | "pending" | "absent" | "expired" | "unverifiable" | "size_mismatch" | "type_mismatch";
254
+ /**
255
+ * A minted grant. `uploadUrl` is a CREDENTIAL: do not log it or store it.
256
+ *
257
+ * `requiredHeaders` is not advice. The provider rebuilds the signature from
258
+ * what actually arrives, so a PUT that omits or alters either header is
259
+ * refused.
260
+ */
261
+ export interface UruUploadGrant {
262
+ readonly uploadId: string;
263
+ readonly uploadUrl: string;
264
+ readonly method: "PUT";
265
+ readonly requiredHeaders: Readonly<Record<string, string>>;
266
+ readonly filename: string;
267
+ readonly contentType: string;
268
+ readonly sizeBytes: number;
269
+ readonly expiresAt: string;
270
+ }
271
+ /** The verdict a completion reached. */
272
+ export interface UruUploadResult {
273
+ readonly uploadId: string;
274
+ readonly state: "granted" | "verified" | "rejected" | "expired";
275
+ readonly outcome: UruUploadOutcome;
276
+ readonly filename: string;
277
+ readonly contentType: string;
278
+ /** The VERIFIED byte count, or `null` when the object was not admitted. */
279
+ readonly sizeBytes: number | null;
280
+ /** True only when a refused object could not be removed from storage. */
281
+ readonly cleanupFailed: boolean;
282
+ }
283
+ /** The file-upload lane a Gem gets with the `storage` capability. */
284
+ export interface UruUploadsContext {
285
+ request(input: {
286
+ filename: string;
287
+ contentType: string;
288
+ sizeBytes: number;
289
+ signal?: AbortSignal;
290
+ }): Promise<UruUploadGrant>;
291
+ complete(uploadId: string, options?: {
292
+ signal?: AbortSignal;
293
+ }): Promise<UruUploadResult>;
294
+ /** Request, PUT and complete in one call. What almost every caller wants. */
295
+ upload(file: File, options?: {
296
+ signal?: AbortSignal;
297
+ }): Promise<UruUploadResult>;
298
+ }
299
+ export interface UruJobProgress {
300
+ readonly completed: number;
301
+ readonly total?: number;
302
+ readonly message?: string;
162
303
  }
304
+ export type UruJobCheckpoint = RuntimeJsonObject;
163
305
  /** Everything a Uru server runtime hands an app. */
164
306
  export interface UruServerContext {
307
+ files: UruFilesContext;
165
308
  datasets: UruDatasetsContext;
166
309
  app: UruAppRuntimeClient;
167
310
  actions: {
168
- run: <TResult = unknown>(name: string, input?: Record<string, unknown>, options?: UruAppRuntimeInvocationOptions) => Promise<TResult>;
311
+ run: UruActionInvoker;
169
312
  };
170
313
  jobs: {
171
- start: <TResult = unknown>(name: string, input?: Record<string, unknown>, options?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse<TResult>>;
314
+ start: UruCapabilityInvoker;
315
+ progress: (progress: UruJobProgress) => Promise<void>;
316
+ checkpoint: (value: UruJobCheckpoint) => Promise<void>;
172
317
  };
173
318
  secrets: {
174
319
  has: (name: string) => boolean;
@@ -190,7 +335,7 @@ export interface UruProviderRuntimeEnvironment {
190
335
  /** Options for `createUruServerContext`. */
191
336
  export interface CreateUruServerContextOptions {
192
337
  /** Override the `fetch` used for every call. Defaults to `globalThis.fetch`. */
193
- fetch?: typeof fetch;
338
+ fetch?: RuntimeFetch;
194
339
  }
195
340
  /** Options for `createUruAppRuntimeClient`. */
196
341
  export interface CreateUruAppRuntimeClientOptions {
@@ -199,7 +344,7 @@ export interface CreateUruAppRuntimeClientOptions {
199
344
  runtimeBasePath?: string;
200
345
  publicPageSlug?: string;
201
346
  providerRuntime?: boolean;
202
- fetch?: typeof fetch;
347
+ fetch?: RuntimeFetch;
203
348
  headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
204
349
  /**
205
350
  * Client-side runaway dampers (P2 cost-safety). Every field defaults; pass
@@ -209,3 +354,4 @@ export interface CreateUruAppRuntimeClientOptions {
209
354
  */
210
355
  dampers?: UruRunawayDamperOptions;
211
356
  }
357
+ export {};
package/dist/types.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * the barrel. Publishing turns barrel exports into permanent promises, so the
10
10
  * cycle was broken instead of documented.
11
11
  *
12
- * The only edge out of this module is a type-only import of the damper options
13
- * from `./dampers.js`, which imports nothing.
12
+ * All imports are type-only. JSON values belong to the HTTP edge, not to a
13
+ * domain model's inheritance hierarchy.
14
14
  */
15
15
  export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `uru.uploads` — how a Gem accepts a file from the person using it.
3
+ *
4
+ * ## Three hops, and the middle one does not touch Uru
5
+ *
6
+ * 1. `request(...)` asks the platform for a grant. The answer carries a
7
+ * credential that authorizes ONE PUT: exactly one object key, exactly the
8
+ * declared byte count, exactly the declared media type, for a short window
9
+ * the server derived from the size.
10
+ * 2. The browser PUTs the bytes STRAIGHT to object storage with that
11
+ * credential. They never pass through Uru: every runtime invocation body is
12
+ * capped at 100 KB and hashed in worker memory before it is forwarded, so a
13
+ * file could not travel that way at any size worth calling a file.
14
+ * 3. `complete(...)` consumes the grant. The platform then READS the stored
15
+ * object and decides for itself whether it is what was authorized. A
16
+ * "done!" from this SDK is a trigger for that read, never evidence.
17
+ *
18
+ * `upload(file)` performs all three, which is what almost every caller wants.
19
+ *
20
+ * ## The refusals are values, not exceptions
21
+ *
22
+ * A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
23
+ * that nobody redeemed (`expired`) is a normal outcome of an upload a user
24
+ * started, and a Gem has to render it. So `complete` RESOLVES with the verdict
25
+ * and throws only when the platform could not be asked at all. `pending` is the
26
+ * one non-terminal outcome: the window is still open and nothing has landed, so
27
+ * the grant is untouched and may be completed again.
28
+ */
29
+ import type { CreateUruAppRuntimeClientOptions, UruUploadsContext } from './types.js';
30
+ /** The platform's per-file ceiling. Restated so a caller is refused locally. */
31
+ export declare const URU_UPLOAD_MAX_BYTES: number;
32
+ export declare function createUploadsContext(options: CreateUruAppRuntimeClientOptions): UruUploadsContext;
@@ -0,0 +1,228 @@
1
+ /**
2
+ * `uru.uploads` — how a Gem accepts a file from the person using it.
3
+ *
4
+ * ## Three hops, and the middle one does not touch Uru
5
+ *
6
+ * 1. `request(...)` asks the platform for a grant. The answer carries a
7
+ * credential that authorizes ONE PUT: exactly one object key, exactly the
8
+ * declared byte count, exactly the declared media type, for a short window
9
+ * the server derived from the size.
10
+ * 2. The browser PUTs the bytes STRAIGHT to object storage with that
11
+ * credential. They never pass through Uru: every runtime invocation body is
12
+ * capped at 100 KB and hashed in worker memory before it is forwarded, so a
13
+ * file could not travel that way at any size worth calling a file.
14
+ * 3. `complete(...)` consumes the grant. The platform then READS the stored
15
+ * object and decides for itself whether it is what was authorized. A
16
+ * "done!" from this SDK is a trigger for that read, never evidence.
17
+ *
18
+ * `upload(file)` performs all three, which is what almost every caller wants.
19
+ *
20
+ * ## The refusals are values, not exceptions
21
+ *
22
+ * A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
23
+ * that nobody redeemed (`expired`) is a normal outcome of an upload a user
24
+ * started, and a Gem has to render it. So `complete` RESOLVES with the verdict
25
+ * and throws only when the platform could not be asked at all. `pending` is the
26
+ * one non-terminal outcome: the window is still open and nothing has landed, so
27
+ * the grant is untouched and may be completed again.
28
+ */
29
+ import { UruAppRuntimeError } from './errors.js';
30
+ import { resolveHeaders, runtimeBasePath, trimTrailingSlash } from './runtime.js';
31
+ import { isRuntimeJsonObject } from './transport-json.js';
32
+ /** The platform's per-file ceiling. Restated so a caller is refused locally. */
33
+ export const URU_UPLOAD_MAX_BYTES = 100 * 1024 * 1024;
34
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35
+ const RESPONSE_BYTES = 64 * 1024;
36
+ const OUTCOMES = [
37
+ 'verified',
38
+ 'pending',
39
+ 'absent',
40
+ 'expired',
41
+ 'unverifiable',
42
+ 'size_mismatch',
43
+ 'type_mismatch',
44
+ ];
45
+ function invalid() {
46
+ throw new UruAppRuntimeError('Invalid upload request or response.', {
47
+ status: 0,
48
+ body: null,
49
+ });
50
+ }
51
+ const object = (value) => isRuntimeJsonObject(value) ? value : invalid();
52
+ const string = (value) => typeof value === 'string' ? value : invalid();
53
+ /**
54
+ * Read a bounded JSON body.
55
+ *
56
+ * Bounded rather than trusted for the same reason the files context bounds its
57
+ * own: a runtime that answered with an unbounded body would otherwise be able
58
+ * to exhaust the Gem's memory through a call the Gem made on purpose.
59
+ */
60
+ async function readJson(response) {
61
+ const reader = response.body?.getReader();
62
+ if (reader === undefined)
63
+ invalid();
64
+ const decoder = new TextDecoder();
65
+ let size = 0;
66
+ let text = '';
67
+ try {
68
+ for (;;) {
69
+ const chunk = await reader.read();
70
+ if (chunk.done)
71
+ break;
72
+ size += chunk.value.byteLength;
73
+ if (size > RESPONSE_BYTES) {
74
+ await reader.cancel();
75
+ invalid();
76
+ }
77
+ text += decoder.decode(chunk.value, { stream: true });
78
+ }
79
+ text += decoder.decode();
80
+ return JSON.parse(text);
81
+ }
82
+ catch (error) {
83
+ if (error instanceof UruAppRuntimeError)
84
+ throw error;
85
+ return invalid();
86
+ }
87
+ finally {
88
+ reader.releaseLock();
89
+ }
90
+ }
91
+ function grantFrom(value) {
92
+ const row = object(value);
93
+ const uploadId = string(row['uploadId']);
94
+ const uploadUrl = string(row['uploadUrl']);
95
+ const sizeBytes = row['sizeBytes'];
96
+ const headers = row['requiredHeaders'];
97
+ if (!UUID.test(uploadId) ||
98
+ uploadUrl === '' ||
99
+ typeof sizeBytes !== 'number' ||
100
+ !Number.isSafeInteger(sizeBytes) ||
101
+ sizeBytes < 1 ||
102
+ !isRuntimeJsonObject(headers)) {
103
+ invalid();
104
+ }
105
+ const requiredHeaders = {};
106
+ for (const [name, headerValue] of Object.entries(headers)) {
107
+ requiredHeaders[name] = string(headerValue);
108
+ }
109
+ return {
110
+ uploadId,
111
+ uploadUrl,
112
+ method: 'PUT',
113
+ requiredHeaders,
114
+ filename: string(row['filename']),
115
+ contentType: string(row['contentType']),
116
+ sizeBytes,
117
+ expiresAt: string(row['expiresAt']),
118
+ };
119
+ }
120
+ function resultFrom(value) {
121
+ const row = object(value);
122
+ const outcome = string(row['outcome']);
123
+ const state = string(row['state']);
124
+ const sizeBytes = row['sizeBytes'];
125
+ if (!OUTCOMES.includes(outcome) ||
126
+ (state !== 'granted' &&
127
+ state !== 'verified' &&
128
+ state !== 'rejected' &&
129
+ state !== 'expired') ||
130
+ (sizeBytes !== null && typeof sizeBytes !== 'number')) {
131
+ invalid();
132
+ }
133
+ return {
134
+ uploadId: string(row['uploadId']),
135
+ state,
136
+ outcome: outcome,
137
+ filename: string(row['filename']),
138
+ contentType: string(row['contentType']),
139
+ sizeBytes: sizeBytes === null ? null : sizeBytes,
140
+ cleanupFailed: row['cleanupFailed'] === true,
141
+ };
142
+ }
143
+ export function createUploadsContext(options) {
144
+ const base = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/uploads`;
145
+ const doFetch = options.fetch ?? globalThis.fetch;
146
+ const post = async (path, payload, signal) => {
147
+ const headers = new Headers(await resolveHeaders(options.headers));
148
+ if (payload !== undefined)
149
+ headers.set('content-type', 'application/json');
150
+ const response = await doFetch(`${base}${path}`, {
151
+ method: 'POST',
152
+ headers,
153
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
154
+ signal: signal === undefined
155
+ ? AbortSignal.timeout(30_000)
156
+ : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
157
+ });
158
+ if (!response.ok) {
159
+ await response.body?.cancel();
160
+ throw new UruAppRuntimeError('Upload request was not accepted.', {
161
+ status: response.status,
162
+ body: null,
163
+ });
164
+ }
165
+ return readJson(response);
166
+ };
167
+ const request = async (input) => {
168
+ if (typeof input.filename !== 'string' ||
169
+ input.filename.trim().length < 1 ||
170
+ input.filename.length > 255 ||
171
+ typeof input.contentType !== 'string' ||
172
+ input.contentType.trim().length < 3 ||
173
+ input.contentType.length > 255 ||
174
+ !Number.isSafeInteger(input.sizeBytes) ||
175
+ input.sizeBytes < 1 ||
176
+ input.sizeBytes > URU_UPLOAD_MAX_BYTES) {
177
+ invalid();
178
+ }
179
+ return grantFrom(await post('', {
180
+ filename: input.filename,
181
+ contentType: input.contentType,
182
+ sizeBytes: input.sizeBytes,
183
+ }, input.signal));
184
+ };
185
+ const complete = async (uploadId, settings) => {
186
+ if (typeof uploadId !== 'string' || !UUID.test(uploadId))
187
+ invalid();
188
+ return resultFrom(await post(`/${uploadId}/complete`, undefined, settings?.signal));
189
+ };
190
+ return {
191
+ request,
192
+ complete,
193
+ upload: async (file, settings) => {
194
+ // The media type is the browser's, lower-cased by it already. A file the
195
+ // OS could not type at all gets the generic one rather than an empty
196
+ // header, because a grant must name ONE concrete media type and an empty
197
+ // one would be refused at the mint with a message about a header the
198
+ // caller never wrote.
199
+ const contentType = typeof file.type === 'string' && file.type.trim() !== ''
200
+ ? file.type
201
+ : 'application/octet-stream';
202
+ const grant = await request({
203
+ filename: file.name,
204
+ contentType,
205
+ sizeBytes: file.size,
206
+ ...(settings?.signal === undefined ? {} : { signal: settings.signal }),
207
+ });
208
+ const put = await doFetch(grant.uploadUrl, {
209
+ method: 'PUT',
210
+ // Exactly the headers the grant was SIGNED with. Adding or altering one
211
+ // changes the canonical request the provider rebuilds, and the PUT is
212
+ // refused with a signature error that names nothing.
213
+ headers: new Headers(grant.requiredHeaders),
214
+ body: file,
215
+ ...(settings?.signal === undefined ? {} : { signal: settings.signal }),
216
+ });
217
+ if (!put.ok) {
218
+ await put.body?.cancel();
219
+ throw new UruAppRuntimeError('Upload was refused by object storage.', {
220
+ status: put.status,
221
+ body: null,
222
+ });
223
+ }
224
+ await put.body?.cancel();
225
+ return complete(grant.uploadId, settings?.signal === undefined ? undefined : { signal: settings.signal });
226
+ },
227
+ };
228
+ }