@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/src-BKrQAqJN.mjs
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
import { a as checkMetadata, c as checkRange, d as invalid, h as StorageError, i as checkListLimit, l as checkUploadId, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-DfCBKupJ.mjs";
|
|
2
|
+
import { bucketsOf, remote, repeatable, serve } from "./wire.mjs";
|
|
3
|
+
import { n as late, r as processEnv, t as here } from "./here-CeqGJW21.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
|
|
263
|
+
//#region src/client.ts
|
|
264
|
+
/**
|
|
265
|
+
* Storage from code holding a Storage Key, as an app reaches it: calls are written as usual and travel
|
|
266
|
+
* over one WebSocket, so a client pays for one request when it connects, not one a call. Where a
|
|
267
|
+
* connection cannot open, they travel as batched HTTP, signed with the same key.
|
|
268
|
+
*
|
|
269
|
+
* const files = storage(client("https://api.<site>", { key, secret }))
|
|
270
|
+
* await files.bucket("avatars").put("ada.png", bytes)
|
|
271
|
+
*
|
|
272
|
+
* The calls made in the same turn travel as one batch frame either way. A call whose connection drops
|
|
273
|
+
* before it gets a reply (a server going away on deploy) is sent again on a new connection when the wire
|
|
274
|
+
* says repeating it is safe (`repeatable` in `@midsummer-ai/sdk/wire`), and is otherwise `unavailable`.
|
|
275
|
+
*
|
|
276
|
+
* Signed HTTP is one POST of a frame to `<origin>/storage/frames`, with
|
|
277
|
+
* `authorization: Midsummer-Key key=<id>, time=<ms>, signature=<hex>`: the HMAC-SHA256, under the key's
|
|
278
|
+
* secret, of the time and the frame's SHA-256 (`<time>\n<hex>`). The secret never travels, and a server
|
|
279
|
+
* (`serveSigned`) refuses a signature more than five minutes from its own clock.
|
|
280
|
+
*/
|
|
281
|
+
const SOCKET_PATH = "/storage/socket";
|
|
282
|
+
const FRAMES_PATH = "/storage/frames";
|
|
283
|
+
const SKEW_MS = 3e5;
|
|
284
|
+
/**
|
|
285
|
+
* Storage's engine at `origin` (the API's, `https://api.<site>`) for the Storage Key `key`: one socket,
|
|
286
|
+
* batched HTTP where it cannot open. `close` ends the connection; the next call opens another.
|
|
287
|
+
*/
|
|
288
|
+
function client(origin, options) {
|
|
289
|
+
const base = origin.replace(/\/+$/, "");
|
|
290
|
+
const http = signedHttp(`${base}${FRAMES_PATH}`, options);
|
|
291
|
+
const transport = socket(`${base.replace(/^http/, "ws")}${SOCKET_PATH}`, {
|
|
292
|
+
...options,
|
|
293
|
+
connections: 1,
|
|
294
|
+
fallback: http
|
|
295
|
+
});
|
|
296
|
+
return {
|
|
297
|
+
...remote(transport, { batch: true }),
|
|
298
|
+
close: () => transport.close()
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
async function sha256(bytes) {
|
|
302
|
+
return [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* A transport over HTTP signed with a Storage Key: each frame is one POST to `url`, replied to by
|
|
306
|
+
* `serveSigned`, and sent once more when the request or its answer's body fails and the frame is
|
|
307
|
+
* `repeatable`. A refused key is `forbidden`; a server that cannot be reached, or replies with anything but
|
|
308
|
+
* a frame, is `unavailable`.
|
|
309
|
+
*/
|
|
310
|
+
function signedHttp(url, options) {
|
|
311
|
+
const send = options.fetch ?? ((to, init) => fetch(to, init));
|
|
312
|
+
const clock = options.clock ?? Date.now;
|
|
313
|
+
return { async send(frame) {
|
|
314
|
+
const time = clock();
|
|
315
|
+
const signature = await sign(options.secret, `${time}\n${await sha256(frame)}`);
|
|
316
|
+
for (let sends = 1;; sends += 1) {
|
|
317
|
+
const lost = () => {
|
|
318
|
+
if (sends === 2 || !repeatable(frame)) throw new StorageError("unavailable", "Storage could not be reached");
|
|
319
|
+
};
|
|
320
|
+
let response;
|
|
321
|
+
try {
|
|
322
|
+
response = await send(url, {
|
|
323
|
+
method: "POST",
|
|
324
|
+
headers: {
|
|
325
|
+
authorization: `Midsummer-Key key=${options.key}, time=${time}, signature=${signature}`,
|
|
326
|
+
"content-type": "application/octet-stream"
|
|
327
|
+
},
|
|
328
|
+
body: frame
|
|
329
|
+
});
|
|
330
|
+
} catch {
|
|
331
|
+
lost();
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (response.status === 401 || response.status === 403) throw new StorageError("forbidden", "Storage refused the key");
|
|
335
|
+
if (response.status !== 200) throw new StorageError("unavailable", `Storage answered ${response.status}`);
|
|
336
|
+
try {
|
|
337
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
338
|
+
} catch {
|
|
339
|
+
lost();
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
} };
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Serves `signedHttp` transports: a POST of one frame, signed by a key `credentials` knows, gets one
|
|
346
|
+
* answer frame from `engine` as that key reaches it (`keyed`). Anything else is 405 or 401.
|
|
347
|
+
*/
|
|
348
|
+
function serveSigned(options) {
|
|
349
|
+
const clock = options.clock ?? Date.now;
|
|
350
|
+
return async (request) => {
|
|
351
|
+
if (request.method !== "POST") return new Response(null, { status: 405 });
|
|
352
|
+
const said = /^Midsummer-Key key=([^,\s]+), time=(\d+), signature=([0-9a-f]{64})$/.exec(request.headers.get("authorization") ?? "");
|
|
353
|
+
const frame = new Uint8Array(await request.arrayBuffer());
|
|
354
|
+
if (!said || Math.abs(clock() - Number(said[2])) > SKEW_MS) return new Response(null, { status: 401 });
|
|
355
|
+
const credential = await options.credentials(said[1], bucketsOf(frame));
|
|
356
|
+
if (!credential || !sameHex(await sign(credential.secret, `${said[2]}\n${await sha256(frame)}`), said[3])) return new Response(null, { status: 401 });
|
|
357
|
+
const answer = await serve(keyed(options.engine, credential))(frame);
|
|
358
|
+
return new Response(answer, {
|
|
359
|
+
status: 200,
|
|
360
|
+
headers: { "content-type": "application/octet-stream" }
|
|
361
|
+
});
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
//#endregion
|
|
365
|
+
//#region src/index.ts
|
|
366
|
+
/**
|
|
367
|
+
* The SDK: the one package your project's code imports to use Midsummer's products. This entry is
|
|
368
|
+
* storage: your team's files, kept in buckets.
|
|
369
|
+
*
|
|
370
|
+
* In your deployment, in any framework, `bucket` reaches a bucket by the name the environment binds
|
|
371
|
+
* it under (`midsummer env binding set`), so `avatars` can be one bucket in production and another
|
|
372
|
+
* in preview. Under `midsummer dev`, each name is a bucket of its own:
|
|
373
|
+
*
|
|
374
|
+
* import { bucket } from "@midsummer-ai/sdk"
|
|
375
|
+
*
|
|
376
|
+
* const avatars = bucket("avatars")
|
|
377
|
+
* await avatars.put("ada.png", new Uint8Array(await request.arrayBuffer()), { contentType: "image/png" })
|
|
378
|
+
* const page = await avatars.list({ prefix: "2026/", delimiter: "/" })
|
|
379
|
+
*
|
|
380
|
+
* Code that runs outside Midsummer connects with a storage key (`midsummer storage key create`):
|
|
381
|
+
*
|
|
382
|
+
* import { storage } from "@midsummer-ai/sdk"
|
|
383
|
+
* import { client } from "@midsummer-ai/sdk/client"
|
|
384
|
+
*
|
|
385
|
+
* const files = storage(client("https://api.midsummer.new", { key, secret }))
|
|
386
|
+
*
|
|
387
|
+
* In tests, `standIn` from `@midsummer-ai/sdk/stand-in` keeps files in memory. All three pass the same
|
|
388
|
+
* tests, in `@midsummer-ai/sdk/contract`, and only what those tests check is guaranteed.
|
|
389
|
+
*
|
|
390
|
+
* Bucket names and keys are checked before a request is sent. Every failure is a `StorageError`,
|
|
391
|
+
* and its `code` shows which kind. Reading a key with nothing stored returns `null`, not an error.
|
|
392
|
+
*/
|
|
393
|
+
/**
|
|
394
|
+
* The streaming methods of `engine` an engine wrapping it passes on, with each Bucket named as `read`
|
|
395
|
+
* (for `stream`) and `write` (for the rest) turn it; none where `engine` has none.
|
|
396
|
+
*/
|
|
397
|
+
function streamsOf(engine, read, write) {
|
|
398
|
+
const { stream, putStream, uploadPartStream } = engine;
|
|
399
|
+
return {
|
|
400
|
+
...stream ? { stream: (bucket, key, range) => stream.call(engine, read(bucket), key, range) } : {},
|
|
401
|
+
...putStream ? { putStream: (bucket, key, body, size, options) => putStream.call(engine, write(bucket), key, body, size, options) } : {},
|
|
402
|
+
...uploadPartStream ? { uploadPartStream: (bucket, key, uploadId, partNumber, body, size, sha256) => uploadPartStream.call(engine, write(bucket), key, uploadId, partNumber, body, size, sha256) } : {}
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
/** `midsummer dev`'s Stand-in, reached once per process with the key it hands the code it runs. */
|
|
406
|
+
let dev;
|
|
407
|
+
/**
|
|
408
|
+
* The bucket the environment binds under `name`, from code in a deployment in any framework, or
|
|
409
|
+
* `midsummer dev`'s bucket of that name. Code that runs outside Midsummer connects with a storage
|
|
410
|
+
* key instead: `storage(client(origin, { key, secret }))`.
|
|
411
|
+
*/
|
|
412
|
+
function bucket(name) {
|
|
413
|
+
return storage(late(() => {
|
|
414
|
+
const handle = here()?.storage;
|
|
415
|
+
if (handle) return remote(handle);
|
|
416
|
+
const env = processEnv(), url = env.MIDSUMMER_STORAGE_URL;
|
|
417
|
+
if (url && env.MIDSUMMER_STORAGE_KEY && env.MIDSUMMER_STORAGE_SECRET) {
|
|
418
|
+
if (dev?.url !== url) dev = {
|
|
419
|
+
url,
|
|
420
|
+
engine: client(url, {
|
|
421
|
+
key: env.MIDSUMMER_STORAGE_KEY,
|
|
422
|
+
secret: env.MIDSUMMER_STORAGE_SECRET
|
|
423
|
+
})
|
|
424
|
+
};
|
|
425
|
+
return dev.engine;
|
|
426
|
+
}
|
|
427
|
+
throw new StorageError("forbidden", "This code runs outside Midsummer, so no environment binds a bucket for it. Connect with a storage key: storage(client(origin, { key, secret })).");
|
|
428
|
+
})).bucket(name);
|
|
429
|
+
}
|
|
430
|
+
/** Storage over `engine`. */
|
|
431
|
+
function storage(engine) {
|
|
432
|
+
return { bucket(name) {
|
|
433
|
+
checkBucketName(name);
|
|
434
|
+
return {
|
|
435
|
+
name,
|
|
436
|
+
async put(key, body, options = {}) {
|
|
437
|
+
checkKey(key);
|
|
438
|
+
const metadata = options.metadata ?? {};
|
|
439
|
+
checkMetadata(metadata);
|
|
440
|
+
if (options.ifMatch !== void 0 && !/^[0-9a-f]{64}$/.test(options.ifMatch)) invalid("ifMatch is not an etag");
|
|
441
|
+
return engine.put(name, key, body instanceof Blob ? await bytesOfBlob(body) : bytesOf(body), {
|
|
442
|
+
contentType: options.contentType ?? "application/octet-stream",
|
|
443
|
+
metadata,
|
|
444
|
+
...options.ifNoneMatch ? { ifNoneMatch: options.ifNoneMatch } : {},
|
|
445
|
+
...options.ifMatch !== void 0 ? { ifMatch: options.ifMatch } : {}
|
|
446
|
+
});
|
|
447
|
+
},
|
|
448
|
+
async get(key, options = {}) {
|
|
449
|
+
checkKey(key);
|
|
450
|
+
if (options.range) checkRange(options.range);
|
|
451
|
+
return engine.get(name, key, options.range);
|
|
452
|
+
},
|
|
453
|
+
async head(key) {
|
|
454
|
+
checkKey(key);
|
|
455
|
+
return engine.head(name, key);
|
|
456
|
+
},
|
|
457
|
+
async delete(key) {
|
|
458
|
+
checkKey(key);
|
|
459
|
+
return engine.delete(name, key);
|
|
460
|
+
},
|
|
461
|
+
async list(options = {}) {
|
|
462
|
+
const limit = options.limit ?? 1e3;
|
|
463
|
+
checkListLimit(limit);
|
|
464
|
+
if (options.delimiter === "") invalid("the delimiter is empty");
|
|
465
|
+
return engine.list(name, {
|
|
466
|
+
prefix: options.prefix ?? "",
|
|
467
|
+
limit,
|
|
468
|
+
...options.delimiter !== void 0 ? { delimiter: options.delimiter } : {},
|
|
469
|
+
...options.after !== void 0 ? { after: options.after } : {}
|
|
470
|
+
});
|
|
471
|
+
},
|
|
472
|
+
async copy(from, to, options = {}) {
|
|
473
|
+
checkKey(from);
|
|
474
|
+
checkKey(to);
|
|
475
|
+
return engine.copy(name, from, to, options.ifNoneMatch ? { ifNoneMatch: options.ifNoneMatch } : {});
|
|
476
|
+
},
|
|
477
|
+
async createUpload(key, options = {}) {
|
|
478
|
+
checkKey(key);
|
|
479
|
+
const metadata = options.metadata ?? {};
|
|
480
|
+
checkMetadata(metadata);
|
|
481
|
+
return engine.createUpload(name, key, {
|
|
482
|
+
contentType: options.contentType ?? "application/octet-stream",
|
|
483
|
+
metadata,
|
|
484
|
+
...options.ifNoneMatch ? { ifNoneMatch: options.ifNoneMatch } : {}
|
|
485
|
+
});
|
|
486
|
+
},
|
|
487
|
+
async uploadPart(key, uploadId, partNumber, body) {
|
|
488
|
+
checkKey(key);
|
|
489
|
+
checkUploadId(uploadId);
|
|
490
|
+
checkPartNumber(partNumber);
|
|
491
|
+
return engine.uploadPart(name, key, uploadId, partNumber, body instanceof Blob ? await bytesOfBlob(body) : bytesOf(body));
|
|
492
|
+
},
|
|
493
|
+
async completeUpload(key, uploadId, parts) {
|
|
494
|
+
checkKey(key);
|
|
495
|
+
checkUploadId(uploadId);
|
|
496
|
+
checkParts(parts);
|
|
497
|
+
return engine.completeUpload(name, key, uploadId, parts.map((p) => ({
|
|
498
|
+
partNumber: p.partNumber,
|
|
499
|
+
etag: p.etag
|
|
500
|
+
})));
|
|
501
|
+
},
|
|
502
|
+
async abortUpload(key, uploadId) {
|
|
503
|
+
checkKey(key);
|
|
504
|
+
checkUploadId(uploadId);
|
|
505
|
+
return engine.abortUpload(name, key, uploadId);
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
} };
|
|
509
|
+
}
|
|
510
|
+
function bytesOf(body) {
|
|
511
|
+
if (typeof body === "string") return new TextEncoder().encode(body);
|
|
512
|
+
if (body instanceof Uint8Array) return body;
|
|
513
|
+
return new Uint8Array(body);
|
|
514
|
+
}
|
|
515
|
+
async function bytesOfBlob(body) {
|
|
516
|
+
return new Uint8Array(await body.arrayBuffer());
|
|
517
|
+
}
|
|
518
|
+
//#endregion
|
|
519
|
+
export { SOCKET_PATH as a, signedHttp as c, sign as d, socket as f, FRAMES_PATH as i, keyed as l, storage as n, client as o, socketSession as p, streamsOf as r, serveSigned as s, bucket as t, sameHex as u };
|
package/stand-in.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Connection } from "./connection-
|
|
1
|
+
import { t as Connection } from "./connection-C_JSWUrt.mjs";
|
|
2
2
|
//#region src/database/client/tabs.mjs
|
|
3
3
|
/** Argument index of the options that take a `tag` (a tab tags its own writes: the same tag after a handover). */
|
|
4
4
|
const TAGGED = {
|
package/vector/contract.d.mts
CHANGED
package/vector/contract.mjs
CHANGED
package/vector/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as VectorControl, B as
|
|
2
|
-
export { Aggregate, AggregateGroup, AggregateOptions, Condition, Consistency, EngineAggregate, EngineList, EngineMultiQuery, EnginePart, EngineQuery, EngineTextSearch, Filter, ListOptions, Listed, MAX_BATCH, MAX_DIMENSION, MAX_FULL_TEXT, MAX_METADATA_BYTES, MAX_QUERIES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, Match, MetadataValue, Metric, MultiQueryOptions, MultiQueryPart, MultiQueryResult, Namespace, NamespaceInfo, QueryOptions, Scalar, TextSearchOptions, TextVector, ValuesEngine, ValuesMultiQuery, Vector, VectorControl, VectorDb, VectorEngine, VectorError, type VectorErrorCode, embedded, vectorDb, vectorErrorCodes };
|
|
1
|
+
import { A as VectorControl, B as MAX_QUERIES, C as QueryOptions, D as ValuesEngine, E as TextVector, F as vectorDb, G as VectorErrorCode, H as MAX_TOP_K, I as MAX_BATCH, K as vectorErrorCodes, L as MAX_DIMENSION, M as VectorEngine, N as embedded, O as ValuesMultiQuery, P as namespace, R as MAX_FULL_TEXT, S as NamespaceInfo, T as TextSearchOptions, U as MAX_VALUE, V as MAX_TEXT, W as VectorError, _ as Metric, a as Consistency, b as MultiQueryResult, c as EngineMultiQuery, d as EngineTextSearch, f as Filter, g as MetadataValue, h as Match, i as Condition, j as VectorDb, k as Vector, l as EnginePart, m as Listed, n as AggregateGroup, o as EngineAggregate, p as ListOptions, r as AggregateOptions, s as EngineList, t as Aggregate, u as EngineQuery, v as MultiQueryOptions, w as Scalar, x as Namespace, y as MultiQueryPart, z as MAX_METADATA_BYTES } from "../index-B9zs0wIp.mjs";
|
|
2
|
+
export { Aggregate, AggregateGroup, AggregateOptions, Condition, Consistency, EngineAggregate, EngineList, EngineMultiQuery, EnginePart, EngineQuery, EngineTextSearch, Filter, ListOptions, Listed, MAX_BATCH, MAX_DIMENSION, MAX_FULL_TEXT, MAX_METADATA_BYTES, MAX_QUERIES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, Match, MetadataValue, Metric, MultiQueryOptions, MultiQueryPart, MultiQueryResult, Namespace, NamespaceInfo, QueryOptions, Scalar, TextSearchOptions, TextVector, ValuesEngine, ValuesMultiQuery, Vector, VectorControl, VectorDb, VectorEngine, VectorError, type VectorErrorCode, embedded, namespace, vectorDb, vectorErrorCodes };
|
package/vector/index.mjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as late, t as here } from "../here-CeqGJW21.mjs";
|
|
2
|
+
import { C as checked, S as Vectors, T as vectorErrorCodes, _ as MAX_VALUE, b as Query, c as Ids, d as MAX_DIMENSION, f as MAX_FULL_TEXT, g as MAX_TOP_K, h as MAX_TEXT, i as remote, l as List, m as MAX_QUERIES, p as MAX_METADATA_BYTES, s as Aggregation, u as MAX_BATCH, v as MultiQuery, w as VectorError, x as TextSearch, y as NamespaceName } from "../wire-BdNDzlIN.mjs";
|
|
2
3
|
//#region src/vector/index.ts
|
|
3
4
|
/**
|
|
4
5
|
* Vector DB: a Team's Vectors in Vector namespaces, searched by closeness and filtered by their
|
|
5
6
|
* metadata.
|
|
6
7
|
*
|
|
7
|
-
* In your
|
|
8
|
-
*
|
|
8
|
+
* In your deployment, in any framework, `namespace` reaches a namespace by the name the environment
|
|
9
|
+
* binds it under (`midsummer env binding set`):
|
|
9
10
|
*
|
|
10
|
-
* import {
|
|
11
|
-
* import { remote } from "@midsummer-ai/sdk/vector/wire"
|
|
11
|
+
* import { namespace } from "@midsummer-ai/sdk/vector"
|
|
12
12
|
*
|
|
13
|
-
* const docs =
|
|
13
|
+
* const docs = namespace("docs")
|
|
14
14
|
* await docs.upsert([{ id: "intro", values: [0.1, 0.2, 0.3], metadata: { lang: "en" } }])
|
|
15
15
|
* const matches = await docs.query([0.1, 0.2, 0.25], { topK: 5, filter: { lang: "en" }, includeMetadata: true })
|
|
16
16
|
*
|
|
@@ -40,6 +40,17 @@ import { a as MAX_DIMENSION, b as VectorError, c as MAX_QUERIES, d as MAX_VALUE,
|
|
|
40
40
|
* Calls are checked here, before anything leaves the caller. Every failure is a `VectorError`; its
|
|
41
41
|
* `code` tells you which kind, and is the same code the wire carries.
|
|
42
42
|
*/
|
|
43
|
+
/**
|
|
44
|
+
* The namespace the environment binds under `name`, from code in a deployment in any framework.
|
|
45
|
+
* Tests use `vectorDb(standIn())` instead.
|
|
46
|
+
*/
|
|
47
|
+
function namespace(name) {
|
|
48
|
+
return vectorDb(late(() => {
|
|
49
|
+
const handle = here()?.vector;
|
|
50
|
+
if (handle) return remote(handle);
|
|
51
|
+
throw new VectorError("forbidden", "This code runs outside a deployment, so no environment binds a Vector DB namespace for it.");
|
|
52
|
+
})).namespace(name);
|
|
53
|
+
}
|
|
43
54
|
/** Vector DB over `engine`. */
|
|
44
55
|
function vectorDb(engine) {
|
|
45
56
|
return { namespace(name) {
|
|
@@ -173,4 +184,4 @@ function embedded(engine, embed) {
|
|
|
173
184
|
};
|
|
174
185
|
}
|
|
175
186
|
//#endregion
|
|
176
|
-
export { MAX_BATCH, MAX_DIMENSION, MAX_FULL_TEXT, MAX_METADATA_BYTES, MAX_QUERIES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, VectorError, embedded, vectorDb, vectorErrorCodes };
|
|
187
|
+
export { MAX_BATCH, MAX_DIMENSION, MAX_FULL_TEXT, MAX_METADATA_BYTES, MAX_QUERIES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, VectorError, embedded, namespace, vectorDb, vectorErrorCodes };
|
package/vector/stand-in.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as VectorControl, M as VectorEngine } from "../index-
|
|
1
|
+
import { A as VectorControl, M as VectorEngine } from "../index-B9zs0wIp.mjs";
|
|
2
2
|
//#region src/vector/stand-in.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* A text's Stand-in embedding of `dimension` numbers: each word (letters and digits, in lower case)
|
package/vector/stand-in.mjs
CHANGED
package/vector/wire.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as VectorControl, M as VectorEngine } from "../index-
|
|
1
|
+
import { A as VectorControl, M as VectorEngine } from "../index-B9zs0wIp.mjs";
|
|
2
2
|
//#region src/vector/wire.d.ts
|
|
3
3
|
/** Carries one request frame to a server and brings back its answer frame. */
|
|
4
4
|
interface Transport {
|