stateplane 0.0.0-stage → 0.0.1
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/README.md +10 -2
- package/bin/keychain.swift +19 -0
- package/bin/secure-acl.ps1 +69 -0
- package/bin/stateplane.js +4 -0
- package/dist/config.d.ts +41 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1329 -0
- package/dist/run.d.ts +3 -0
- package/dist/transport.d.ts +54 -0
- package/package.json +24 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1329 @@
|
|
|
1
|
+
// ../contracts/dist/analysis.js
|
|
2
|
+
var analysisBounds = Object.freeze({ bodyBytes: 262144, specBytes: 32768, requestBytes: 33792, specDepth: 16 });
|
|
3
|
+
var object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
4
|
+
function utf8Bytes(text) {
|
|
5
|
+
let bytes = 0;
|
|
6
|
+
for (let i = 0; i < text.length; i++) {
|
|
7
|
+
const code = text.charCodeAt(i);
|
|
8
|
+
if (code < 128)
|
|
9
|
+
bytes += 1;
|
|
10
|
+
else if (code < 2048)
|
|
11
|
+
bytes += 2;
|
|
12
|
+
else if (code >= 55296 && code < 56320 && (text.charCodeAt(i + 1) & 64512) === 56320) {
|
|
13
|
+
bytes += 4;
|
|
14
|
+
i++;
|
|
15
|
+
} else
|
|
16
|
+
bytes += 3;
|
|
17
|
+
}
|
|
18
|
+
return bytes;
|
|
19
|
+
}
|
|
20
|
+
function encode(value, limit) {
|
|
21
|
+
const parts = [];
|
|
22
|
+
const stack = [];
|
|
23
|
+
const active = /* @__PURE__ */ new Set();
|
|
24
|
+
let bytes = 0, depth = 0, finite = true;
|
|
25
|
+
const write = (text) => {
|
|
26
|
+
parts.push(text);
|
|
27
|
+
bytes += utf8Bytes(text);
|
|
28
|
+
return bytes <= limit;
|
|
29
|
+
};
|
|
30
|
+
const string = (text) => text.length <= limit - bytes && write(JSON.stringify(text));
|
|
31
|
+
const emit = (item) => {
|
|
32
|
+
let written;
|
|
33
|
+
if (item === null)
|
|
34
|
+
written = write("null");
|
|
35
|
+
else if (typeof item === "string")
|
|
36
|
+
written = string(item);
|
|
37
|
+
else if (typeof item === "boolean")
|
|
38
|
+
written = write(item ? "true" : "false");
|
|
39
|
+
else if (typeof item === "number") {
|
|
40
|
+
if (Number.isNaN(item))
|
|
41
|
+
return "invalid";
|
|
42
|
+
if (!Number.isFinite(item))
|
|
43
|
+
finite = false;
|
|
44
|
+
written = write(item === Infinity ? "1e400" : item === -Infinity ? "-1e400" : Object.is(item, -0) ? "-0" : JSON.stringify(item));
|
|
45
|
+
} else if (item && typeof item === "object") {
|
|
46
|
+
if (active.has(item))
|
|
47
|
+
return "invalid";
|
|
48
|
+
active.add(item);
|
|
49
|
+
const keys = Array.isArray(item) ? null : Object.keys(item);
|
|
50
|
+
stack.push({ node: item, keys, index: 0 });
|
|
51
|
+
if (stack.length > depth)
|
|
52
|
+
depth = stack.length;
|
|
53
|
+
written = write(keys ? "{" : "[");
|
|
54
|
+
} else
|
|
55
|
+
return "invalid";
|
|
56
|
+
return written ? "ok" : "over";
|
|
57
|
+
};
|
|
58
|
+
let step = emit(value);
|
|
59
|
+
while (step === "ok" && stack.length) {
|
|
60
|
+
const frame = stack[stack.length - 1];
|
|
61
|
+
const length = frame.keys ? frame.keys.length : frame.node.length;
|
|
62
|
+
if (frame.index === length) {
|
|
63
|
+
active.delete(frame.node);
|
|
64
|
+
stack.pop();
|
|
65
|
+
if (!write(frame.keys ? "}" : "]"))
|
|
66
|
+
step = "over";
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (frame.index && !write(",")) {
|
|
70
|
+
step = "over";
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const at = frame.index++;
|
|
74
|
+
let item;
|
|
75
|
+
if (frame.keys) {
|
|
76
|
+
const key = frame.keys[at];
|
|
77
|
+
if (!string(key) || !write(":")) {
|
|
78
|
+
step = "over";
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
item = frame.node[key];
|
|
82
|
+
} else
|
|
83
|
+
item = frame.node[at];
|
|
84
|
+
step = emit(item);
|
|
85
|
+
}
|
|
86
|
+
if (step !== "ok")
|
|
87
|
+
return step === "over" ? "over" : void 0;
|
|
88
|
+
return { text: parts.join(""), depth, finite };
|
|
89
|
+
}
|
|
90
|
+
function admitAggregation(spec) {
|
|
91
|
+
const encoded2 = encode(spec, analysisBounds.specBytes);
|
|
92
|
+
if (!encoded2)
|
|
93
|
+
return { refused: "INVALID_ARGUMENT" };
|
|
94
|
+
if (encoded2 === "over")
|
|
95
|
+
return { refused: "RATE_LIMITED" };
|
|
96
|
+
if (encoded2.depth > analysisBounds.specDepth || !object(spec) || !encoded2.finite)
|
|
97
|
+
return { refused: "INVALID_ARGUMENT" };
|
|
98
|
+
return { spec: encoded2.text };
|
|
99
|
+
}
|
|
100
|
+
function admitAnalysisJob(request) {
|
|
101
|
+
const encoded2 = encode(request, analysisBounds.requestBytes);
|
|
102
|
+
if (!encoded2)
|
|
103
|
+
return { refused: "INVALID_ARGUMENT" };
|
|
104
|
+
if (encoded2 === "over")
|
|
105
|
+
return { refused: "RATE_LIMITED" };
|
|
106
|
+
if (!object(request) || Object.keys(request).some((key) => key !== "kind" && key !== "spec"))
|
|
107
|
+
return { refused: "INVALID_ARGUMENT" };
|
|
108
|
+
const kind = Object.hasOwn(request, "kind") ? request.kind : void 0;
|
|
109
|
+
if (kind !== "aggregate" && kind !== "export")
|
|
110
|
+
return { refused: "INVALID_ARGUMENT" };
|
|
111
|
+
if (!Object.hasOwn(request, "spec"))
|
|
112
|
+
return { kind, spec: void 0 };
|
|
113
|
+
const spec = encode(request.spec, analysisBounds.specBytes);
|
|
114
|
+
if (spec === "over")
|
|
115
|
+
return { refused: "RATE_LIMITED" };
|
|
116
|
+
if (spec.depth > analysisBounds.specDepth || !object(request.spec) || !spec.finite)
|
|
117
|
+
return { refused: "INVALID_ARGUMENT" };
|
|
118
|
+
return { kind, spec: spec.text };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ../contracts/dist/index.js
|
|
122
|
+
var isSafeInteger = Number.isSafeInteger;
|
|
123
|
+
var capabilityMembers = {
|
|
124
|
+
"records:read": true,
|
|
125
|
+
"records:write": true,
|
|
126
|
+
"events:read": true,
|
|
127
|
+
"schema:write": true,
|
|
128
|
+
"sources:read": true,
|
|
129
|
+
"sources:write": true,
|
|
130
|
+
"claims:read": true,
|
|
131
|
+
"claims:write": true,
|
|
132
|
+
"claims:review": true,
|
|
133
|
+
"export:read": true,
|
|
134
|
+
"space:admin": true
|
|
135
|
+
};
|
|
136
|
+
var capabilities = Object.freeze(Object.keys(capabilityMembers));
|
|
137
|
+
function parseV1Path(pathname) {
|
|
138
|
+
const parts = pathname.split("/").slice(1);
|
|
139
|
+
if (parts[0] !== "v1")
|
|
140
|
+
return null;
|
|
141
|
+
const decoded = [];
|
|
142
|
+
for (const part of parts.slice(1)) {
|
|
143
|
+
try {
|
|
144
|
+
if (part === ";." || part === ";..") {
|
|
145
|
+
decoded.push(part.slice(1));
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const value = decodeURIComponent(part);
|
|
149
|
+
if (!value || value === "." || value === ".." || value.includes("\0") || value.length > 512)
|
|
150
|
+
return null;
|
|
151
|
+
decoded.push(value);
|
|
152
|
+
} catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return decoded;
|
|
157
|
+
}
|
|
158
|
+
function isSafeHttpRead(method, route) {
|
|
159
|
+
if (method === "GET")
|
|
160
|
+
return true;
|
|
161
|
+
if (method !== "POST" || route[0] !== "spaces")
|
|
162
|
+
return false;
|
|
163
|
+
if (route.length === 3)
|
|
164
|
+
return route[2] === "search" || route[2] === "bundles";
|
|
165
|
+
if (route.length === 5)
|
|
166
|
+
return route[2] === "collections" && route[4] === "aggregate";
|
|
167
|
+
return route.length === 6 && route[2] === "collections" && route[4] === "records" && (route[5] === "query" || route[5] === "count");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// src/transport.ts
|
|
171
|
+
var StateplaneCliError = class extends Error {
|
|
172
|
+
constructor(code, requestId, retryAfter2, retryable) {
|
|
173
|
+
super(code);
|
|
174
|
+
this.code = code;
|
|
175
|
+
this.requestId = requestId;
|
|
176
|
+
this.retryAfter = retryAfter2;
|
|
177
|
+
this.name = "StateplaneCliError";
|
|
178
|
+
this.retryable = retryable ?? ["RECEIPT_PENDING", "PROVIDER_UNAVAILABLE", "BACKPRESSURE", "RATE_LIMITED", "STALE_PLACEMENT"].includes(code);
|
|
179
|
+
}
|
|
180
|
+
code;
|
|
181
|
+
requestId;
|
|
182
|
+
retryAfter;
|
|
183
|
+
retryable;
|
|
184
|
+
};
|
|
185
|
+
function serializeBody(body) {
|
|
186
|
+
if (body === void 0) return void 0;
|
|
187
|
+
let serialized;
|
|
188
|
+
try {
|
|
189
|
+
serialized = JSON.stringify(body);
|
|
190
|
+
} catch {
|
|
191
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
192
|
+
}
|
|
193
|
+
if (serialized === void 0) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
194
|
+
return serialized;
|
|
195
|
+
}
|
|
196
|
+
function retryAfter(response) {
|
|
197
|
+
const header = response.headers.get("retry-after");
|
|
198
|
+
return header && /^\d+$/.test(header) ? Math.min(5, Number(header)) : void 0;
|
|
199
|
+
}
|
|
200
|
+
function serverError(value, after) {
|
|
201
|
+
const envelope = value;
|
|
202
|
+
const code = typeof envelope?.error?.code === "string" && /^[A-Z_]{1,64}$/.test(envelope.error.code) ? envelope.error.code : "PROVIDER_UNAVAILABLE";
|
|
203
|
+
const requestId = typeof envelope?.error?.requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(envelope.error.requestId) ? envelope.error.requestId : void 0;
|
|
204
|
+
return new StateplaneCliError(
|
|
205
|
+
code,
|
|
206
|
+
requestId,
|
|
207
|
+
after,
|
|
208
|
+
typeof envelope?.error?.retryable === "boolean" ? envelope.error.retryable : void 0
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
var WireFailure = class extends Error {
|
|
212
|
+
};
|
|
213
|
+
var protectedHeaders = /* @__PURE__ */ new Set([
|
|
214
|
+
"authorization",
|
|
215
|
+
"proxy-authorization",
|
|
216
|
+
"cookie",
|
|
217
|
+
"host",
|
|
218
|
+
"accept",
|
|
219
|
+
"content-type",
|
|
220
|
+
"content-length",
|
|
221
|
+
"transfer-encoding",
|
|
222
|
+
"origin",
|
|
223
|
+
"referer"
|
|
224
|
+
]);
|
|
225
|
+
function requestHeaders(token, serialized, extraHeaders) {
|
|
226
|
+
const headers = {
|
|
227
|
+
Authorization: `Bearer ${token}`,
|
|
228
|
+
Accept: "application/json",
|
|
229
|
+
...serialized === void 0 ? {} : { "Content-Type": "application/json" }
|
|
230
|
+
};
|
|
231
|
+
if (extraHeaders === void 0) return Object.freeze(headers);
|
|
232
|
+
try {
|
|
233
|
+
for (const [name, value] of Object.entries(extraHeaders)) {
|
|
234
|
+
if (typeof value !== "string" || protectedHeaders.has(name.toLowerCase()))
|
|
235
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
236
|
+
new Headers([[name, value]]);
|
|
237
|
+
headers[name.toLowerCase()] = value;
|
|
238
|
+
}
|
|
239
|
+
} catch {
|
|
240
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
241
|
+
}
|
|
242
|
+
return Object.freeze(headers);
|
|
243
|
+
}
|
|
244
|
+
async function wireFetch(fetcher, url, options) {
|
|
245
|
+
try {
|
|
246
|
+
return await fetcher(url, options);
|
|
247
|
+
} catch {
|
|
248
|
+
throw new WireFailure();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
async function wireJson(response) {
|
|
252
|
+
try {
|
|
253
|
+
return await response.json();
|
|
254
|
+
} catch {
|
|
255
|
+
throw new WireFailure();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
function deadlineOf(ms) {
|
|
259
|
+
const signal = AbortSignal.timeout(ms);
|
|
260
|
+
const end = Date.now() + ms;
|
|
261
|
+
return { signal, end, expired: () => signal.aborted || Date.now() >= end };
|
|
262
|
+
}
|
|
263
|
+
var fits = (ms, deadline) => !deadline || !deadline.expired() && Date.now() + ms < deadline.end;
|
|
264
|
+
var StateplaneHttpClient = class {
|
|
265
|
+
endpoint;
|
|
266
|
+
token;
|
|
267
|
+
fetcher;
|
|
268
|
+
timeoutMs;
|
|
269
|
+
sleep;
|
|
270
|
+
constructor(options) {
|
|
271
|
+
const token = options.token;
|
|
272
|
+
try {
|
|
273
|
+
this.endpoint = new URL(options.endpoint);
|
|
274
|
+
} catch {
|
|
275
|
+
throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
276
|
+
}
|
|
277
|
+
if (!["https:", "http:"].includes(this.endpoint.protocol) || this.endpoint.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(this.endpoint.hostname) || this.endpoint.username || this.endpoint.password || this.endpoint.search || this.endpoint.hash || this.endpoint.pathname !== "/" || typeof token !== "string" || !token || /[\r\n\0]/.test(token))
|
|
278
|
+
throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
279
|
+
this.token = token;
|
|
280
|
+
this.fetcher = options.fetch ?? fetch;
|
|
281
|
+
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
282
|
+
if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 12e4)
|
|
283
|
+
throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
284
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
285
|
+
}
|
|
286
|
+
/** One wire attempt; only an explicit safe-read response can request a repeat. A raw
|
|
287
|
+
* exchange returns a successful response unread, for a byte stream, and runs
|
|
288
|
+
* under the download's deadline, which never waits past its end. */
|
|
289
|
+
async exchange(method, url, payload2, headers, safeRead, attempt, deadline) {
|
|
290
|
+
const response = await wireFetch(this.fetcher, url, {
|
|
291
|
+
method,
|
|
292
|
+
redirect: "error",
|
|
293
|
+
signal: deadline?.signal ?? AbortSignal.timeout(this.timeoutMs),
|
|
294
|
+
headers,
|
|
295
|
+
body: payload2
|
|
296
|
+
});
|
|
297
|
+
const after = retryAfter(response);
|
|
298
|
+
if (safeRead && attempt < 2 && [429, 503].includes(response.status) && after !== void 0 && fits(after * 1e3, deadline)) {
|
|
299
|
+
await response.body?.cancel().catch(() => {
|
|
300
|
+
});
|
|
301
|
+
await this.sleep(after * 1e3);
|
|
302
|
+
return { retry: true };
|
|
303
|
+
}
|
|
304
|
+
if (deadline && response.ok) return { retry: false, value: response };
|
|
305
|
+
const value = await wireJson(response);
|
|
306
|
+
if (!response.ok) throw serverError(value, after);
|
|
307
|
+
return { retry: false, value };
|
|
308
|
+
}
|
|
309
|
+
/** Resolve the route before any bearer token is attached to a request. */
|
|
310
|
+
route(path) {
|
|
311
|
+
if (!path.startsWith("/v1/") || path.startsWith("//")) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
312
|
+
let url;
|
|
313
|
+
try {
|
|
314
|
+
url = new URL(path, this.endpoint);
|
|
315
|
+
} catch {
|
|
316
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
317
|
+
}
|
|
318
|
+
const segments = parseV1Path(url.pathname);
|
|
319
|
+
if (url.origin !== this.endpoint.origin || !segments) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
320
|
+
return { url, segments };
|
|
321
|
+
}
|
|
322
|
+
/** A wire failure is ambiguous for writes, but a read can be repeated twice,
|
|
323
|
+
* within a download's deadline. */
|
|
324
|
+
async recoverWireFailure(safeRead, attempt, deadline) {
|
|
325
|
+
if (!safeRead) throw new StateplaneCliError("OUTCOME_UNKNOWN");
|
|
326
|
+
if (attempt >= 2 || !fits(250 * (attempt + 1), deadline)) throw new StateplaneCliError("PROVIDER_UNAVAILABLE");
|
|
327
|
+
await this.sleep(250 * (attempt + 1));
|
|
328
|
+
}
|
|
329
|
+
/** Validate the route once, then bound retries to read-only operations. */
|
|
330
|
+
async request(method, path, body, extraHeaders) {
|
|
331
|
+
const route = this.route(path);
|
|
332
|
+
const serialized = serializeBody(body);
|
|
333
|
+
return this.send(method, route, serialized, requestHeaders(this.token, serialized, extraHeaders));
|
|
334
|
+
}
|
|
335
|
+
/** Read a byte stream, such as a source's original, asking for it unencoded.
|
|
336
|
+
* The response is returned unread once its status is successful, with the
|
|
337
|
+
* deadline that bounds the whole download, including how its body is consumed;
|
|
338
|
+
* an error response is a CLI error. */
|
|
339
|
+
async download(path) {
|
|
340
|
+
const deadline = deadlineOf(this.timeoutMs);
|
|
341
|
+
const response = await this.send(
|
|
342
|
+
"GET",
|
|
343
|
+
this.route(path),
|
|
344
|
+
void 0,
|
|
345
|
+
Object.freeze({ Authorization: `Bearer ${this.token}`, Accept: "*/*", "Accept-Encoding": "identity" }),
|
|
346
|
+
deadline
|
|
347
|
+
);
|
|
348
|
+
return { response, deadline };
|
|
349
|
+
}
|
|
350
|
+
/** Send exact bytes with their media type, such as one upload attempt. Never repeated. */
|
|
351
|
+
async upload(path, bytes, contentType) {
|
|
352
|
+
const route = this.route(path);
|
|
353
|
+
let headers;
|
|
354
|
+
try {
|
|
355
|
+
new Headers([["content-type", contentType]]);
|
|
356
|
+
headers = Object.freeze({ Authorization: `Bearer ${this.token}`, Accept: "application/json", "Content-Type": contentType });
|
|
357
|
+
} catch {
|
|
358
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
359
|
+
}
|
|
360
|
+
return this.send("POST", route, bytes, headers);
|
|
361
|
+
}
|
|
362
|
+
/** A download passes its deadline: every attempt, each pause and the body share it.
|
|
363
|
+
* Any other request gives each attempt its own --timeout. */
|
|
364
|
+
async send(method, { url, segments }, payload2, headers, deadline) {
|
|
365
|
+
const safeRead = isSafeHttpRead(method, segments);
|
|
366
|
+
for (let attempt = 0; attempt < (safeRead ? 3 : 1); attempt++) {
|
|
367
|
+
try {
|
|
368
|
+
const result = await this.exchange(method, url, payload2, headers, safeRead, attempt, deadline);
|
|
369
|
+
if (result.retry) continue;
|
|
370
|
+
return result.value;
|
|
371
|
+
} catch (error) {
|
|
372
|
+
if (!(error instanceof WireFailure)) throw error;
|
|
373
|
+
await this.recoverWireFailure(safeRead, attempt, deadline);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
throw new StateplaneCliError("PROVIDER_UNAVAILABLE");
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
// src/run.ts
|
|
381
|
+
import { createHash } from "node:crypto";
|
|
382
|
+
import { createReadStream } from "node:fs";
|
|
383
|
+
import { open as open2, unlink } from "node:fs/promises";
|
|
384
|
+
|
|
385
|
+
// src/config.ts
|
|
386
|
+
import { spawn } from "node:child_process";
|
|
387
|
+
import { mkdir, readFile, rename, rm, lstat, writeFile, open } from "node:fs/promises";
|
|
388
|
+
import { homedir, platform } from "node:os";
|
|
389
|
+
import { dirname, join } from "node:path";
|
|
390
|
+
import { fileURLToPath } from "node:url";
|
|
391
|
+
function configDir() {
|
|
392
|
+
return process.env.STATEPLANE_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "stateplane");
|
|
393
|
+
}
|
|
394
|
+
var windowsAclScript = join(dirname(fileURLToPath(import.meta.url)), "../bin/secure-acl.ps1");
|
|
395
|
+
async function windowsAcl(path, action) {
|
|
396
|
+
const powershell = join(process.env.SystemRoot ?? String.raw`C:\Windows`, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
397
|
+
const result = await command(powershell, [
|
|
398
|
+
"-NoProfile",
|
|
399
|
+
"-NonInteractive",
|
|
400
|
+
"-ExecutionPolicy",
|
|
401
|
+
"Bypass",
|
|
402
|
+
"-File",
|
|
403
|
+
windowsAclScript,
|
|
404
|
+
"-TargetPath",
|
|
405
|
+
path,
|
|
406
|
+
"-Action",
|
|
407
|
+
action
|
|
408
|
+
]);
|
|
409
|
+
if (!result.ok) throw new StateplaneCliError("INSECURE_CONFIGURATION");
|
|
410
|
+
}
|
|
411
|
+
async function secureDirectory() {
|
|
412
|
+
await mkdir(configDir(), { recursive: true, mode: 448 });
|
|
413
|
+
const stat = await lstat(configDir());
|
|
414
|
+
if (!stat.isDirectory()) throw new StateplaneCliError("INSECURE_CONFIGURATION");
|
|
415
|
+
if (platform() === "win32") await windowsAcl(configDir(), "harden");
|
|
416
|
+
else if ((stat.mode & 63) !== 0) throw new StateplaneCliError("INSECURE_CONFIGURATION");
|
|
417
|
+
}
|
|
418
|
+
var configPath = () => join(configDir(), "config.json");
|
|
419
|
+
var tokenPath = () => join(configDir(), "token");
|
|
420
|
+
var mutationTail = Promise.resolve();
|
|
421
|
+
var sqliteModule;
|
|
422
|
+
function sqlite() {
|
|
423
|
+
if (!sqliteModule) {
|
|
424
|
+
const emitWarning = process.emitWarning;
|
|
425
|
+
process.emitWarning = function(warning, ...args) {
|
|
426
|
+
if (String(warning) === "SQLite is an experimental feature and might change at any time") return;
|
|
427
|
+
return Reflect.apply(emitWarning, process, [warning, ...args]);
|
|
428
|
+
};
|
|
429
|
+
sqliteModule = import("node:sqlite").finally(() => {
|
|
430
|
+
process.emitWarning = emitWarning;
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
return sqliteModule;
|
|
434
|
+
}
|
|
435
|
+
async function withConfigMutation(change) {
|
|
436
|
+
const previous = mutationTail;
|
|
437
|
+
let release;
|
|
438
|
+
mutationTail = new Promise((resolve) => {
|
|
439
|
+
release = resolve;
|
|
440
|
+
});
|
|
441
|
+
await previous;
|
|
442
|
+
let database;
|
|
443
|
+
try {
|
|
444
|
+
await secureDirectory();
|
|
445
|
+
const path = join(configDir(), "config.lock.sqlite");
|
|
446
|
+
try {
|
|
447
|
+
const file = await open(path, "wx", 384);
|
|
448
|
+
await file.close();
|
|
449
|
+
} catch (error) {
|
|
450
|
+
if (error.code !== "EEXIST") throw error;
|
|
451
|
+
}
|
|
452
|
+
if (platform() === "win32") await windowsAcl(path, "harden");
|
|
453
|
+
await privateFile(path);
|
|
454
|
+
const { DatabaseSync } = await sqlite();
|
|
455
|
+
database = new DatabaseSync(path);
|
|
456
|
+
database.exec("PRAGMA busy_timeout = 120000");
|
|
457
|
+
try {
|
|
458
|
+
database.exec("BEGIN IMMEDIATE");
|
|
459
|
+
} catch (error) {
|
|
460
|
+
if (String(error).includes("database is locked"))
|
|
461
|
+
throw new StateplaneCliError("CONFIGURATION_BUSY", void 0, void 0, true);
|
|
462
|
+
throw error;
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
const result = await change(await readConfig());
|
|
466
|
+
database.exec("COMMIT");
|
|
467
|
+
return result;
|
|
468
|
+
} catch (error) {
|
|
469
|
+
database.exec("ROLLBACK");
|
|
470
|
+
throw error;
|
|
471
|
+
}
|
|
472
|
+
} finally {
|
|
473
|
+
database?.close();
|
|
474
|
+
release();
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
async function privateFile(path) {
|
|
478
|
+
try {
|
|
479
|
+
const stat = await lstat(path);
|
|
480
|
+
if (!stat.isFile()) throw new StateplaneCliError("INSECURE_CONFIGURATION");
|
|
481
|
+
if (platform() === "win32") await windowsAcl(path, "verify");
|
|
482
|
+
else if ((stat.mode & 63) !== 0) throw new StateplaneCliError("INSECURE_CONFIGURATION");
|
|
483
|
+
return true;
|
|
484
|
+
} catch (error) {
|
|
485
|
+
if (error.code === "ENOENT") return false;
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
async function readConfig() {
|
|
490
|
+
try {
|
|
491
|
+
await lstat(configDir());
|
|
492
|
+
await secureDirectory();
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (error.code !== "ENOENT") throw error;
|
|
495
|
+
}
|
|
496
|
+
if (!await privateFile(configPath())) return {};
|
|
497
|
+
try {
|
|
498
|
+
const value = JSON.parse(await readFile(configPath(), "utf8"));
|
|
499
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !["endpoint", "space", "tokenStore", "tokenLocations"].includes(key)) || value.endpoint !== void 0 && typeof value.endpoint !== "string" || value.space !== void 0 && typeof value.space !== "string" || value.tokenStore !== void 0 && !["file", "keychain"].includes(value.tokenStore) || value.tokenLocations !== void 0 && (!value.endpoint || !Array.isArray(value.tokenLocations) || value.tokenLocations.length < 1 || value.tokenLocations.length > 2 || new Set(value.tokenLocations).size !== value.tokenLocations.length || value.tokenLocations.some((store) => store !== "file" && store !== "keychain") || value.tokenStore !== void 0 && !value.tokenLocations.includes(value.tokenStore)))
|
|
500
|
+
throw new Error("invalid");
|
|
501
|
+
return value;
|
|
502
|
+
} catch {
|
|
503
|
+
throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async function saveConfig(value) {
|
|
507
|
+
await secureDirectory();
|
|
508
|
+
const temp = join(configDir(), `.config-${process.pid}-${crypto.randomUUID()}`);
|
|
509
|
+
try {
|
|
510
|
+
await writeFile(temp, JSON.stringify(value) + "\n", { mode: 384, flag: "wx" });
|
|
511
|
+
if (platform() === "win32") await windowsAcl(temp, "harden");
|
|
512
|
+
await rename(temp, configPath());
|
|
513
|
+
} finally {
|
|
514
|
+
await rm(temp, { force: true });
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
function keyArgs(endpoint2) {
|
|
518
|
+
return ["service", "stateplane", "endpoint", endpoint2];
|
|
519
|
+
}
|
|
520
|
+
var macKeychainScript = join(dirname(fileURLToPath(import.meta.url)), "../bin/keychain.swift");
|
|
521
|
+
function macKeychain(operation, endpoint2, stdin, run = command) {
|
|
522
|
+
return run("/usr/bin/xcrun", ["--sdk", "macosx", "swift", macKeychainScript, operation, `stateplane:${endpoint2}`], stdin);
|
|
523
|
+
}
|
|
524
|
+
function command(program, args, stdin) {
|
|
525
|
+
return new Promise((resolve) => {
|
|
526
|
+
const child = spawn(program, args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
527
|
+
const timer = setTimeout(() => child.kill(), 3e4);
|
|
528
|
+
let output2 = "";
|
|
529
|
+
let diagnostic = false;
|
|
530
|
+
child.stdout.setEncoding("utf8");
|
|
531
|
+
child.stdout.on("data", (chunk) => {
|
|
532
|
+
if (output2.length < 16384) output2 += chunk;
|
|
533
|
+
});
|
|
534
|
+
child.stderr.on("data", () => {
|
|
535
|
+
diagnostic = true;
|
|
536
|
+
});
|
|
537
|
+
child.stdin.on("error", () => {
|
|
538
|
+
});
|
|
539
|
+
child.on("error", () => {
|
|
540
|
+
clearTimeout(timer);
|
|
541
|
+
resolve({ ok: false, output: "" });
|
|
542
|
+
});
|
|
543
|
+
child.on("close", (code) => {
|
|
544
|
+
clearTimeout(timer);
|
|
545
|
+
resolve({
|
|
546
|
+
ok: code === 0,
|
|
547
|
+
output: output2,
|
|
548
|
+
missing: program === "/usr/bin/xcrun" ? code === 2 : program === "secret-tool" && code === 1 && !diagnostic
|
|
549
|
+
});
|
|
550
|
+
});
|
|
551
|
+
child.stdin.end(stdin);
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
async function loadSecretServiceToken(endpoint2, run = command) {
|
|
555
|
+
const result = await run("secret-tool", ["lookup", ...keyArgs(endpoint2)]);
|
|
556
|
+
if (!result.ok) throw new StateplaneCliError(result.missing ? "UNAUTHENTICATED" : "KEYCHAIN_UNAVAILABLE");
|
|
557
|
+
const token = result.output.replace(/\n$/, "");
|
|
558
|
+
if (!token) throw new StateplaneCliError("UNAUTHENTICATED");
|
|
559
|
+
return token;
|
|
560
|
+
}
|
|
561
|
+
async function loadOsSecretToken(endpoint2, os = platform(), run = command) {
|
|
562
|
+
if (os === "linux") return loadSecretServiceToken(endpoint2, run);
|
|
563
|
+
throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
564
|
+
}
|
|
565
|
+
async function storeSecretServiceToken(endpoint2, token, run = command) {
|
|
566
|
+
const args = keyArgs(endpoint2);
|
|
567
|
+
const stored = await run("secret-tool", ["store", "--label=Stateplane API key", ...args], token);
|
|
568
|
+
if (!stored.ok) throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
569
|
+
const checked = await run("secret-tool", ["lookup", ...args]);
|
|
570
|
+
if (!checked.ok || checked.output.replace(/\n$/, "") !== token) {
|
|
571
|
+
await run("secret-tool", ["clear", ...args]);
|
|
572
|
+
throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
async function removeSecretServiceToken(endpoint2, run = command) {
|
|
576
|
+
const args = keyArgs(endpoint2);
|
|
577
|
+
const cleared = await run("secret-tool", ["clear", ...args]);
|
|
578
|
+
if (cleared.ok) return;
|
|
579
|
+
if (!cleared.missing) throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
580
|
+
const remaining = await run("secret-tool", ["lookup", ...args]);
|
|
581
|
+
if (!remaining.missing) throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
582
|
+
}
|
|
583
|
+
async function saveToken(endpoint2, token, store) {
|
|
584
|
+
if (!token || /[\r\n\0]/.test(token)) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
585
|
+
if (store === "file") {
|
|
586
|
+
await secureDirectory();
|
|
587
|
+
const temp = join(configDir(), `.token-${process.pid}-${crypto.randomUUID()}`);
|
|
588
|
+
try {
|
|
589
|
+
await writeFile(temp, token, { mode: 384, flag: "wx" });
|
|
590
|
+
if (platform() === "win32") await windowsAcl(temp, "harden");
|
|
591
|
+
await rename(temp, tokenPath());
|
|
592
|
+
} finally {
|
|
593
|
+
await rm(temp, { force: true });
|
|
594
|
+
}
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
if (platform() === "linux") return storeSecretServiceToken(endpoint2, token);
|
|
598
|
+
throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
599
|
+
}
|
|
600
|
+
async function loadToken(config) {
|
|
601
|
+
if (process.env.STATEPLANE_TOKEN) return process.env.STATEPLANE_TOKEN;
|
|
602
|
+
if (!config.endpoint) throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
603
|
+
if (config.tokenStore === "file") {
|
|
604
|
+
if (!await privateFile(tokenPath())) throw new StateplaneCliError("UNAUTHENTICATED");
|
|
605
|
+
const token = await readFile(tokenPath(), "utf8");
|
|
606
|
+
if (!token || /[\r\n\0]/.test(token)) throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
607
|
+
return token;
|
|
608
|
+
}
|
|
609
|
+
if (config.tokenStore === "keychain") {
|
|
610
|
+
return loadOsSecretToken(config.endpoint);
|
|
611
|
+
}
|
|
612
|
+
throw new StateplaneCliError("UNAUTHENTICATED");
|
|
613
|
+
}
|
|
614
|
+
async function removeToken(config) {
|
|
615
|
+
if (config.tokenStore === "file") await rm(tokenPath(), { force: true });
|
|
616
|
+
else if (config.tokenStore === "keychain" && config.endpoint) {
|
|
617
|
+
let result;
|
|
618
|
+
if (platform() === "darwin") result = await macKeychain("remove", config.endpoint);
|
|
619
|
+
else if (platform() === "linux") return removeSecretServiceToken(config.endpoint);
|
|
620
|
+
else result = { ok: false, output: "" };
|
|
621
|
+
if (!result.ok) throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
var persistence = { saveConfig, saveToken, removeToken };
|
|
625
|
+
async function configureToken(config, token, store, io = persistence) {
|
|
626
|
+
if (!config.endpoint) throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
627
|
+
if (store === "keychain" && platform() !== "linux") throw new StateplaneCliError("KEYCHAIN_UNAVAILABLE");
|
|
628
|
+
const locations = [.../* @__PURE__ */ new Set([...config.tokenLocations ?? [], ...config.tokenStore ? [config.tokenStore] : [], store])];
|
|
629
|
+
await io.saveConfig({ ...config, tokenLocations: locations });
|
|
630
|
+
await io.saveToken(config.endpoint, token, store);
|
|
631
|
+
await io.saveConfig({ ...config, tokenStore: store, tokenLocations: locations });
|
|
632
|
+
for (const previous of locations) if (previous !== store)
|
|
633
|
+
await io.removeToken({ ...config, tokenStore: previous });
|
|
634
|
+
await io.saveConfig({ ...config, tokenStore: store, tokenLocations: void 0 });
|
|
635
|
+
}
|
|
636
|
+
async function removeTrackedTokens(config, io = persistence) {
|
|
637
|
+
const locations = /* @__PURE__ */ new Set([...config.tokenLocations ?? [], ...config.tokenStore ? [config.tokenStore] : []]);
|
|
638
|
+
let failure;
|
|
639
|
+
for (const store of locations) {
|
|
640
|
+
try {
|
|
641
|
+
await io.removeToken({ ...config, tokenStore: store });
|
|
642
|
+
} catch (error) {
|
|
643
|
+
failure ??= error;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
if (failure) throw failure;
|
|
647
|
+
}
|
|
648
|
+
var logoutPersistence = { removeTrackedTokens, saveConfig };
|
|
649
|
+
async function logoutConfig(config, io = logoutPersistence) {
|
|
650
|
+
await io.removeTrackedTokens(config);
|
|
651
|
+
await io.saveConfig({ ...config, tokenStore: void 0, tokenLocations: void 0 });
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// src/run.ts
|
|
655
|
+
var encoded = (value) => value === "." || value === ".." ? `;${value}` : encodeURIComponent(value);
|
|
656
|
+
var switches = /* @__PURE__ */ new Set(["retry-failed", "json", "token-stdin", "help"]);
|
|
657
|
+
function parseOption(argv, index, flags) {
|
|
658
|
+
const item = argv[index];
|
|
659
|
+
const equals = item.indexOf("=");
|
|
660
|
+
const key = item.slice(2, equals < 0 ? void 0 : equals);
|
|
661
|
+
if (!/^[a-z][a-z0-9-]*$/.test(key) || Object.hasOwn(flags, key)) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
662
|
+
if (switches.has(key)) {
|
|
663
|
+
if (equals >= 0) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
664
|
+
flags[key] = true;
|
|
665
|
+
return index;
|
|
666
|
+
}
|
|
667
|
+
const value = equals >= 0 ? item.slice(equals + 1) : argv[++index];
|
|
668
|
+
if (value === void 0 || equals < 0 && value.startsWith("--")) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
669
|
+
flags[key] = value;
|
|
670
|
+
return index;
|
|
671
|
+
}
|
|
672
|
+
function parse(argv) {
|
|
673
|
+
const words = [];
|
|
674
|
+
const flags = {};
|
|
675
|
+
let i = 0;
|
|
676
|
+
while (i < argv.length) {
|
|
677
|
+
const item = argv[i];
|
|
678
|
+
if (!item.startsWith("--")) {
|
|
679
|
+
words.push(item);
|
|
680
|
+
i++;
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
i = parseOption(argv, i, flags) + 1;
|
|
684
|
+
}
|
|
685
|
+
return { words, flags };
|
|
686
|
+
}
|
|
687
|
+
var largeBody = 3145728;
|
|
688
|
+
var smallBody = 32768;
|
|
689
|
+
var retrievalBody = 131072;
|
|
690
|
+
var uploadBytes = 26214400;
|
|
691
|
+
var textBytes = 1048576;
|
|
692
|
+
var evidenceCommands = {
|
|
693
|
+
"sources get": ["space", "collection", "id"],
|
|
694
|
+
"sources content": ["space", "collection", "id", "output"],
|
|
695
|
+
"sources ingest-text": ["space", "collection", "idempotency-key", "text", "file", "mime-type", "locator", "captured-at"],
|
|
696
|
+
"sources ingest-reference": ["space", "collection", "idempotency-key", "locator", "mime-type", "captured-at"],
|
|
697
|
+
"sources delete": ["space", "collection", "id"],
|
|
698
|
+
"sources extract": ["space", "collection", "id"],
|
|
699
|
+
"sources extraction": ["space", "collection", "id", "version"],
|
|
700
|
+
"sources correct": ["space", "collection", "id", "base-version", "data", "file"],
|
|
701
|
+
"uploads create": ["space", "collection", "mime-type", "max-bytes", "sha256", "expires-in"],
|
|
702
|
+
"uploads send": ["space", "collection", "grant", "file", "mime-type", "sha256"],
|
|
703
|
+
"uploads finalize": ["space", "collection", "grant", "attempt", "locator", "captured-at"],
|
|
704
|
+
"uploads revoke": ["space", "collection", "grant"],
|
|
705
|
+
"claims create": ["space", "collection", "idempotency-key", "data", "file"],
|
|
706
|
+
"claims revise": ["space", "collection", "id", "base-revision", "data", "file"],
|
|
707
|
+
"claims review": ["space", "collection", "id", "base-revision", "status"],
|
|
708
|
+
"claims delete": ["space", "collection", "id", "base-revision"],
|
|
709
|
+
"claims get": ["space", "collection", "id", "revision"],
|
|
710
|
+
"claims list": ["space", "collection", "status", "citing-collection", "citing-source", "after", "limit"],
|
|
711
|
+
"links create": ["space", "collection", "idempotency-key", "data", "file"],
|
|
712
|
+
"links get": ["space", "collection", "id"],
|
|
713
|
+
"links delete": ["space", "collection", "id"],
|
|
714
|
+
"links list": ["space", "collection", "endpoint-kind", "endpoint-id", "after", "limit"]
|
|
715
|
+
};
|
|
716
|
+
var common = ["json"];
|
|
717
|
+
var allowed = {
|
|
718
|
+
"config endpoint": ["url"],
|
|
719
|
+
"config show": [],
|
|
720
|
+
"auth login": ["token-stdin", "store", "timeout"],
|
|
721
|
+
"auth import": ["token-stdin", "store"],
|
|
722
|
+
"auth logout": [],
|
|
723
|
+
"spaces select": ["space"],
|
|
724
|
+
"spaces list": ["cursor"],
|
|
725
|
+
"spaces create": ["cell", "space"],
|
|
726
|
+
"spaces get": ["space"],
|
|
727
|
+
"spaces update": ["space", "lifecycle"],
|
|
728
|
+
"spaces delete": ["space"],
|
|
729
|
+
"spaces erasure": ["space"],
|
|
730
|
+
"collections list": ["space", "cursor"],
|
|
731
|
+
"collections get": ["space", "collection"],
|
|
732
|
+
"collections define": ["space", "collection", "data", "file"],
|
|
733
|
+
"collections revise": ["space", "collection", "data", "file", "version"],
|
|
734
|
+
"records get": ["space", "collection", "id"],
|
|
735
|
+
"records key": ["space", "collection", "key", "mode"],
|
|
736
|
+
"records projection": ["space", "collection", "id"],
|
|
737
|
+
"records query": ["space", "collection", "predicates", "limit", "sort", "cursor"],
|
|
738
|
+
"records count": ["space", "collection", "predicates"],
|
|
739
|
+
"records create": ["space", "collection", "idempotency-key", "expected-schema-version", "data", "file", "key"],
|
|
740
|
+
"records replace": ["space", "collection", "idempotency-key", "id", "expected-revision", "expected-schema-version", "data", "file"],
|
|
741
|
+
"records patch": ["space", "collection", "idempotency-key", "id", "expected-revision", "expected-schema-version", "data", "file"],
|
|
742
|
+
"records delete": ["space", "collection", "idempotency-key", "id", "expected-revision", "expected-schema-version"],
|
|
743
|
+
"batches ingest": ["space", "collection", "operation-key", "file", "retry-failed"],
|
|
744
|
+
"batches status": ["space", "collection", "operation-key"],
|
|
745
|
+
"batches cancel": ["space", "collection", "operation-key"],
|
|
746
|
+
"events list": ["space", "collection", "cursor"],
|
|
747
|
+
"retrieval search": ["space", "data", "file"],
|
|
748
|
+
"retrieval bundle": ["space", "data", "file"],
|
|
749
|
+
"retrieval status": ["space", "collection"],
|
|
750
|
+
"analysis aggregate": ["space", "collection", "data", "file"],
|
|
751
|
+
"analysis submit": ["space", "collection", "kind", "data", "file"],
|
|
752
|
+
"analysis status": ["space", "collection", "job"],
|
|
753
|
+
"analysis cancel": ["space", "collection", "job"],
|
|
754
|
+
"analysis page": ["space", "collection", "job", "page"],
|
|
755
|
+
...evidenceCommands
|
|
756
|
+
};
|
|
757
|
+
function validateFlags(resource, action, flags) {
|
|
758
|
+
const command2 = allowed[`${resource} ${action ?? ""}`];
|
|
759
|
+
if (!command2) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
760
|
+
const usesHttp = resource !== "config" && resource !== "auth" && !(resource === "spaces" && action === "select");
|
|
761
|
+
const accepted = /* @__PURE__ */ new Set([...command2, ...common, ...usesHttp ? ["timeout"] : []]);
|
|
762
|
+
if (Object.keys(flags).some((key) => !accepted.has(key))) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
763
|
+
if (flags.space === "" || flags.cell === "" || flags.sort === "" || flags.key === "")
|
|
764
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
765
|
+
if (flags.timeout !== void 0) integer(required(flags, "timeout"));
|
|
766
|
+
}
|
|
767
|
+
function required(flags, key) {
|
|
768
|
+
const value = flags[key];
|
|
769
|
+
if (typeof value !== "string" || !value) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
770
|
+
return value;
|
|
771
|
+
}
|
|
772
|
+
function cursor(flags) {
|
|
773
|
+
const value = flags.cursor;
|
|
774
|
+
if (typeof value !== "string" || !value) throw new StateplaneCliError("CURSOR_INVALID");
|
|
775
|
+
return value;
|
|
776
|
+
}
|
|
777
|
+
function integer(value) {
|
|
778
|
+
if (!/^[1-9]\d*$/.test(value)) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
779
|
+
const number = Number(value);
|
|
780
|
+
if (!Number.isSafeInteger(number) || number < 1) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
781
|
+
return number;
|
|
782
|
+
}
|
|
783
|
+
function parsed(value) {
|
|
784
|
+
try {
|
|
785
|
+
return JSON.parse(value, (_key, item) => {
|
|
786
|
+
if (typeof item === "number" && !Number.isFinite(item)) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
787
|
+
return item;
|
|
788
|
+
});
|
|
789
|
+
} catch {
|
|
790
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
async function input(path, maxBytes, keepBom = false) {
|
|
794
|
+
const source = path === "-" ? process.stdin : createReadStream(path);
|
|
795
|
+
const chunks = [];
|
|
796
|
+
let size = 0;
|
|
797
|
+
try {
|
|
798
|
+
for await (const chunk of source) {
|
|
799
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
800
|
+
size += bytes.length;
|
|
801
|
+
if (size > maxBytes) throw new StateplaneCliError("RATE_LIMITED", void 0, void 0, false);
|
|
802
|
+
chunks.push(bytes);
|
|
803
|
+
}
|
|
804
|
+
} catch (error) {
|
|
805
|
+
if (error instanceof StateplaneCliError) throw error;
|
|
806
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
807
|
+
}
|
|
808
|
+
try {
|
|
809
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: keepBom }).decode(Buffer.concat(chunks));
|
|
810
|
+
} catch {
|
|
811
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
async function payload(flags, maxBytes = 1048576) {
|
|
815
|
+
return parsed(await payloadText(flags, maxBytes));
|
|
816
|
+
}
|
|
817
|
+
async function payloadText(flags, maxBytes) {
|
|
818
|
+
if (flags.data !== void 0 && flags.file !== void 0) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
819
|
+
const text = flags.file !== void 0 ? await input(required(flags, "file"), maxBytes) : required(flags, "data");
|
|
820
|
+
if (Buffer.byteLength(text) > maxBytes) throw new StateplaneCliError("RATE_LIMITED", void 0, void 0, false);
|
|
821
|
+
return text;
|
|
822
|
+
}
|
|
823
|
+
function withinWireBudget(value, maxBytes) {
|
|
824
|
+
let serialized;
|
|
825
|
+
try {
|
|
826
|
+
serialized = JSON.stringify(value);
|
|
827
|
+
} catch {
|
|
828
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
829
|
+
}
|
|
830
|
+
if (serialized === void 0) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
831
|
+
if (Buffer.byteLength(serialized) > maxBytes)
|
|
832
|
+
throw new StateplaneCliError("RATE_LIMITED", void 0, void 0, false);
|
|
833
|
+
return value;
|
|
834
|
+
}
|
|
835
|
+
function endpoint(value) {
|
|
836
|
+
let url;
|
|
837
|
+
try {
|
|
838
|
+
url = new URL(value);
|
|
839
|
+
} catch {
|
|
840
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
841
|
+
}
|
|
842
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))
|
|
843
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
844
|
+
return url.origin + "/";
|
|
845
|
+
}
|
|
846
|
+
function output(value) {
|
|
847
|
+
process.stdout.write(JSON.stringify(value) + "\n");
|
|
848
|
+
}
|
|
849
|
+
function help() {
|
|
850
|
+
output({
|
|
851
|
+
usage: "stateplane <config|auth|spaces|collections|records|batches|events|sources|uploads|claims|links|retrieval|analysis> <command> [--space ID] [--collection ID] [options]",
|
|
852
|
+
docs: "See docs/http-cli.md for examples and recovery rules."
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
async function runConfig(action, flags, config) {
|
|
856
|
+
if (action === "show") return { endpoint: config.endpoint ?? null, space: config.space ?? null, tokenStore: config.tokenStore ?? null };
|
|
857
|
+
if (action !== "endpoint") throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
858
|
+
const value = endpoint(required(flags, "url"));
|
|
859
|
+
return withConfigMutation(async (current) => {
|
|
860
|
+
const changed = current.endpoint !== value;
|
|
861
|
+
if (current.endpoint && changed) await removeTrackedTokens(current);
|
|
862
|
+
await saveConfig({
|
|
863
|
+
...current,
|
|
864
|
+
endpoint: value,
|
|
865
|
+
space: changed ? void 0 : current.space,
|
|
866
|
+
tokenStore: changed ? void 0 : current.tokenStore,
|
|
867
|
+
tokenLocations: changed ? void 0 : current.tokenLocations
|
|
868
|
+
});
|
|
869
|
+
return { endpoint: value, space: changed ? null : current.space ?? null };
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
async function runAuth(action, flags, config) {
|
|
873
|
+
if (action === "logout") {
|
|
874
|
+
await withConfigMutation((current) => logoutConfig(current));
|
|
875
|
+
return { configured: false };
|
|
876
|
+
}
|
|
877
|
+
if (action !== "login" && action !== "import") throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
878
|
+
if (!config.endpoint || flags["token-stdin"] !== true) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
879
|
+
const store = flags.store ?? (process.platform === "linux" ? "keychain" : "file");
|
|
880
|
+
if (store !== "file" && store !== "keychain") throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
881
|
+
const token = (await input("-", 4096)).replace(/\r?\n$/, "");
|
|
882
|
+
if (action === "login") await new StateplaneHttpClient({
|
|
883
|
+
endpoint: config.endpoint,
|
|
884
|
+
token,
|
|
885
|
+
timeoutMs: flags.timeout ? integer(required(flags, "timeout")) : void 0
|
|
886
|
+
}).request("GET", "/v1/auth/session");
|
|
887
|
+
await withConfigMutation(async (current) => {
|
|
888
|
+
if (current.endpoint !== config.endpoint) throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
889
|
+
await configureToken(current, token, store);
|
|
890
|
+
});
|
|
891
|
+
return { configured: true, store };
|
|
892
|
+
}
|
|
893
|
+
async function runSpaces(client, action, flags, spacePath) {
|
|
894
|
+
if (action === "list") {
|
|
895
|
+
const suffix = flags.cursor === void 0 ? "" : `?cursor=${encoded(cursor(flags))}`;
|
|
896
|
+
return client.request("GET", `/v1/spaces${suffix}`);
|
|
897
|
+
}
|
|
898
|
+
if (action === "create") return client.request(
|
|
899
|
+
"POST",
|
|
900
|
+
"/v1/spaces",
|
|
901
|
+
withinWireBudget({ spaceId: required(flags, "space"), ...flags.cell ? { cellId: flags.cell } : {} }, 4096)
|
|
902
|
+
);
|
|
903
|
+
if (action === "get" && spacePath) return client.request("GET", spacePath);
|
|
904
|
+
if (action === "update" && spacePath) return client.request(
|
|
905
|
+
"PATCH",
|
|
906
|
+
spacePath,
|
|
907
|
+
withinWireBudget({ lifecycle: required(flags, "lifecycle") }, 4096)
|
|
908
|
+
);
|
|
909
|
+
if (action === "delete" && spacePath) return client.request("DELETE", spacePath);
|
|
910
|
+
if (action === "erasure" && spacePath) return client.request("GET", `${spacePath}/erasure`);
|
|
911
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
912
|
+
}
|
|
913
|
+
async function runCollections(client, action, flags, spacePath, collectionPath) {
|
|
914
|
+
if (action === "list") {
|
|
915
|
+
const suffix = flags.cursor !== void 0 ? `?cursor=${encoded(cursor(flags))}` : "";
|
|
916
|
+
return client.request("GET", `${spacePath}/collections${suffix}`);
|
|
917
|
+
}
|
|
918
|
+
if (action === "get" && collectionPath) return client.request("GET", collectionPath);
|
|
919
|
+
if (action === "define" && collectionPath) return client.request(
|
|
920
|
+
"PUT",
|
|
921
|
+
collectionPath,
|
|
922
|
+
withinWireBudget(await payload(flags), 1048576)
|
|
923
|
+
);
|
|
924
|
+
if (action === "revise" && collectionPath) return client.request(
|
|
925
|
+
"PATCH",
|
|
926
|
+
collectionPath,
|
|
927
|
+
withinWireBudget(await payload(flags), 1048576),
|
|
928
|
+
{ "If-Match": String(integer(required(flags, "version"))) }
|
|
929
|
+
);
|
|
930
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
931
|
+
}
|
|
932
|
+
async function mutationRequest(action, flags) {
|
|
933
|
+
const request = { operation: action, idempotencyKey: required(flags, "idempotency-key") };
|
|
934
|
+
if (flags["expected-schema-version"] !== void 0)
|
|
935
|
+
request.expectedSchemaVersion = integer(required(flags, "expected-schema-version"));
|
|
936
|
+
if (action === "create") {
|
|
937
|
+
request.data = await payload(flags);
|
|
938
|
+
if (flags.key !== void 0) request.externalKey = required(flags, "key");
|
|
939
|
+
return request;
|
|
940
|
+
}
|
|
941
|
+
request.id = required(flags, "id");
|
|
942
|
+
request.expectedRevision = integer(required(flags, "expected-revision"));
|
|
943
|
+
if (action === "replace") request.data = await payload(flags);
|
|
944
|
+
if (action === "patch") {
|
|
945
|
+
const patch = await payload(flags);
|
|
946
|
+
if (!patch || typeof patch !== "object" || Array.isArray(patch) || !patch.set || typeof patch.set !== "object" || Array.isArray(patch.set) || !Array.isArray(patch.unset) || patch.unset.some((value) => typeof value !== "string"))
|
|
947
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
948
|
+
request.set = patch.set;
|
|
949
|
+
request.unset = patch.unset;
|
|
950
|
+
}
|
|
951
|
+
return request;
|
|
952
|
+
}
|
|
953
|
+
async function runRecords(client, action, flags, recordPath) {
|
|
954
|
+
if (action === "get") return client.request("GET", `${recordPath}/${encoded(required(flags, "id"))}`);
|
|
955
|
+
if (action === "key") return client.request("GET", `${recordPath}/by-key/${encoded(required(flags, "key"))}?mode=${encoded(required(flags, "mode"))}`);
|
|
956
|
+
if (action === "projection") return client.request("GET", `${recordPath}/${encoded(required(flags, "id"))}/projection`);
|
|
957
|
+
if (action === "query") return client.request("POST", `${recordPath}/query`, withinWireBudget({
|
|
958
|
+
predicates: parsed(typeof flags.predicates === "string" ? flags.predicates : "[]"),
|
|
959
|
+
limit: integer(required(flags, "limit")),
|
|
960
|
+
...flags.sort ? { sort: parsed(required(flags, "sort")) } : {},
|
|
961
|
+
...flags.cursor !== void 0 ? { cursor: cursor(flags) } : {}
|
|
962
|
+
}, 32768));
|
|
963
|
+
if (action === "count") return client.request(
|
|
964
|
+
"POST",
|
|
965
|
+
`${recordPath}/count`,
|
|
966
|
+
withinWireBudget(parsed(typeof flags.predicates === "string" ? flags.predicates : "[]"), 32768)
|
|
967
|
+
);
|
|
968
|
+
if (action && ["create", "replace", "patch", "delete"].includes(action))
|
|
969
|
+
return client.request("POST", recordPath, withinWireBudget(await mutationRequest(action, flags), 1048576));
|
|
970
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
971
|
+
}
|
|
972
|
+
async function runBatches(client, action, flags, collectionPath) {
|
|
973
|
+
const operation = required(flags, "operation-key");
|
|
974
|
+
const url = `${collectionPath}/batches/${encoded(operation)}`;
|
|
975
|
+
if (action === "status") return client.request("GET", url);
|
|
976
|
+
if (action === "cancel") return client.request("DELETE", url);
|
|
977
|
+
if (action !== "ingest") throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
978
|
+
const lines = (await input(required(flags, "file"), 3145728)).split(/\r?\n/).filter(Boolean);
|
|
979
|
+
if (!lines.length || lines.length > 20) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
980
|
+
const manifest = lines.map((line) => {
|
|
981
|
+
parsed(line);
|
|
982
|
+
return line;
|
|
983
|
+
});
|
|
984
|
+
const itemBytes = manifest.map((item) => Buffer.byteLength(item));
|
|
985
|
+
if (itemBytes.some((size) => size > 1048576) || itemBytes.reduce((sum, size) => sum + size, 0) > 2097152)
|
|
986
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
987
|
+
return client.request(
|
|
988
|
+
"PUT",
|
|
989
|
+
url + (flags["retry-failed"] ? "?retryFailed=true" : ""),
|
|
990
|
+
withinWireBudget(manifest, 3145728)
|
|
991
|
+
);
|
|
992
|
+
}
|
|
993
|
+
function optional(flags, names) {
|
|
994
|
+
const out = {};
|
|
995
|
+
for (const [flag, field] of Object.entries(names)) if (flags[flag] !== void 0) out[field] = required(flags, flag);
|
|
996
|
+
return out;
|
|
997
|
+
}
|
|
998
|
+
async function objectWith(flags, field, value, maxBytes) {
|
|
999
|
+
const data = await payload(flags, maxBytes);
|
|
1000
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || Object.hasOwn(data, field))
|
|
1001
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1002
|
+
return { [field]: value, ...data };
|
|
1003
|
+
}
|
|
1004
|
+
function search(values) {
|
|
1005
|
+
const params = new URLSearchParams();
|
|
1006
|
+
for (const [key, value] of Object.entries(values)) if (value !== void 0) params.append(key, value);
|
|
1007
|
+
const text = params.toString();
|
|
1008
|
+
return text ? `?${text}` : "";
|
|
1009
|
+
}
|
|
1010
|
+
async function fileBytes(path, maxBytes) {
|
|
1011
|
+
const chunks = [];
|
|
1012
|
+
let size = 0;
|
|
1013
|
+
try {
|
|
1014
|
+
for await (const chunk of createReadStream(path)) {
|
|
1015
|
+
size += chunk.length;
|
|
1016
|
+
if (size > maxBytes) throw new StateplaneCliError("RATE_LIMITED", void 0, void 0, false);
|
|
1017
|
+
chunks.push(chunk);
|
|
1018
|
+
}
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
if (error instanceof StateplaneCliError) throw error;
|
|
1021
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1022
|
+
}
|
|
1023
|
+
return new Uint8Array(Buffer.concat(chunks));
|
|
1024
|
+
}
|
|
1025
|
+
async function writeAll(file, chunk, deadline) {
|
|
1026
|
+
let offset = 0;
|
|
1027
|
+
while (offset < chunk.byteLength) {
|
|
1028
|
+
if (deadline.expired()) throw new Error("deadline passed");
|
|
1029
|
+
const { bytesWritten } = await file.write(chunk, offset, chunk.byteLength - offset);
|
|
1030
|
+
if (!(bytesWritten > 0)) throw new Error("short write");
|
|
1031
|
+
offset += bytesWritten;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
async function saveContent(client, path, output2) {
|
|
1035
|
+
const { response, deadline } = await client.download(path);
|
|
1036
|
+
if (response.status === 204) {
|
|
1037
|
+
await response.body?.cancel().catch(() => {
|
|
1038
|
+
});
|
|
1039
|
+
return { referenceOnly: true, output: null };
|
|
1040
|
+
}
|
|
1041
|
+
const digest = /^sha-256=:([A-Za-z0-9+/]{43}=):$/.exec(response.headers.get("repr-digest") ?? "")?.[1];
|
|
1042
|
+
const declared = response.headers.get("content-length");
|
|
1043
|
+
const encoding = response.headers.get("content-encoding");
|
|
1044
|
+
const encoded2 = encoding !== null && encoding.trim().toLowerCase() !== "identity";
|
|
1045
|
+
let length = null;
|
|
1046
|
+
if (declared !== null && !encoded2) length = /^(?:0|[1-9]\d*)$/.test(declared) ? Number(declared) : Number.NaN;
|
|
1047
|
+
let file;
|
|
1048
|
+
try {
|
|
1049
|
+
file = await open2(output2, "wx", 384);
|
|
1050
|
+
} catch {
|
|
1051
|
+
await response.body?.cancel().catch(() => {
|
|
1052
|
+
});
|
|
1053
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1054
|
+
}
|
|
1055
|
+
const hash = createHash("sha256");
|
|
1056
|
+
let bytes = 0;
|
|
1057
|
+
let complete = true;
|
|
1058
|
+
let interrupted = false;
|
|
1059
|
+
const reader = response.body?.getReader();
|
|
1060
|
+
while (reader && complete) {
|
|
1061
|
+
let next;
|
|
1062
|
+
try {
|
|
1063
|
+
next = await reader.read();
|
|
1064
|
+
} catch {
|
|
1065
|
+
interrupted = true;
|
|
1066
|
+
complete = false;
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
if (next.done) break;
|
|
1070
|
+
try {
|
|
1071
|
+
await writeAll(file, next.value, deadline);
|
|
1072
|
+
} catch {
|
|
1073
|
+
complete = false;
|
|
1074
|
+
await reader.cancel().catch(() => {
|
|
1075
|
+
});
|
|
1076
|
+
break;
|
|
1077
|
+
}
|
|
1078
|
+
hash.update(next.value);
|
|
1079
|
+
bytes += next.value.byteLength;
|
|
1080
|
+
}
|
|
1081
|
+
complete &&= digest !== void 0 && hash.digest("base64") === digest && (length === null || bytes === length);
|
|
1082
|
+
try {
|
|
1083
|
+
await file.close();
|
|
1084
|
+
} catch {
|
|
1085
|
+
complete = false;
|
|
1086
|
+
}
|
|
1087
|
+
const late = deadline.expired();
|
|
1088
|
+
if (!complete || late) {
|
|
1089
|
+
await unlink(output2).catch(() => {
|
|
1090
|
+
});
|
|
1091
|
+
throw new StateplaneCliError("PROVIDER_UNAVAILABLE", void 0, void 0, interrupted || late);
|
|
1092
|
+
}
|
|
1093
|
+
return {
|
|
1094
|
+
referenceOnly: false,
|
|
1095
|
+
output: output2,
|
|
1096
|
+
bytes,
|
|
1097
|
+
sha256: Buffer.from(digest, "base64").toString("hex"),
|
|
1098
|
+
mimeType: response.headers.get("content-type")
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
async function runSources(client, action, flags, base) {
|
|
1102
|
+
const sources = `${base}/sources`;
|
|
1103
|
+
if (action === "ingest-text") {
|
|
1104
|
+
if (flags.text === void 0 === (flags.file === void 0)) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1105
|
+
const text = flags.file !== void 0 ? await input(required(flags, "file"), textBytes, true) : required(flags, "text");
|
|
1106
|
+
return client.request("POST", `${sources}/text`, withinWireBudget({
|
|
1107
|
+
idempotencyKey: required(flags, "idempotency-key"),
|
|
1108
|
+
text,
|
|
1109
|
+
...optional(flags, { "mime-type": "mimeType", locator: "locator", "captured-at": "capturedAt" })
|
|
1110
|
+
}, largeBody));
|
|
1111
|
+
}
|
|
1112
|
+
if (action === "ingest-reference")
|
|
1113
|
+
return client.request("POST", `${sources}/reference`, withinWireBudget({
|
|
1114
|
+
idempotencyKey: required(flags, "idempotency-key"),
|
|
1115
|
+
locator: required(flags, "locator"),
|
|
1116
|
+
...optional(flags, { "mime-type": "mimeType", "captured-at": "capturedAt" })
|
|
1117
|
+
}, smallBody));
|
|
1118
|
+
const source = `${sources}/${encoded(required(flags, "id"))}`;
|
|
1119
|
+
if (action === "get") return client.request("GET", source);
|
|
1120
|
+
if (action === "delete") return client.request("DELETE", source);
|
|
1121
|
+
if (action === "content") return saveContent(client, `${source}/content`, required(flags, "output"));
|
|
1122
|
+
if (action === "extract") return client.request("POST", `${source}/extraction`);
|
|
1123
|
+
if (action === "extraction") return client.request("GET", `${source}/extraction${search({
|
|
1124
|
+
version: flags.version === void 0 ? void 0 : String(integer(required(flags, "version")))
|
|
1125
|
+
})}`);
|
|
1126
|
+
if (action === "correct")
|
|
1127
|
+
return client.request("POST", `${source}/extraction/corrections`, withinWireBudget(await objectWith(
|
|
1128
|
+
flags,
|
|
1129
|
+
"baseVersion",
|
|
1130
|
+
integer(required(flags, "base-version")),
|
|
1131
|
+
largeBody
|
|
1132
|
+
), largeBody));
|
|
1133
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1134
|
+
}
|
|
1135
|
+
async function runUploads(client, action, flags, base) {
|
|
1136
|
+
const uploads = `${base}/uploads`;
|
|
1137
|
+
if (action === "create")
|
|
1138
|
+
return client.request("POST", uploads, withinWireBudget({
|
|
1139
|
+
mimeType: required(flags, "mime-type"),
|
|
1140
|
+
maxBytes: integer(required(flags, "max-bytes")),
|
|
1141
|
+
...optional(flags, { sha256: "sha256" }),
|
|
1142
|
+
...flags["expires-in"] === void 0 ? {} : { expiresInSeconds: integer(required(flags, "expires-in")) }
|
|
1143
|
+
}, smallBody));
|
|
1144
|
+
const grant = `${uploads}/${encoded(required(flags, "grant"))}`;
|
|
1145
|
+
if (action === "revoke") return client.request("DELETE", grant);
|
|
1146
|
+
if (action === "finalize")
|
|
1147
|
+
return client.request("POST", `${grant}/finalize`, withinWireBudget({
|
|
1148
|
+
attemptId: required(flags, "attempt"),
|
|
1149
|
+
...optional(flags, { locator: "locator", "captured-at": "capturedAt" })
|
|
1150
|
+
}, smallBody));
|
|
1151
|
+
if (action === "send") {
|
|
1152
|
+
const mimeType = required(flags, "mime-type");
|
|
1153
|
+
const bytes = await fileBytes(required(flags, "file"), uploadBytes);
|
|
1154
|
+
return client.upload(
|
|
1155
|
+
`${grant}/attempts${search({ sha256: flags.sha256 === void 0 ? void 0 : required(flags, "sha256") })}`,
|
|
1156
|
+
bytes,
|
|
1157
|
+
mimeType
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1161
|
+
}
|
|
1162
|
+
async function runClaims(client, action, flags, base) {
|
|
1163
|
+
const claims = `${base}/claims`;
|
|
1164
|
+
if (action === "create")
|
|
1165
|
+
return client.request("POST", claims, withinWireBudget(await objectWith(
|
|
1166
|
+
flags,
|
|
1167
|
+
"idempotencyKey",
|
|
1168
|
+
required(flags, "idempotency-key"),
|
|
1169
|
+
largeBody
|
|
1170
|
+
), largeBody));
|
|
1171
|
+
if (action === "list")
|
|
1172
|
+
return client.request("GET", `${claims}${search({
|
|
1173
|
+
status: flags.status === void 0 ? void 0 : required(flags, "status"),
|
|
1174
|
+
citingCollection: flags["citing-collection"] === void 0 ? void 0 : required(flags, "citing-collection"),
|
|
1175
|
+
citingSource: flags["citing-source"] === void 0 ? void 0 : required(flags, "citing-source"),
|
|
1176
|
+
after: flags.after === void 0 ? void 0 : required(flags, "after"),
|
|
1177
|
+
limit: flags.limit === void 0 ? void 0 : String(integer(required(flags, "limit")))
|
|
1178
|
+
})}`);
|
|
1179
|
+
const claim = `${claims}/${encoded(required(flags, "id"))}`;
|
|
1180
|
+
if (action === "get") return client.request("GET", `${claim}${search({
|
|
1181
|
+
revision: flags.revision === void 0 ? void 0 : String(integer(required(flags, "revision")))
|
|
1182
|
+
})}`);
|
|
1183
|
+
const baseRevision = integer(required(flags, "base-revision"));
|
|
1184
|
+
if (action === "revise")
|
|
1185
|
+
return client.request("POST", `${claim}/revisions`, withinWireBudget(await objectWith(flags, "baseRevision", baseRevision, largeBody), largeBody));
|
|
1186
|
+
if (action === "review")
|
|
1187
|
+
return client.request("POST", `${claim}/reviews`, withinWireBudget({ baseRevision, status: required(flags, "status") }, smallBody));
|
|
1188
|
+
if (action === "delete") return client.request("DELETE", `${claim}${search({ baseRevision: String(baseRevision) })}`);
|
|
1189
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1190
|
+
}
|
|
1191
|
+
async function runLinks(client, action, flags, base) {
|
|
1192
|
+
const links = `${base}/links`;
|
|
1193
|
+
if (action === "create")
|
|
1194
|
+
return client.request("POST", links, withinWireBudget(await objectWith(
|
|
1195
|
+
flags,
|
|
1196
|
+
"idempotencyKey",
|
|
1197
|
+
required(flags, "idempotency-key"),
|
|
1198
|
+
smallBody
|
|
1199
|
+
), smallBody));
|
|
1200
|
+
if (action === "list")
|
|
1201
|
+
return client.request("GET", `${links}${search({
|
|
1202
|
+
endpointKind: required(flags, "endpoint-kind"),
|
|
1203
|
+
endpointId: required(flags, "endpoint-id"),
|
|
1204
|
+
after: flags.after === void 0 ? void 0 : required(flags, "after"),
|
|
1205
|
+
limit: flags.limit === void 0 ? void 0 : String(integer(required(flags, "limit")))
|
|
1206
|
+
})}`);
|
|
1207
|
+
const link = `${links}/${encoded(required(flags, "id"))}`;
|
|
1208
|
+
if (action === "get") return client.request("GET", link);
|
|
1209
|
+
if (action === "delete") return client.request("DELETE", link);
|
|
1210
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1211
|
+
}
|
|
1212
|
+
async function runEvidence(client, resource, action, flags, collectionPath) {
|
|
1213
|
+
if (!action) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1214
|
+
if (resource === "sources") return runSources(client, action, flags, collectionPath);
|
|
1215
|
+
if (resource === "uploads") return runUploads(client, action, flags, collectionPath);
|
|
1216
|
+
if (resource === "claims") return runClaims(client, action, flags, collectionPath);
|
|
1217
|
+
if (resource === "links") return runLinks(client, action, flags, collectionPath);
|
|
1218
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1219
|
+
}
|
|
1220
|
+
async function runCollectionResource(client, resource, action, flags, spacePath) {
|
|
1221
|
+
const collection = typeof flags.collection === "string" ? flags.collection : void 0;
|
|
1222
|
+
const collectionPath = collection ? `${spacePath}/collections/${encoded(collection)}` : "";
|
|
1223
|
+
if (resource === "collections") return runCollections(client, action, flags, spacePath, collectionPath);
|
|
1224
|
+
if (!collectionPath) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1225
|
+
if (resource === "records") return runRecords(client, action, flags, `${collectionPath}/records`);
|
|
1226
|
+
if (resource === "batches") return runBatches(client, action, flags, collectionPath);
|
|
1227
|
+
if (["sources", "uploads", "claims", "links"].includes(resource)) return runEvidence(client, resource, action, flags, collectionPath);
|
|
1228
|
+
if (resource === "analysis") return runAnalysis(client, action, flags, collectionPath);
|
|
1229
|
+
if (resource === "events" && action === "list") {
|
|
1230
|
+
const suffix = flags.cursor !== void 0 ? `?cursor=${encoded(cursor(flags))}` : "";
|
|
1231
|
+
return client.request("GET", `${collectionPath}/events${suffix}`);
|
|
1232
|
+
}
|
|
1233
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1234
|
+
}
|
|
1235
|
+
async function runRetrieval(client, action, flags, spacePath) {
|
|
1236
|
+
if (action === "status") return client.request("GET", `${spacePath}/collections/${encoded(required(flags, "collection"))}/projections`);
|
|
1237
|
+
const data = await payload(flags, retrievalBody);
|
|
1238
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1239
|
+
return client.request("POST", `${spacePath}/${action === "search" ? "search" : "bundles"}`, withinWireBudget(data, retrievalBody));
|
|
1240
|
+
}
|
|
1241
|
+
async function runAnalysis(client, action, flags, collectionPath) {
|
|
1242
|
+
const refuse = (code) => {
|
|
1243
|
+
throw new StateplaneCliError(code, void 0, void 0, false);
|
|
1244
|
+
};
|
|
1245
|
+
const given = async (maxBytes, around = (text) => text) => {
|
|
1246
|
+
const text = await payloadText(flags, maxBytes);
|
|
1247
|
+
if (Buffer.byteLength(around(text)) > maxBytes) refuse("RATE_LIMITED");
|
|
1248
|
+
try {
|
|
1249
|
+
return JSON.parse(text);
|
|
1250
|
+
} catch {
|
|
1251
|
+
return null;
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
if (action === "aggregate") {
|
|
1255
|
+
const spec = await given(analysisBounds.bodyBytes);
|
|
1256
|
+
const admitted = admitAggregation(spec);
|
|
1257
|
+
if ("refused" in admitted) return refuse(admitted.refused);
|
|
1258
|
+
return client.request("POST", `${collectionPath}/aggregate`, spec);
|
|
1259
|
+
}
|
|
1260
|
+
if (action === "submit") {
|
|
1261
|
+
const kind = required(flags, "kind");
|
|
1262
|
+
const request = flags.data === void 0 && flags.file === void 0 ? { kind } : { kind, spec: await given(analysisBounds.bodyBytes, (text) => `{"kind":${JSON.stringify(kind)},"spec":${text}}`) };
|
|
1263
|
+
const admitted = admitAnalysisJob(request);
|
|
1264
|
+
if ("refused" in admitted) return refuse(admitted.refused);
|
|
1265
|
+
return client.request("POST", `${collectionPath}/jobs`, request);
|
|
1266
|
+
}
|
|
1267
|
+
const job = `${collectionPath}/jobs/${encoded(required(flags, "job"))}`;
|
|
1268
|
+
if (action === "status") return client.request("GET", job);
|
|
1269
|
+
if (action === "cancel") return client.request("DELETE", job);
|
|
1270
|
+
if (action === "page") return client.request("GET", `${job}/pages/${encoded(required(flags, "page"))}`);
|
|
1271
|
+
throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1272
|
+
}
|
|
1273
|
+
async function runHttpCommand(resource, action, flags) {
|
|
1274
|
+
const snapshot = await withConfigMutation(async (current) => ({ config: current, token: await loadToken(current) }));
|
|
1275
|
+
if (!snapshot.config.endpoint) throw new StateplaneCliError("INVALID_CONFIGURATION");
|
|
1276
|
+
const client = new StateplaneHttpClient({
|
|
1277
|
+
endpoint: snapshot.config.endpoint,
|
|
1278
|
+
token: snapshot.token,
|
|
1279
|
+
timeoutMs: flags.timeout ? integer(required(flags, "timeout")) : void 0
|
|
1280
|
+
});
|
|
1281
|
+
const space = typeof flags.space === "string" ? flags.space : snapshot.config.space;
|
|
1282
|
+
const spacePath = space ? `/v1/spaces/${encoded(space)}` : "";
|
|
1283
|
+
if (resource === "spaces") return runSpaces(client, action, flags, spacePath);
|
|
1284
|
+
if (!spacePath) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1285
|
+
if (resource === "retrieval") return runRetrieval(client, action, flags, spacePath);
|
|
1286
|
+
return runCollectionResource(client, resource, action, flags, spacePath);
|
|
1287
|
+
}
|
|
1288
|
+
async function runCli(argv) {
|
|
1289
|
+
try {
|
|
1290
|
+
const { words, flags } = parse(argv);
|
|
1291
|
+
const [resource, action, ...rest] = words;
|
|
1292
|
+
if (!resource || resource === "help" || flags.help) {
|
|
1293
|
+
help();
|
|
1294
|
+
return 0;
|
|
1295
|
+
}
|
|
1296
|
+
if (rest.length) throw new StateplaneCliError("INVALID_ARGUMENT");
|
|
1297
|
+
validateFlags(resource, action, flags);
|
|
1298
|
+
const config = await readConfig();
|
|
1299
|
+
if (resource === "config") output(await runConfig(action, flags, config));
|
|
1300
|
+
else if (resource === "auth") output(await runAuth(action, flags, config));
|
|
1301
|
+
else if (resource === "spaces" && action === "select") {
|
|
1302
|
+
const space = required(flags, "space");
|
|
1303
|
+
await withConfigMutation(async (current) => {
|
|
1304
|
+
await saveConfig({ ...current, space });
|
|
1305
|
+
});
|
|
1306
|
+
output({ space });
|
|
1307
|
+
} else output(await runHttpCommand(resource, action, flags));
|
|
1308
|
+
return 0;
|
|
1309
|
+
} catch (error) {
|
|
1310
|
+
const localCode = error?.code;
|
|
1311
|
+
let failure;
|
|
1312
|
+
if (error instanceof StateplaneCliError) failure = error;
|
|
1313
|
+
else if (typeof localCode === "string" && ["EACCES", "EPERM", "ENOENT", "ENOTDIR", "EISDIR", "EROFS", "ENOSPC"].includes(localCode))
|
|
1314
|
+
failure = new StateplaneCliError("INVALID_CONFIGURATION");
|
|
1315
|
+
else failure = new StateplaneCliError("PROVIDER_UNAVAILABLE");
|
|
1316
|
+
process.stderr.write(JSON.stringify({ contractVersion: "1", error: {
|
|
1317
|
+
code: failure.code,
|
|
1318
|
+
message: failure.code,
|
|
1319
|
+
retryable: failure.retryable,
|
|
1320
|
+
requestId: failure.requestId ?? null
|
|
1321
|
+
} }) + "\n");
|
|
1322
|
+
return 1;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
export {
|
|
1326
|
+
StateplaneCliError,
|
|
1327
|
+
StateplaneHttpClient,
|
|
1328
|
+
runCli
|
|
1329
|
+
};
|