@astrale-os/kernel-client 1.0.0-beta.36 → 1.0.0-beta.38

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.
@@ -9,6 +9,10 @@ export interface ContentLocation {
9
9
  readonly node: string;
10
10
  readonly property: string;
11
11
  }
12
+ /** The content one upload receipt of this Session's caller names, read back without a holder. */
13
+ export interface ContentReceipt {
14
+ readonly receipt: string;
15
+ }
12
16
  export interface ContentUploadOptions extends SessionControlOptions {
13
17
  readonly mediaType: string;
14
18
  }
@@ -38,6 +42,12 @@ export type ContentSource = Blob | Uint8Array | BinaryRequestBody;
38
42
  export interface ContentApi {
39
43
  upload(source: ContentSource, options: ContentUploadOptions): Promise<ContentUploadResult>;
40
44
  download(location: ContentLocation, options?: SessionControlOptions): Promise<Binary>;
45
+ /**
46
+ * The content an upload receipt names, for the caller it was issued to, before or without any
47
+ * attachment. A receipt another caller received, an expired one, or a Ref is refused
48
+ * (`BLOB_RECEIPT_INVALID`).
49
+ */
50
+ download(receipt: ContentReceipt, options?: SessionControlOptions): Promise<Binary>;
41
51
  /**
42
52
  * One outcome per location, in order, within one time budget for the whole list. Consume each
43
53
  * content body before requesting the next outcome: an unread body is skipped.
@@ -1,7 +1,7 @@
1
1
  import { cancelUnsent } from '../../transport/http/binary-request.js';
2
2
  import { requireResultKind } from '../routing/index.js';
3
3
  import { downloadBatch } from './batch.js';
4
- import { acceptBody, acceptControls, acceptLocation, acceptMediaType } from './input.js';
4
+ import { acceptBody, acceptControls, acceptLocation, acceptMediaType, acceptReceipt, isReceipt, } from './input.js';
5
5
  import { retry } from './retry.js';
6
6
  import { DOWNLOAD, UPLOAD, decodeDownload, decodeUploadResult } from './wire.js';
7
7
  /** Transfer immutable content over the authenticated Session routing conversation. */
@@ -28,9 +28,10 @@ export function createContentApi(dependencies) {
28
28
  }
29
29
  return downloadOne(input, options);
30
30
  }
31
- async function downloadOne(location, options) {
31
+ async function downloadOne(source, options) {
32
+ const request = isReceipt(source) ? acceptReceipt(source) : acceptLocation(source);
32
33
  const operation = dependencies.operation(acceptControls(options));
33
- const result = await dependencies.dispatch(DOWNLOAD, acceptLocation(location), operation);
34
+ const result = await dependencies.dispatch(DOWNLOAD, request, operation);
34
35
  return decodeDownload(requireResultKind('binary', result).value);
35
36
  }
36
37
  return Object.freeze({ upload, download });
@@ -0,0 +1,12 @@
1
+ import type { schema } from '@astrale-os/kernel-dsl/v1';
2
+ import type { ContentUploadOptions, ContentUploadResult } from './api.js';
3
+ type FilePosition = schema.values.FilePosition;
4
+ /** What sending a typed input's files needs: one upload per file. */
5
+ export type FileUpload = (source: Blob, options: ContentUploadOptions) => Promise<ContentUploadResult>;
6
+ /**
7
+ * `input` with every Blob or File at one of `positions` uploaded and replaced by its receipt. A
8
+ * file is checked against the constraints its field states before it is uploaded; a value that is
9
+ * not a Blob, a receipt already, is sent as it is. Without a Blob the input is returned unchanged.
10
+ */
11
+ export declare function uploadFiles(positions: readonly FilePosition[], input: unknown, upload: FileUpload, options: Omit<ContentUploadOptions, 'mediaType'>): Promise<unknown>;
12
+ export {};
@@ -0,0 +1,47 @@
1
+ import { locateFiles } from '@astrale-os/kernel-dsl/v1/schema/values';
2
+ import { acceptMediaType } from './input.js';
3
+ /**
4
+ * `input` with every Blob or File at one of `positions` uploaded and replaced by its receipt. A
5
+ * file is checked against the constraints its field states before it is uploaded; a value that is
6
+ * not a Blob, a receipt already, is sent as it is. Without a Blob the input is returned unchanged.
7
+ */
8
+ export async function uploadFiles(positions, input, upload, options) {
9
+ const files = locateFiles(positions, input).filter(({ value }) => value instanceof Blob);
10
+ if (files.length === 0)
11
+ return input;
12
+ let sent = input;
13
+ for (const { pointer, position, value } of files) {
14
+ const blob = value;
15
+ const mediaType = acceptMediaType(blob.type === '' ? 'application/octet-stream' : blob.type);
16
+ if (position.maxBytes !== undefined && blob.size > position.maxBytes) {
17
+ throw new TypeError(`File at ${pointer || '/'} exceeds its ${position.maxBytes} bytes.`);
18
+ }
19
+ if (position.mediaTypes !== undefined && !position.mediaTypes.includes(mediaType)) {
20
+ throw new TypeError(`File at ${pointer || '/'} has a media type its field refuses.`);
21
+ }
22
+ const { receipt } = await upload(blob, { ...options, mediaType });
23
+ sent = replaceAt(sent, tokensOf(pointer), receipt);
24
+ }
25
+ return sent;
26
+ }
27
+ /** A copy of `value` with `replacement` at `tokens`; only the containers on the way are copied. */
28
+ function replaceAt(value, tokens, replacement) {
29
+ if (tokens.length === 0)
30
+ return replacement;
31
+ const [token, ...rest] = tokens;
32
+ if (Array.isArray(value)) {
33
+ const copy = [...value];
34
+ copy[Number(token)] = replaceAt(value[Number(token)], rest, replacement);
35
+ return copy;
36
+ }
37
+ const record = value;
38
+ return { ...record, [token]: replaceAt(record[token], rest, replacement) };
39
+ }
40
+ function tokensOf(pointer) {
41
+ if (pointer === '')
42
+ return [];
43
+ return pointer
44
+ .slice(1)
45
+ .split('/')
46
+ .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));
47
+ }
@@ -1 +1 @@
1
- export { createContentApi, type ContentApi, type ContentDownload, type ContentLocation, type ContentRejection, type ContentSource, type ContentUploadOptions, type ContentUploadResult, } from './api.js';
1
+ export { createContentApi, type ContentApi, type ContentDownload, type ContentLocation, type ContentReceipt, type ContentRejection, type ContentSource, type ContentUploadOptions, type ContentUploadResult, } from './api.js';
@@ -1,9 +1,15 @@
1
1
  import type { BinaryBody } from '../../transport/http/binary-request.js';
2
2
  import type { SessionControlOptions } from '../context/index.js';
3
- import type { ContentLocation } from './api.js';
3
+ import type { ContentLocation, ContentReceipt } from './api.js';
4
4
  /** One canonical content location, as a download request carries it. */
5
5
  export type Slot = Readonly<Record<'node' | 'property', string>>;
6
6
  export declare function acceptLocation(input: ContentLocation): Slot;
7
+ /** Whether a download names a receipt rather than a holder location. */
8
+ export declare function isReceipt(input: ContentLocation | ContentReceipt): input is ContentReceipt;
9
+ /** One receipt download, exactly as the request carries it; the Kernel admits the receipt. */
10
+ export declare function acceptReceipt(input: ContentReceipt): Readonly<{
11
+ receipt: string;
12
+ }>;
7
13
  /**
8
14
  * The bytes of one upload: a Blob, an owned snapshot of a Uint8Array, or a byte stream with its
9
15
  * exact length, which the upload consumes.
@@ -10,6 +10,19 @@ export function acceptLocation(input) {
10
10
  }
11
11
  return Object.freeze({ node: NodeId(input.node), property: PropertyKey(input.property) });
12
12
  }
13
+ /** Whether a download names a receipt rather than a holder location. */
14
+ export function isReceipt(input) {
15
+ return input !== null && typeof input === 'object' && Object.hasOwn(input, 'receipt');
16
+ }
17
+ /** One receipt download, exactly as the request carries it; the Kernel admits the receipt. */
18
+ export function acceptReceipt(input) {
19
+ if (Object.keys(input).length !== 1 ||
20
+ typeof input.receipt !== 'string' ||
21
+ input.receipt.length === 0) {
22
+ throw new TypeError('Content receipt is invalid.');
23
+ }
24
+ return Object.freeze({ receipt: input.receipt });
25
+ }
13
26
  /**
14
27
  * The bytes of one upload: a Blob, an owned snapshot of a Uint8Array, or a byte stream with its
15
28
  * exact length, which the upload consumes.
@@ -1,5 +1,5 @@
1
1
  export type { SessionControlOptions, SessionPolicy } from './context/index.js';
2
- export type { ContentApi, ContentDownload, ContentLocation, ContentRejection, ContentSource, ContentUploadOptions, ContentUploadResult, } from './content/index.js';
2
+ export type { ContentApi, ContentDownload, ContentLocation, ContentReceipt, ContentRejection, ContentSource, ContentUploadOptions, ContentUploadResult, } from './content/index.js';
3
3
  export { bindSession, type BoundClientSession, type BoundSessionControls, type BoundSessionSource, } from './bound.js';
4
4
  export { credentials, type Credentials, type CredentialsMint, type CredentialsOptions, type CredentialsState, type SessionCredential, } from './credential/index.js';
5
5
  export type { IntrinsicRelease, SessionSnapshot } from './discovery/index.js';
@@ -7,7 +7,7 @@ export type { SessionExchangeOptions, SessionExchangeRequest } from './exchange/
7
7
  export type { Auth, PersistedRoute, SessionRouteArtifact, SessionRouteStore, SessionAuth, SessionEnvelopeTransport, SessionRequestOptions, SessionRequestOptionsWithBody, } from './routing/index.js';
8
8
  export type { ClientSessionOptions } from './options.js';
9
9
  export { ClientSession, connect, type ConnectOptions } from './session.js';
10
- export type { CallableReference, InputOfReference, InputModeOfReference, InstanceCallableReference, OutputOfReference, } from './reference.js';
10
+ export type { CallableReference, FileSourcesOf, InputOfReference, InputModeOfReference, InstanceCallableReference, OutputOfReference, } from './reference.js';
11
11
  export { reference } from './reference.js';
12
12
  export type { DeletedExecutionStatus, ExecutionApi, ExecutionFailure, ExecutionNodeStatus, ExecutionOutcome, ExecutionRef, ExecutionState, ExecutionStatus, ExecutionTarget, ExecutionWait, } from '../execution/index.js';
13
13
  export type { View, ViewsOf } from './views/index.js';
@@ -1,7 +1,8 @@
1
1
  import type { Path as PathValue, PathLike } from '@astrale-os/kernel-core/path';
2
- import type { CallableInputOf, CallableInputModeOf, CallableOutputOf, CallableResultOf, Domain, ResolvedFunction, ExecutableMethod, ResolvedMethod } from '@astrale-os/kernel-dsl/v1';
2
+ import type { BlobReceipt, CallableInputOf, CallableInputModeOf, CallableOutputOf, CallableResultOf, Domain, ResolvedFunction, ExecutableMethod, ResolvedMethod } from '@astrale-os/kernel-dsl/v1';
3
3
  import type { MethodAddress } from '@astrale-os/kernel-dsl/v1/addressing';
4
4
  import type { MeaningFingerprint } from '@astrale-os/kernel-dsl/v1/schema/fingerprint';
5
+ import type { FilePosition } from '@astrale-os/kernel-dsl/v1/schema/values';
5
6
  import { type Key as KeyType } from '@astrale-os/kernel-dsl/v1/addressing';
6
7
  import type { Binary, Input, Result } from '../client/index.js';
7
8
  import type { ExecutionRef } from '../execution/index.js';
@@ -17,6 +18,11 @@ export interface CallableReference<InputValue = Input, Output = unknown, InputMo
17
18
  readonly callable: KeyType.Callable;
18
19
  readonly target: PathValue;
19
20
  readonly outputMode: OutputMode;
21
+ /**
22
+ * Where the callable input holds file fields. `invoke` uploads a Blob or File found there and
23
+ * sends its receipt; a generated reference carries them, a Kernel reference none.
24
+ */
25
+ readonly files?: readonly FilePosition[];
20
26
  readonly [REFERENCE_INPUT]?: InputValue;
21
27
  readonly [REFERENCE_INPUT_MODE]?: InputMode;
22
28
  readonly [REFERENCE_OUTPUT]?: Output;
@@ -27,11 +33,20 @@ export interface InstanceCallableReference<InputValue = Input, Output = unknown>
27
33
  readonly fingerprint?: MeaningFingerprint;
28
34
  readonly callable: KeyType.Callable;
29
35
  readonly outputMode: OutputMode;
36
+ readonly files?: readonly FilePosition[];
30
37
  }
31
38
  export type InputOfReference<Reference extends CallableReference<unknown>> = Reference extends CallableReference<infer InputValue, unknown> ? InputValue : never;
32
39
  export type OutputOfReference<Reference extends CallableReference<unknown>> = Reference extends CallableReference<infer _Input, infer Output> ? Output : never;
33
40
  export type InputModeOfReference<Reference extends CallableReference<unknown>> = Reference extends CallableReference<infer _Input, infer _Output, infer Mode> ? Mode : never;
34
- type ReferenceInput<Callable> = unknown extends CallableInputOf<Callable> ? Input : CallableInputOf<Callable>;
41
+ type ReferenceInput<Callable> = unknown extends CallableInputOf<Callable> ? Input : FileSourcesOf<CallableInputOf<Callable>>;
42
+ type ContainsReceipt<Value, Depth extends readonly unknown[] = []> = Depth['length'] extends 8 ? false : Value extends BlobReceipt ? true : Value extends object ? true extends {
43
+ [Key in keyof Value]-?: ContainsReceipt<Value[Key], readonly [...Depth, unknown]>;
44
+ }[keyof Value] ? true : false : false;
45
+ /** A typed input whose file fields also take the Blob or File `invoke` uploads first. */
46
+ export type FileSourcesOf<Value> = true extends ContainsReceipt<Value> ? FileSourcesIn<Value> : Value;
47
+ type FileSourcesIn<Value> = Value extends BlobReceipt ? Value | Blob : Value extends object ? {
48
+ [Key in keyof Value]: FileSourcesIn<Value[Key]>;
49
+ } : Value;
35
50
  type HandlerOutput<Callable> = unknown extends CallableOutputOf<Callable> ? unknown : CallableResultOf<Callable, Binary>;
36
51
  type ReferenceOutput<Callable> = Callable extends {
37
52
  readonly execution: {
@@ -49,6 +64,8 @@ export declare function reference<const Callable extends ExecutableInstanceMetho
49
64
  * addresses every Kernel syscall. Loading the Session therefore never resolves the Kernel Schema.
50
65
  */
51
66
  export declare function kernelReference(method: MethodAddress): InstanceCallableReference<unknown>;
67
+ /** Where the input of this callable holds file fields. */
68
+ export declare function filesOf(callable: ResolvedFunction | ResolvedMethod): readonly FilePosition[];
52
69
  /** The result kind invoking this callable yields. */
53
70
  export declare function outputModeOf(callable: ResolvedFunction | ResolvedMethod): OutputMode;
54
71
  export declare function admitReference(input: CallableReference<unknown>): CallableReference<unknown>;
@@ -1,6 +1,8 @@
1
1
  import { Path } from '@astrale-os/kernel-core/path';
2
2
  import { callableAddress, Key, MethodKey, patterns, } from '@astrale-os/kernel-dsl/v1/addressing';
3
+ import { isBinaryInput } from '@astrale-os/kernel-dsl/v1/language';
3
4
  import { callableFingerprint } from '@astrale-os/kernel-dsl/v1/schema/fingerprint';
5
+ import { filePositions } from '@astrale-os/kernel-dsl/v1/schema/values';
4
6
  const FINGERPRINT_PATTERN = /^sha256:[0-9a-f]{64}$/u;
5
7
  const OUTPUT_MODES = ['value', 'stream', 'binary', 'execution'];
6
8
  export function reference(domain, callable) {
@@ -8,11 +10,13 @@ export function reference(domain, callable) {
8
10
  invalid();
9
11
  if ('owner' in callable && !callable.executable)
10
12
  invalid();
13
+ const files = filesOf(callable);
11
14
  const common = Object.freeze({
12
15
  origin: domain.origin,
13
16
  fingerprint: callableFingerprint(callable),
14
17
  callable: callable.key,
15
18
  outputMode: outputModeOf(callable),
19
+ ...(files.length === 0 ? {} : { files }),
16
20
  });
17
21
  if ('owner' in callable && !callable.static) {
18
22
  const bind = (receiver) => admitReference({
@@ -40,6 +44,10 @@ export function kernelReference(method) {
40
44
  const bind = (receiver) => admitReference({ ...common, target: Path.instanceMethod(Path.from(receiver), callable) });
41
45
  return Object.assign(bind, common);
42
46
  }
47
+ /** Where the input of this callable holds file fields. */
48
+ export function filesOf(callable) {
49
+ return filePositions(isBinaryInput(callable.input) ? callable.input.metadata : callable.input);
50
+ }
43
51
  /** The result kind invoking this callable yields. */
44
52
  export function outputModeOf(callable) {
45
53
  return callable.execution?.durable === true ? 'execution' : callable.output.mode;
@@ -54,7 +62,8 @@ export function admitReference(input) {
54
62
  Key.origin(input.callable) !== input.origin ||
55
63
  !OUTPUT_MODES.includes(input.outputMode) ||
56
64
  (input.fingerprint !== undefined &&
57
- (typeof input.fingerprint !== 'string' || !FINGERPRINT_PATTERN.test(input.fingerprint))))
65
+ (typeof input.fingerprint !== 'string' || !FINGERPRINT_PATTERN.test(input.fingerprint))) ||
66
+ (input.files !== undefined && !Array.isArray(input.files)))
58
67
  invalid();
59
68
  const target = Path.from(input.target);
60
69
  if (!matchesCallable(target, input.callable))
@@ -65,6 +74,7 @@ export function admitReference(input) {
65
74
  callable: input.callable,
66
75
  target,
67
76
  outputMode: input.outputMode,
77
+ ...(input.files === undefined || input.files.length === 0 ? {} : { files: input.files }),
68
78
  });
69
79
  }
70
80
  export function matchesCallable(target, callable) {
@@ -8,13 +8,14 @@ import { createDomainBinding } from '../graph/domain/binding.js';
8
8
  import { createGraph } from '../graph/index.js';
9
9
  import { createSchema } from '../schema/index.js';
10
10
  import { admitFunction } from './admission.js';
11
+ import { uploadFiles } from './content/files.js';
11
12
  import { createContentApi } from './content/index.js';
12
13
  import { admitControlOptions, allowEndpoint, createSessionOperation, sessionTransportOptions, } from './context/index.js';
13
14
  import { createSessionDiscovery } from './discovery/index.js';
14
15
  import { attemptDurable, durableOptions } from './durable.js';
15
16
  import { acquireDomainCredential, admitExchangeRequest, createSessionExchange, } from './exchange/index.js';
16
17
  import { acceptSessionOptions } from './options.js';
17
- import { admitReference, outputModeOf } from './reference.js';
18
+ import { admitReference, filesOf, outputModeOf } from './reference.js';
18
19
  import { admitInvocationOptions, requireResultKind, SessionDispatcher } from './routing/index.js';
19
20
  import { admitView } from './views/index.js';
20
21
  import { readDomainViewsOrResolved, readViewOrResolved, resolvedViewSource, } from './views/legacy/index.js';
@@ -161,6 +162,10 @@ export class ClientSession {
161
162
  async invoke(reference, input, options) {
162
163
  const admittedReference = admitReference(reference);
163
164
  const admitted = admitInvocationOptions(options);
165
+ // A file field may hold the Blob itself: it is uploaded, and its receipt is sent.
166
+ const sent = admittedReference.files === undefined
167
+ ? input
168
+ : await uploadFiles(admittedReference.files, input, (source, uploadOptions) => this.content.upload(source, uploadOptions), admitted.options.signal === undefined ? {} : { signal: admitted.options.signal });
164
169
  const { anchor, steps } = admittedReference.target.ast;
165
170
  const last = steps.at(-1);
166
171
  const instance = last?.kind === 'method' && last.dispatch === 'instance'
@@ -176,7 +181,7 @@ export class ClientSession {
176
181
  : { fingerprint: admittedReference.fingerprint }),
177
182
  ...(instance === undefined ? {} : { instance }),
178
183
  }),
179
- input,
184
+ input: sent,
180
185
  };
181
186
  // A durable call is keyed, so an attempt whose outcome is unknown can be sent again.
182
187
  const durable = admittedReference.outputMode === 'execution';
@@ -244,6 +249,7 @@ export class ClientSession {
244
249
  callable: method.key,
245
250
  target: Path.instanceMethod(Path.id(node.id), method.key),
246
251
  outputMode: outputModeOf(method),
252
+ files: filesOf(method),
247
253
  }, input);
248
254
  }
249
255
  operation(options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/kernel-client",
3
- "version": "1.0.0-beta.36",
3
+ "version": "1.0.0-beta.38",
4
4
  "description": "Universal Client — protocol-first, transport-agnostic",
5
5
  "keywords": [
6
6
  "astrale",
@@ -65,18 +65,18 @@
65
65
  "access": "public"
66
66
  },
67
67
  "dependencies": {
68
- "@astrale-os/kernel-core": "1.0.0-beta.33",
69
- "@astrale-os/kernel-dsl": "1.0.0-beta.21",
70
- "@astrale-os/kernel-protocol": "1.0.0-beta.33",
68
+ "@astrale-os/kernel-core": "1.0.0-beta.35",
69
+ "@astrale-os/kernel-dsl": "1.0.0-beta.23",
70
+ "@astrale-os/kernel-protocol": "1.0.0-beta.35",
71
71
  "@tanstack/pacer": "0.20.1"
72
72
  },
73
73
  "devDependencies": {
74
- "@astrale-os/kernel-server": "1.0.0-beta.33",
74
+ "@astrale-os/kernel-server": "1.0.0-beta.35",
75
75
  "@astrale/typescript-config": "npm:@jsr/astrale__typescript-config@~1.1.0",
76
- "@types/node": "^22.0.0",
76
+ "@types/node": "^24.10.0",
77
77
  "esbuild": "0.28.1",
78
78
  "typescript": "7.0.2",
79
- "undici": "8.10.0",
79
+ "undici": "8.12.2",
80
80
  "vitest": "^5.0.1"
81
81
  },
82
82
  "scripts": {