@midsummer-ai/sdk 0.1.0-staging.3123 → 0.1.0-staging.3129
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/ai/contract.mjs +39 -0
- package/ai/index.d.mts +70 -12
- package/ai/index.mjs +74 -5
- package/ai/stand-in.mjs +26 -4
- package/client.d.mts +1 -1
- package/client.mjs +1 -105
- package/{connection-Cu2GSOaR.mjs → connection-C_JSWUrt.mjs} +7 -6
- package/contract.d.mts +1 -1
- package/contract.mjs +1 -1
- package/database/client.d.mts +20 -1
- package/database/client.mjs +31 -8
- package/database/stand-in.d.mts +2 -2
- package/database/stand-in.mjs +1 -1
- package/email/client.mjs +1 -130
- package/email/contract.mjs +1 -1
- package/email/index.d.mts +9 -7
- package/email/index.mjs +1 -58
- package/email/smtp.mjs +1 -2
- package/email/stand-in.mjs +1 -1
- package/email-DXtpr7pT.mjs +214 -0
- package/here-CeqGJW21.mjs +28 -0
- package/{index-DNNXNny7.d.mts → index-B9zs0wIp.d.mts} +6 -1
- package/{index-sgdyoA2P.d.mts → index-Ci6mGXqz.d.mts} +7 -1
- package/index.d.mts +2 -2
- package/index.mjs +3 -137
- package/package.json +1 -1
- package/queues/index.d.mts +17 -5
- package/queues/index.mjs +71 -1
- package/s3.d.mts +1 -1
- package/s3.mjs +1 -1
- package/socket.d.mts +1 -1
- package/socket.mjs +1 -262
- package/src-BKrQAqJN.mjs +519 -0
- package/stand-in.d.mts +1 -1
- package/{store-lIZ5GxVv.mjs → store-CsBhnabU.mjs} +1 -1
- package/{tabs-zCh8kceo.mjs → tabs-gHJHkhm2.mjs} +1 -1
- package/vector/contract.d.mts +1 -1
- package/vector/contract.mjs +1 -1
- package/vector/index.d.mts +2 -2
- package/vector/index.mjs +18 -7
- package/vector/stand-in.d.mts +1 -1
- package/vector/stand-in.mjs +1 -1
- package/vector/wire.d.mts +1 -1
- package/vector/wire.mjs +1 -339
- package/wire-BdNDzlIN.mjs +554 -0
- package/wire.d.mts +1 -1
- package/schema-CTHQMRsW.mjs +0 -217
package/index.mjs
CHANGED
|
@@ -1,137 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* The SDK: the one package your project's code imports to use Midsummer's products. This entry is
|
|
5
|
-
* storage: your team's files, kept in buckets.
|
|
6
|
-
*
|
|
7
|
-
* In your deployment's server, the environment's storage arrives as `context.storage`. A bucket is
|
|
8
|
-
* named by the name the environment binds it under (`midsummer env binding set`), so `avatars` can
|
|
9
|
-
* be one bucket in production and another in Preview:
|
|
10
|
-
*
|
|
11
|
-
* import { storage } from "@midsummer-ai/sdk"
|
|
12
|
-
* import { remote } from "@midsummer-ai/sdk/wire"
|
|
13
|
-
*
|
|
14
|
-
* export default {
|
|
15
|
-
* async fetch(request: Request, context: { storage: { send(frame: Uint8Array): Promise<Uint8Array> } }) {
|
|
16
|
-
* const avatars = storage(remote(context.storage)).bucket("avatars")
|
|
17
|
-
* await avatars.put("ada.png", new Uint8Array(await request.arrayBuffer()), { contentType: "image/png" })
|
|
18
|
-
* const page = await avatars.list({ prefix: "2026/", delimiter: "/" })
|
|
19
|
-
* return Response.json(page)
|
|
20
|
-
* },
|
|
21
|
-
* }
|
|
22
|
-
*
|
|
23
|
-
* Code that runs outside Midsummer connects with a storage key (`midsummer storage key create`):
|
|
24
|
-
*
|
|
25
|
-
* import { storage } from "@midsummer-ai/sdk"
|
|
26
|
-
* import { client } from "@midsummer-ai/sdk/client"
|
|
27
|
-
*
|
|
28
|
-
* const files = storage(client("https://api.midsummer.new", { key, secret }))
|
|
29
|
-
*
|
|
30
|
-
* In tests, `standIn` from `@midsummer-ai/sdk/stand-in` keeps files in memory. All three pass the same
|
|
31
|
-
* tests, in `@midsummer-ai/sdk/contract`, and only what those tests check is guaranteed.
|
|
32
|
-
*
|
|
33
|
-
* Bucket names and keys are checked before a request is sent. Every failure is a `StorageError`,
|
|
34
|
-
* and its `code` shows which kind. Reading a key with nothing stored returns `null`, not an error.
|
|
35
|
-
*/
|
|
36
|
-
/**
|
|
37
|
-
* The streaming methods of `engine` an engine wrapping it passes on, with each Bucket named as `read`
|
|
38
|
-
* (for `stream`) and `write` (for the rest) turn it; none where `engine` has none.
|
|
39
|
-
*/
|
|
40
|
-
function streamsOf(engine, read, write) {
|
|
41
|
-
const { stream, putStream, uploadPartStream } = engine;
|
|
42
|
-
return {
|
|
43
|
-
...stream ? { stream: (bucket, key, range) => stream.call(engine, read(bucket), key, range) } : {},
|
|
44
|
-
...putStream ? { putStream: (bucket, key, body, size, options) => putStream.call(engine, write(bucket), key, body, size, options) } : {},
|
|
45
|
-
...uploadPartStream ? { uploadPartStream: (bucket, key, uploadId, partNumber, body, size, sha256) => uploadPartStream.call(engine, write(bucket), key, uploadId, partNumber, body, size, sha256) } : {}
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
/** Storage over `engine`. */
|
|
49
|
-
function storage(engine) {
|
|
50
|
-
return { bucket(name) {
|
|
51
|
-
checkBucketName(name);
|
|
52
|
-
return {
|
|
53
|
-
name,
|
|
54
|
-
async put(key, body, options = {}) {
|
|
55
|
-
checkKey(key);
|
|
56
|
-
const metadata = options.metadata ?? {};
|
|
57
|
-
checkMetadata(metadata);
|
|
58
|
-
if (options.ifMatch !== void 0 && !/^[0-9a-f]{64}$/.test(options.ifMatch)) invalid("ifMatch is not an etag");
|
|
59
|
-
return engine.put(name, key, body instanceof Blob ? await bytesOfBlob(body) : bytesOf(body), {
|
|
60
|
-
contentType: options.contentType ?? "application/octet-stream",
|
|
61
|
-
metadata,
|
|
62
|
-
...options.ifNoneMatch ? { ifNoneMatch: options.ifNoneMatch } : {},
|
|
63
|
-
...options.ifMatch !== void 0 ? { ifMatch: options.ifMatch } : {}
|
|
64
|
-
});
|
|
65
|
-
},
|
|
66
|
-
async get(key, options = {}) {
|
|
67
|
-
checkKey(key);
|
|
68
|
-
if (options.range) checkRange(options.range);
|
|
69
|
-
return engine.get(name, key, options.range);
|
|
70
|
-
},
|
|
71
|
-
async head(key) {
|
|
72
|
-
checkKey(key);
|
|
73
|
-
return engine.head(name, key);
|
|
74
|
-
},
|
|
75
|
-
async delete(key) {
|
|
76
|
-
checkKey(key);
|
|
77
|
-
return engine.delete(name, key);
|
|
78
|
-
},
|
|
79
|
-
async list(options = {}) {
|
|
80
|
-
const limit = options.limit ?? 1e3;
|
|
81
|
-
checkListLimit(limit);
|
|
82
|
-
if (options.delimiter === "") invalid("the delimiter is empty");
|
|
83
|
-
return engine.list(name, {
|
|
84
|
-
prefix: options.prefix ?? "",
|
|
85
|
-
limit,
|
|
86
|
-
...options.delimiter !== void 0 ? { delimiter: options.delimiter } : {},
|
|
87
|
-
...options.after !== void 0 ? { after: options.after } : {}
|
|
88
|
-
});
|
|
89
|
-
},
|
|
90
|
-
async copy(from, to, options = {}) {
|
|
91
|
-
checkKey(from);
|
|
92
|
-
checkKey(to);
|
|
93
|
-
return engine.copy(name, from, to, options.ifNoneMatch ? { ifNoneMatch: options.ifNoneMatch } : {});
|
|
94
|
-
},
|
|
95
|
-
async createUpload(key, options = {}) {
|
|
96
|
-
checkKey(key);
|
|
97
|
-
const metadata = options.metadata ?? {};
|
|
98
|
-
checkMetadata(metadata);
|
|
99
|
-
return engine.createUpload(name, key, {
|
|
100
|
-
contentType: options.contentType ?? "application/octet-stream",
|
|
101
|
-
metadata,
|
|
102
|
-
...options.ifNoneMatch ? { ifNoneMatch: options.ifNoneMatch } : {}
|
|
103
|
-
});
|
|
104
|
-
},
|
|
105
|
-
async uploadPart(key, uploadId, partNumber, body) {
|
|
106
|
-
checkKey(key);
|
|
107
|
-
checkUploadId(uploadId);
|
|
108
|
-
checkPartNumber(partNumber);
|
|
109
|
-
return engine.uploadPart(name, key, uploadId, partNumber, body instanceof Blob ? await bytesOfBlob(body) : bytesOf(body));
|
|
110
|
-
},
|
|
111
|
-
async completeUpload(key, uploadId, parts) {
|
|
112
|
-
checkKey(key);
|
|
113
|
-
checkUploadId(uploadId);
|
|
114
|
-
checkParts(parts);
|
|
115
|
-
return engine.completeUpload(name, key, uploadId, parts.map((p) => ({
|
|
116
|
-
partNumber: p.partNumber,
|
|
117
|
-
etag: p.etag
|
|
118
|
-
})));
|
|
119
|
-
},
|
|
120
|
-
async abortUpload(key, uploadId) {
|
|
121
|
-
checkKey(key);
|
|
122
|
-
checkUploadId(uploadId);
|
|
123
|
-
return engine.abortUpload(name, key, uploadId);
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
} };
|
|
127
|
-
}
|
|
128
|
-
function bytesOf(body) {
|
|
129
|
-
if (typeof body === "string") return new TextEncoder().encode(body);
|
|
130
|
-
if (body instanceof Uint8Array) return body;
|
|
131
|
-
return new Uint8Array(body);
|
|
132
|
-
}
|
|
133
|
-
async function bytesOfBlob(body) {
|
|
134
|
-
return new Uint8Array(await body.arrayBuffer());
|
|
135
|
-
}
|
|
136
|
-
//#endregion
|
|
137
|
-
export { StorageError, storage, streamsOf };
|
|
1
|
+
import { h as StorageError } from "./names-DfCBKupJ.mjs";
|
|
2
|
+
import { n as storage, r as streamsOf, t as bucket } from "./src-BKrQAqJN.mjs";
|
|
3
|
+
export { StorageError, bucket, storage, streamsOf };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midsummer-ai/sdk",
|
|
3
|
-
"version": "0.1.0-staging.
|
|
3
|
+
"version": "0.1.0-staging.3129",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",
|
package/queues/index.d.mts
CHANGED
|
@@ -15,10 +15,17 @@
|
|
|
15
15
|
* }
|
|
16
16
|
* const { depth, oldestSentAt } = await emails.stats()
|
|
17
17
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
18
|
+
* In a deployment, in any framework, and under `midsummer dev`, `queue` reaches the queue the
|
|
19
|
+
* environment binds under a name, with nothing to connect:
|
|
20
|
+
*
|
|
21
|
+
* import { queue } from "@midsummer-ai/sdk/queues"
|
|
22
|
+
*
|
|
23
|
+
* await queue("emails").send({ to: "ada@example.com" })
|
|
24
|
+
*
|
|
25
|
+
* The Stand-in keeps Messages in memory, for tests and `midsummer dev`. Code can pull its Messages
|
|
26
|
+
* with `receive`, or a consumer can deliver each one to a path of your site (`midsummer queue
|
|
27
|
+
* consumer set`). Each engine is held to the cases in `@midsummer-ai/sdk/queues/contract`; a
|
|
28
|
+
* behaviour that is not a case there is not promised.
|
|
22
29
|
*
|
|
23
30
|
* Delivery is at least once. A Message received is hidden from other receivers for its visibility
|
|
24
31
|
* window; acked, it is gone; retried, or left until the window ends, it is delivered again, a later
|
|
@@ -179,6 +186,11 @@ declare function checkReceive(options: {
|
|
|
179
186
|
readonly maxAttempts: number;
|
|
180
187
|
}): void;
|
|
181
188
|
/** Queues over `engine`. */
|
|
189
|
+
/**
|
|
190
|
+
* The queue the environment binds under `name`, from code in a deployment in any framework, or
|
|
191
|
+
* `midsummer dev`'s queue of that name.
|
|
192
|
+
*/
|
|
193
|
+
declare function queue(name: string): Queue;
|
|
182
194
|
declare function queues(engine: QueueEngine): Queues;
|
|
183
195
|
//#endregion
|
|
184
|
-
export { DEAD, Delivery, EngineDelivery, EngineMessage, Json, MAX_BODY, Queue, QueueEngine, QueueError, QueueErrorCode, QueueStats, Queues, ReceiveOptions, STATS_CAP, SendOptions, backoffMs, bodyText, checkDelaySeconds, checkEngineQueue, checkKey, checkQueueName, checkReceipt, checkReceive, invalid, queueErrorCodes, queues };
|
|
196
|
+
export { DEAD, Delivery, EngineDelivery, EngineMessage, Json, MAX_BODY, Queue, QueueEngine, QueueError, QueueErrorCode, QueueStats, Queues, ReceiveOptions, STATS_CAP, SendOptions, backoffMs, bodyText, checkDelaySeconds, checkEngineQueue, checkKey, checkQueueName, checkReceipt, checkReceive, invalid, queue, queueErrorCodes, queues };
|
package/queues/index.mjs
CHANGED
|
@@ -1,4 +1,50 @@
|
|
|
1
|
+
import { n as late, r as processEnv, t as here } from "../here-CeqGJW21.mjs";
|
|
1
2
|
//#region src/queues/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* Queues: a Team's Queues of Messages, which the SDK reaches by the name an Environment binds each one
|
|
5
|
+
* under (`midsummer env binding set`).
|
|
6
|
+
*
|
|
7
|
+
* import { queues } from "@midsummer-ai/sdk/queues"
|
|
8
|
+
* import { standIn } from "@midsummer-ai/sdk/queues/stand-in"
|
|
9
|
+
*
|
|
10
|
+
* const jobs = queues(standIn({ clock: Date.now }))
|
|
11
|
+
* const emails = jobs.queue("emails")
|
|
12
|
+
* await emails.send({ to: "ada@example.com" }, { key: `welcome:${userId}` })
|
|
13
|
+
* for (const delivery of await emails.receive({ limit: 10 })) {
|
|
14
|
+
* try { await mail(delivery.body); await emails.ack(delivery.receipt) }
|
|
15
|
+
* catch { await emails.retry(delivery.receipt) }
|
|
16
|
+
* }
|
|
17
|
+
* const { depth, oldestSentAt } = await emails.stats()
|
|
18
|
+
*
|
|
19
|
+
* In a deployment, in any framework, and under `midsummer dev`, `queue` reaches the queue the
|
|
20
|
+
* environment binds under a name, with nothing to connect:
|
|
21
|
+
*
|
|
22
|
+
* import { queue } from "@midsummer-ai/sdk/queues"
|
|
23
|
+
*
|
|
24
|
+
* await queue("emails").send({ to: "ada@example.com" })
|
|
25
|
+
*
|
|
26
|
+
* The Stand-in keeps Messages in memory, for tests and `midsummer dev`. Code can pull its Messages
|
|
27
|
+
* with `receive`, or a consumer can deliver each one to a path of your site (`midsummer queue
|
|
28
|
+
* consumer set`). Each engine is held to the cases in `@midsummer-ai/sdk/queues/contract`; a
|
|
29
|
+
* behaviour that is not a case there is not promised.
|
|
30
|
+
*
|
|
31
|
+
* Delivery is at least once. A Message received is hidden from other receivers for its visibility
|
|
32
|
+
* window; acked, it is gone; retried, or left until the window ends, it is delivered again, a later
|
|
33
|
+
* time each attempt (10 seconds after the first, doubling, at most 10 minutes). Once it has been
|
|
34
|
+
* delivered `maxAttempts` times (5 unless the receiver says), a retry or an ended window moves it
|
|
35
|
+
* to the Queue's dead-letter Queue, `queue.deadLetter`, where it waits to be read and never moves on.
|
|
36
|
+
* A receipt names one delivery: acking or retrying one whose window has ended does nothing.
|
|
37
|
+
*
|
|
38
|
+
* A send with a `key` is made once: sending the same key to the same Queue again, within a day,
|
|
39
|
+
* returns the first Message's id and sends nothing. Schedules send with one, so a Schedule's minute
|
|
40
|
+
* sends once however often it is reached.
|
|
41
|
+
*
|
|
42
|
+
* Names and bodies are checked here, before anything leaves the caller. Every failure is a
|
|
43
|
+
* `QueueError`, whose `code` is the one the wire carries.
|
|
44
|
+
*/
|
|
45
|
+
/** The wire, loaded on the first call: it reads this module's names as it loads, so it can't load with it. */
|
|
46
|
+
let wire;
|
|
47
|
+
const remoteOver = (transport) => (wire ??= import("./wire.mjs")).then(({ remote }) => remote(transport));
|
|
2
48
|
const queueErrorCodes = [
|
|
3
49
|
"invalid",
|
|
4
50
|
"forbidden",
|
|
@@ -63,6 +109,30 @@ function checkReceive(options) {
|
|
|
63
109
|
if (!whole(options.maxAttempts, 1, 100)) invalid("maxAttempts is 1 to 100");
|
|
64
110
|
}
|
|
65
111
|
/** Queues over `engine`. */
|
|
112
|
+
/**
|
|
113
|
+
* The queue the environment binds under `name`, from code in a deployment in any framework, or
|
|
114
|
+
* `midsummer dev`'s queue of that name.
|
|
115
|
+
*/
|
|
116
|
+
function queue(name) {
|
|
117
|
+
return queues(late(() => {
|
|
118
|
+
const handle = here()?.queues;
|
|
119
|
+
if (handle) return remoteOver(handle);
|
|
120
|
+
const env = processEnv(), url = env.MIDSUMMER_QUEUES_URL, token = env.MIDSUMMER_QUEUES_TOKEN;
|
|
121
|
+
if (url && token) return remoteOver({ async send(frame) {
|
|
122
|
+
const response = await fetch(url, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: {
|
|
125
|
+
authorization: `Bearer ${token}`,
|
|
126
|
+
"content-type": "application/octet-stream"
|
|
127
|
+
},
|
|
128
|
+
body: frame
|
|
129
|
+
}).catch(() => void 0);
|
|
130
|
+
if (!response || response.status !== 200) throw new QueueError("unavailable", "Queues could not be reached. Is midsummer dev still running?");
|
|
131
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
132
|
+
} });
|
|
133
|
+
throw new QueueError("forbidden", "This code runs outside Midsummer, so no environment binds a queue for it.");
|
|
134
|
+
})).queue(name);
|
|
135
|
+
}
|
|
66
136
|
function queues(engine) {
|
|
67
137
|
const queueOf = (name, engineName, dead) => {
|
|
68
138
|
const queue = {
|
|
@@ -123,4 +193,4 @@ function queues(engine) {
|
|
|
123
193
|
} };
|
|
124
194
|
}
|
|
125
195
|
//#endregion
|
|
126
|
-
export { DEAD, MAX_BODY, QueueError, STATS_CAP, backoffMs, bodyText, checkDelaySeconds, checkEngineQueue, checkKey, checkQueueName, checkReceipt, checkReceive, invalid, queueErrorCodes, queues };
|
|
196
|
+
export { DEAD, MAX_BODY, QueueError, STATS_CAP, backoffMs, bodyText, checkDelaySeconds, checkEngineQueue, checkKey, checkQueueName, checkReceipt, checkReceive, invalid, queue, queueErrorCodes, queues };
|
package/s3.d.mts
CHANGED
package/s3.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as checkMetadata, h as StorageError, l as checkUploadId, m as sha256, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-DfCBKupJ.mjs";
|
|
2
|
-
import { streamsOf } from "./
|
|
2
|
+
import { r as streamsOf } from "./src-BKrQAqJN.mjs";
|
|
3
3
|
//#region src/s3.ts
|
|
4
4
|
/**
|
|
5
5
|
* Storage over the S3 protocol, so the tools and SDKs that speak it reach a Project's Buckets
|
package/socket.d.mts
CHANGED
package/socket.mjs
CHANGED
|
@@ -1,263 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { streamsOf } from "./index.mjs";
|
|
3
|
-
import { repeatable, serve } from "./wire.mjs";
|
|
4
|
-
//#region src/socket.ts
|
|
5
|
-
/**
|
|
6
|
-
* Storage's wire over a WebSocket: one connection carries every call, so a client pays for one HTTP
|
|
7
|
-
* request when it connects, not one a call. The frames are the wire's own (`@midsummer-ai/sdk/wire`),
|
|
8
|
-
* each sent with a request id, replied to in any order; `remote` batches over it as over HTTP.
|
|
9
|
-
*
|
|
10
|
-
* const files = storage(remote(socket("wss://api.<site>/storage/socket", { key, secret }), { batch: true }))
|
|
11
|
-
* // an app uses `client` (`@midsummer-ai/sdk/client`): this over one connection, with signed HTTP behind it
|
|
12
|
-
* // on the server, a session a connection:
|
|
13
|
-
* const session = socketSession({ engine, credentials })
|
|
14
|
-
* ws.send(session.greeting); ws.onmessage = async (m) => { const reply = await session.receive(m.data); if (reply) ws.send(reply) }
|
|
15
|
-
*
|
|
16
|
-
* A connection opens with a challenge: the server sends a random one, and the client replies with its
|
|
17
|
-
* Storage Key's id and the HMAC-SHA256 of the challenge under its secret, so the secret never travels.
|
|
18
|
-
* Then each message is a 4-byte little-endian request id followed by a frame, both ways. The key
|
|
19
|
-
* reaches what it would over S3: its own Buckets, by name, writing only if it may and while its
|
|
20
|
-
* Bucket's writes are not paused. A connection lives a minute, or 4,000 calls: the server then says it is closing,
|
|
21
|
-
* replies to what it was sent, and closes, and the client opens a new one for its next call, so a key
|
|
22
|
-
* revoked or a Bucket paused reaches every connection within a minute.
|
|
23
|
-
*/
|
|
24
|
-
const encoder = new TextEncoder();
|
|
25
|
-
const SOCKET_LIFE_MS = 6e4;
|
|
26
|
-
const SOCKET_FRAMES = 4e3;
|
|
27
|
-
const SESSION_CONCURRENCY = 32;
|
|
28
|
-
const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
29
|
-
async function sign(secret, challenge) {
|
|
30
|
-
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
31
|
-
name: "HMAC",
|
|
32
|
-
hash: "SHA-256"
|
|
33
|
-
}, false, ["sign"]);
|
|
34
|
-
return hex(await crypto.subtle.sign("HMAC", key, encoder.encode(challenge)));
|
|
35
|
-
}
|
|
36
|
-
function sameHex(a, b) {
|
|
37
|
-
if (a.length !== b.length) return false;
|
|
38
|
-
let difference = 0;
|
|
39
|
-
for (let i = 0; i < a.length; i += 1) difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
40
|
-
return difference === 0;
|
|
41
|
-
}
|
|
42
|
-
/** The id and frame of a message, or a message from them. */
|
|
43
|
-
function tagged(id, frame) {
|
|
44
|
-
const message = new Uint8Array(4 + frame.length);
|
|
45
|
-
new DataView(message.buffer).setUint32(0, id, true);
|
|
46
|
-
message.set(frame, 4);
|
|
47
|
-
return message;
|
|
48
|
-
}
|
|
49
|
-
const CONNECT_MS = 1e4;
|
|
50
|
-
const FALLBACK_MS = 6e4;
|
|
51
|
-
const SENDS = 3;
|
|
52
|
-
const OPEN = 1;
|
|
53
|
-
/** A connection that never opened: nothing was sent on it, so the call may go another way. */
|
|
54
|
-
var Unreached = class extends StorageError {
|
|
55
|
-
constructor() {
|
|
56
|
-
super("unavailable", "Storage could not be reached");
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
/**
|
|
60
|
-
* A transport over WebSockets to `url` (`connections` of them, 16 when not given), each call sent on
|
|
61
|
-
* the one with the fewest calls in flight: one connection is one invocation on the server, so a few
|
|
62
|
-
* carry more at once. Each opens on its first call and again after it closes. A call in flight when its
|
|
63
|
-
* connection drops (a server going away on deploy closes every connection) is sent again on a new one
|
|
64
|
-
* when the wire says repeating it is safe (`repeatable`), and is otherwise `unavailable`, since it may
|
|
65
|
-
* have been carried out. Where no connection opens, or the runtime has no WebSocket, calls go over
|
|
66
|
-
* `fallback` for a minute, then a connection is tried again; without one they are `unavailable`.
|
|
67
|
-
*/
|
|
68
|
-
function socket(url, options) {
|
|
69
|
-
const lines = Array.from({ length: options.connections ?? 16 }, () => line(url, options));
|
|
70
|
-
const { fallback } = options;
|
|
71
|
-
const clock = options.clock ?? Date.now;
|
|
72
|
-
const noSocket = !options.WebSocket && typeof globalThis.WebSocket !== "function";
|
|
73
|
-
let socketAfter = 0;
|
|
74
|
-
return {
|
|
75
|
-
async send(frame) {
|
|
76
|
-
if (fallback && (noSocket || clock() < socketAfter)) return fallback.send(frame);
|
|
77
|
-
if (noSocket) throw new Unreached();
|
|
78
|
-
try {
|
|
79
|
-
return await lines.reduce((least, one) => one.inFlight() < least.inFlight() ? one : least).send(frame);
|
|
80
|
-
} catch (error) {
|
|
81
|
-
if (!(error instanceof Unreached) || !fallback) throw error;
|
|
82
|
-
socketAfter = clock() + FALLBACK_MS;
|
|
83
|
-
return fallback.send(frame);
|
|
84
|
-
}
|
|
85
|
-
},
|
|
86
|
-
close() {
|
|
87
|
-
for (const one of lines) one.close();
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
/** One connection of a socket transport. */
|
|
92
|
-
function line(url, options) {
|
|
93
|
-
const Socket = options.WebSocket ?? globalThis.WebSocket;
|
|
94
|
-
const waiting = /* @__PURE__ */ new Map();
|
|
95
|
-
let open = null;
|
|
96
|
-
let next = 0;
|
|
97
|
-
function connect() {
|
|
98
|
-
if (open) return open;
|
|
99
|
-
let ws;
|
|
100
|
-
try {
|
|
101
|
-
ws = new Socket(url);
|
|
102
|
-
} catch {
|
|
103
|
-
return Promise.reject(new Unreached());
|
|
104
|
-
}
|
|
105
|
-
const opening = new Promise((ready, refused) => {
|
|
106
|
-
ws.binaryType = "arraybuffer";
|
|
107
|
-
const late = setTimeout(() => (closed(), ws.close(1e3, "too slow")), CONNECT_MS);
|
|
108
|
-
const lost = (error) => {
|
|
109
|
-
clearTimeout(late);
|
|
110
|
-
open = null;
|
|
111
|
-
refused(error);
|
|
112
|
-
ws.close(1e3, "refused");
|
|
113
|
-
};
|
|
114
|
-
ws.addEventListener("message", (event) => {
|
|
115
|
-
if (typeof event.data === "string") {
|
|
116
|
-
const said = JSON.parse(event.data);
|
|
117
|
-
if (said.challenge !== void 0) sign(options.secret, said.challenge).then((signature) => ws.send(JSON.stringify({
|
|
118
|
-
key: options.key,
|
|
119
|
-
signature
|
|
120
|
-
})));
|
|
121
|
-
else if (said.ready) clearTimeout(late), ready(ws);
|
|
122
|
-
else if (said.closing) open = null;
|
|
123
|
-
else lost(new StorageError("forbidden", said.refused ?? "Storage refused the key"));
|
|
124
|
-
return;
|
|
125
|
-
}
|
|
126
|
-
const message = new Uint8Array(event.data);
|
|
127
|
-
const id = new DataView(message.buffer, message.byteOffset).getUint32(0, true);
|
|
128
|
-
waiting.get(id)?.done(message.subarray(4));
|
|
129
|
-
waiting.delete(id);
|
|
130
|
-
});
|
|
131
|
-
const closed = () => {
|
|
132
|
-
clearTimeout(late);
|
|
133
|
-
if (open === opening) open = null;
|
|
134
|
-
refused(new Unreached());
|
|
135
|
-
for (const [id, call] of waiting) if (call.on === ws) waiting.delete(id), call.lost();
|
|
136
|
-
};
|
|
137
|
-
ws.addEventListener("close", closed);
|
|
138
|
-
ws.addEventListener("error", closed);
|
|
139
|
-
});
|
|
140
|
-
return open = opening;
|
|
141
|
-
}
|
|
142
|
-
return {
|
|
143
|
-
inFlight: () => waiting.size,
|
|
144
|
-
async send(frame) {
|
|
145
|
-
for (let sends = 0;;) {
|
|
146
|
-
const opening = connect();
|
|
147
|
-
const ws = await opening;
|
|
148
|
-
const id = next = next + 1 >>> 0;
|
|
149
|
-
const sent = ws.readyState === OPEN;
|
|
150
|
-
const answer = await new Promise((done) => {
|
|
151
|
-
waiting.set(id, {
|
|
152
|
-
on: ws,
|
|
153
|
-
done,
|
|
154
|
-
lost: () => done(null)
|
|
155
|
-
});
|
|
156
|
-
if (sent) ws.send(tagged(id, frame));
|
|
157
|
-
else waiting.delete(id), done(null);
|
|
158
|
-
});
|
|
159
|
-
if (answer) return answer;
|
|
160
|
-
if (!sent) {
|
|
161
|
-
if (open === opening) open = null;
|
|
162
|
-
continue;
|
|
163
|
-
}
|
|
164
|
-
sends += 1;
|
|
165
|
-
if (!repeatable(frame)) throw new StorageError("unavailable", "The connection to Storage closed before it answered; the call may have been carried out");
|
|
166
|
-
if (sends === SENDS) throw new StorageError("unavailable", "The connection to Storage closed before it answered");
|
|
167
|
-
}
|
|
168
|
-
},
|
|
169
|
-
close() {
|
|
170
|
-
open?.then((ws) => ws.close(1e3, "done"), () => {});
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* `engine` as a Storage Key reaches it: its Buckets by name (every Bucket, under its own name, when it
|
|
176
|
-
* names none), reading always, writing only with `write` access and while the Bucket's writes are not
|
|
177
|
-
* paused. Metering is the platform's, never a key's.
|
|
178
|
-
*/
|
|
179
|
-
function keyed(engine, credential) {
|
|
180
|
-
const id = (name) => {
|
|
181
|
-
const map = credential.buckets;
|
|
182
|
-
if (!map) return name;
|
|
183
|
-
if (!Object.hasOwn(map, name)) throw new StorageError("forbidden", `The key may not use the Bucket ${name}`);
|
|
184
|
-
return map[name];
|
|
185
|
-
};
|
|
186
|
-
const writable = (name) => {
|
|
187
|
-
if (credential.access !== "write") throw new StorageError("forbidden", "The key may only read");
|
|
188
|
-
if (credential.paused?.includes(name)) throw new StorageError("quota", `Writes to the Bucket ${name} are paused: its Team reached its budget`);
|
|
189
|
-
return id(name);
|
|
190
|
-
};
|
|
191
|
-
const metering = async () => {
|
|
192
|
-
throw new StorageError("forbidden", "Metering is not answered to a key");
|
|
193
|
-
};
|
|
194
|
-
return {
|
|
195
|
-
put: (bucket, ...rest) => engine.put(writable(bucket), ...rest),
|
|
196
|
-
get: (bucket, ...rest) => engine.get(id(bucket), ...rest),
|
|
197
|
-
head: (bucket, ...rest) => engine.head(id(bucket), ...rest),
|
|
198
|
-
delete: (bucket, ...rest) => engine.delete(writable(bucket), ...rest),
|
|
199
|
-
list: (bucket, ...rest) => engine.list(id(bucket), ...rest),
|
|
200
|
-
copy: (bucket, ...rest) => engine.copy(writable(bucket), ...rest),
|
|
201
|
-
createUpload: (bucket, ...rest) => engine.createUpload(writable(bucket), ...rest),
|
|
202
|
-
uploadPart: (bucket, ...rest) => engine.uploadPart(writable(bucket), ...rest),
|
|
203
|
-
completeUpload: (bucket, ...rest) => engine.completeUpload(writable(bucket), ...rest),
|
|
204
|
-
abortUpload: (bucket, ...rest) => engine.abortUpload(writable(bucket), ...rest),
|
|
205
|
-
usage: metering,
|
|
206
|
-
operations: metering,
|
|
207
|
-
...streamsOf(engine, id, writable)
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
/** A server's side of one connection: the handshake against `credentials`, then each frame served by `engine` as the key reaches it. */
|
|
211
|
-
function socketSession(options) {
|
|
212
|
-
const challenge = hex(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)).buffer);
|
|
213
|
-
let answer = null;
|
|
214
|
-
let closing = false, inFlight = 0, frames = 0, drained = null;
|
|
215
|
-
const turns = [];
|
|
216
|
-
let settle;
|
|
217
|
-
const settled = new Promise((resolve) => settle = resolve);
|
|
218
|
-
return {
|
|
219
|
-
greeting: JSON.stringify({ challenge }),
|
|
220
|
-
closing: JSON.stringify({ closing: true }),
|
|
221
|
-
life: SOCKET_LIFE_MS,
|
|
222
|
-
spent: () => frames >= SOCKET_FRAMES,
|
|
223
|
-
idle() {
|
|
224
|
-
closing = true;
|
|
225
|
-
return inFlight === 0 ? Promise.resolve() : new Promise((resolve) => drained = resolve);
|
|
226
|
-
},
|
|
227
|
-
settled,
|
|
228
|
-
async receive(message) {
|
|
229
|
-
if (typeof message === "string") {
|
|
230
|
-
if (answer) return null;
|
|
231
|
-
let said;
|
|
232
|
-
try {
|
|
233
|
-
said = JSON.parse(message);
|
|
234
|
-
} catch {
|
|
235
|
-
said = {};
|
|
236
|
-
}
|
|
237
|
-
const credential = typeof said.key === "string" ? await options.credentials(said.key) : null;
|
|
238
|
-
if (!credential || typeof said.signature !== "string" || !sameHex(await sign(credential.secret, challenge), said.signature)) {
|
|
239
|
-
settle("refused");
|
|
240
|
-
return JSON.stringify({ refused: "The key is unknown, or the signature does not match" });
|
|
241
|
-
}
|
|
242
|
-
answer = serve(keyed(options.engine, credential));
|
|
243
|
-
settle("ready");
|
|
244
|
-
return JSON.stringify({ ready: true });
|
|
245
|
-
}
|
|
246
|
-
if (!answer) return null;
|
|
247
|
-
const bytes = message instanceof Uint8Array ? message : message instanceof Blob ? new Uint8Array(await message.arrayBuffer()) : new Uint8Array(message);
|
|
248
|
-
const id = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0, true);
|
|
249
|
-
inFlight += 1;
|
|
250
|
-
frames += 1;
|
|
251
|
-
if (inFlight > SESSION_CONCURRENCY) await new Promise((go) => turns.push(go));
|
|
252
|
-
try {
|
|
253
|
-
return tagged(id, await answer(bytes.subarray(4)));
|
|
254
|
-
} finally {
|
|
255
|
-
inFlight -= 1;
|
|
256
|
-
turns.shift()?.();
|
|
257
|
-
if (closing && inFlight === 0) drained?.();
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
//#endregion
|
|
1
|
+
import { d as sign, f as socket, l as keyed, p as socketSession, u as sameHex } from "./src-BKrQAqJN.mjs";
|
|
263
2
|
export { keyed, sameHex, sign, socket, socketSession };
|