@karpoland/sdk 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.ja.md +542 -0
- package/README.md +541 -2
- package/README.zh-CN.md +542 -0
- package/dist/app-B7n0h9Pk.d.cts +450 -0
- package/dist/app-DLU_Aj53.d.ts +450 -0
- package/dist/chunk-EZJ5H5WT.js +87 -0
- package/dist/chunk-EZJ5H5WT.js.map +1 -0
- package/dist/chunk-TRJPD7KM.js +378 -0
- package/dist/chunk-TRJPD7KM.js.map +1 -0
- package/dist/cli.js +875 -0
- package/dist/index.cjs +1448 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +562 -0
- package/dist/index.d.ts +562 -0
- package/dist/index.js +1004 -0
- package/dist/index.js.map +1 -0
- package/dist/page.cjs +311 -0
- package/dist/page.cjs.map +1 -0
- package/dist/page.d.cts +116 -0
- package/dist/page.d.ts +116 -0
- package/dist/page.global.js +1 -0
- package/dist/page.js +135 -0
- package/dist/page.js.map +1 -0
- package/dist/testing.cjs +238 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +123 -0
- package/dist/testing.d.ts +123 -0
- package/dist/testing.js +146 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-VExoR9cc.d.cts +1189 -0
- package/dist/types-VExoR9cc.d.ts +1189 -0
- package/package.json +70 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { createHash } from "crypto";
|
|
5
|
+
import { readFileSync, readdirSync, statSync, writeFileSync } from "fs";
|
|
6
|
+
import { join, relative, resolve } from "path";
|
|
7
|
+
import { deflateRawSync } from "zlib";
|
|
8
|
+
|
|
9
|
+
// src/errors.ts
|
|
10
|
+
var STATUSES = {
|
|
11
|
+
OK: { http: 200, retryable: false, action: "" },
|
|
12
|
+
INVALID_ARGUMENT: { http: 400, retryable: false, action: "fix_request" },
|
|
13
|
+
UNAUTHENTICATED: { http: 401, retryable: false, action: "ask_owner" },
|
|
14
|
+
PERMISSION_DENIED: { http: 403, retryable: false, action: "give_up" },
|
|
15
|
+
NOT_FOUND: { http: 404, retryable: false, action: "give_up" },
|
|
16
|
+
ALREADY_EXISTS: { http: 409, retryable: false, action: "treat_as_done" },
|
|
17
|
+
ABORTED: { http: 409, retryable: true, action: "retry" },
|
|
18
|
+
FAILED_PRECONDITION: { http: 412, retryable: false, action: "give_up" },
|
|
19
|
+
RESOURCE_EXHAUSTED: { http: 429, retryable: false, action: "retry_later" },
|
|
20
|
+
DEADLINE_EXCEEDED: { http: 504, retryable: true, action: "retry_later" },
|
|
21
|
+
UNAVAILABLE: { http: 503, retryable: true, action: "wait" },
|
|
22
|
+
CANCELLED: { http: 499, retryable: false, action: "give_up" },
|
|
23
|
+
UNIMPLEMENTED: { http: 501, retryable: false, action: "give_up" },
|
|
24
|
+
INTERNAL: { http: 500, retryable: true, action: "retry_later" }
|
|
25
|
+
};
|
|
26
|
+
var AppError = class _AppError extends Error {
|
|
27
|
+
name = "AppError";
|
|
28
|
+
status;
|
|
29
|
+
reason;
|
|
30
|
+
constructor(status, reason, message = "") {
|
|
31
|
+
super(message);
|
|
32
|
+
this.status = status;
|
|
33
|
+
this.reason = reason;
|
|
34
|
+
}
|
|
35
|
+
/** The HTTP status the service answers with. */
|
|
36
|
+
get httpStatus() {
|
|
37
|
+
return STATUSES[this.status]?.http ?? 412;
|
|
38
|
+
}
|
|
39
|
+
/** The body the service answers with. */
|
|
40
|
+
toJSON() {
|
|
41
|
+
return { status: this.status, reason: this.reason, message: this.message };
|
|
42
|
+
}
|
|
43
|
+
/** FAILED_PRECONDITION / app.RULE_VIOLATION: the request breaks the app's rules. */
|
|
44
|
+
static ruleViolation(message) {
|
|
45
|
+
return new _AppError("FAILED_PRECONDITION", "app.RULE_VIOLATION", message);
|
|
46
|
+
}
|
|
47
|
+
/** ALREADY_EXISTS / app.ALREADY_DONE: the caller already did this. */
|
|
48
|
+
static alreadyDone(message) {
|
|
49
|
+
return new _AppError("ALREADY_EXISTS", "app.ALREADY_DONE", message);
|
|
50
|
+
}
|
|
51
|
+
/** FAILED_PRECONDITION / app.ITEM_UNAVAILABLE: sold out, gone, not offered. */
|
|
52
|
+
static itemUnavailable(message) {
|
|
53
|
+
return new _AppError("FAILED_PRECONDITION", "app.ITEM_UNAVAILABLE", message);
|
|
54
|
+
}
|
|
55
|
+
/** FAILED_PRECONDITION / app.DEADLINE_PASSED: too late. */
|
|
56
|
+
static deadlinePassed(message) {
|
|
57
|
+
return new _AppError("FAILED_PRECONDITION", "app.DEADLINE_PASSED", message);
|
|
58
|
+
}
|
|
59
|
+
/** INVALID_ARGUMENT with a request.* reason. */
|
|
60
|
+
static invalid(reason, message) {
|
|
61
|
+
return new _AppError("INVALID_ARGUMENT", reason, message);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
var PlatformError = class extends Error {
|
|
65
|
+
name = "PlatformError";
|
|
66
|
+
/** HTTP status of the answer (0 when the request never got one). */
|
|
67
|
+
httpStatus;
|
|
68
|
+
/** gRPC-style status, e.g. "FAILED_PRECONDITION". */
|
|
69
|
+
status;
|
|
70
|
+
/** Registered reason, e.g. "session.LIMIT_REACHED"; may be empty. */
|
|
71
|
+
reason;
|
|
72
|
+
action;
|
|
73
|
+
retryable;
|
|
74
|
+
/** How long to wait before retrying, from retry_after_ms or Retry-After. */
|
|
75
|
+
retryAfterMs;
|
|
76
|
+
detail;
|
|
77
|
+
appMessage;
|
|
78
|
+
/**
|
|
79
|
+
* The developer token's own error code on developer routes (401/403
|
|
80
|
+
* {error, code, hint}, e.g. token_expired); "" otherwise. Such an answer
|
|
81
|
+
* has no status: action is "" and you handle it by code.
|
|
82
|
+
*/
|
|
83
|
+
code;
|
|
84
|
+
/** The hint that comes with code; "" otherwise. */
|
|
85
|
+
hint;
|
|
86
|
+
/** The raw error body. */
|
|
87
|
+
body;
|
|
88
|
+
constructor(httpStatus, body = {}, retryAfterHeader) {
|
|
89
|
+
super(body.message || body.error || "");
|
|
90
|
+
this.httpStatus = httpStatus;
|
|
91
|
+
this.body = body;
|
|
92
|
+
this.status = body.status || statusOfHttp(httpStatus);
|
|
93
|
+
this.reason = body.reason || "";
|
|
94
|
+
this.code = typeof body.code === "string" ? body.code : "";
|
|
95
|
+
this.hint = typeof body.hint === "string" ? body.hint : "";
|
|
96
|
+
const tokenError = !body.status && !!this.code;
|
|
97
|
+
this.action = body.action || (tokenError ? "" : STATUSES[this.status]?.action || "");
|
|
98
|
+
this.retryable = body.retryable ?? STATUSES[this.status]?.retryable ?? false;
|
|
99
|
+
let after = typeof body.retry_after_ms === "number" && body.retry_after_ms > 0 ? body.retry_after_ms : void 0;
|
|
100
|
+
if (after === void 0 && retryAfterHeader) {
|
|
101
|
+
const s = Number(retryAfterHeader);
|
|
102
|
+
if (Number.isFinite(s)) after = s * 1e3;
|
|
103
|
+
else {
|
|
104
|
+
const t = Date.parse(retryAfterHeader);
|
|
105
|
+
if (!Number.isNaN(t)) after = Math.max(0, t - Date.now());
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
this.retryAfterMs = after;
|
|
109
|
+
this.detail = body.detail;
|
|
110
|
+
this.appMessage = body.app_message;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
function isReason(e, reason) {
|
|
114
|
+
return (e instanceof PlatformError || e instanceof AppError) && e.reason === reason;
|
|
115
|
+
}
|
|
116
|
+
function statusOfHttp(http) {
|
|
117
|
+
for (const [k, v] of Object.entries(STATUSES)) if (v.http === http) return k;
|
|
118
|
+
if (http >= 500) return "INTERNAL";
|
|
119
|
+
if (http >= 400) return "FAILED_PRECONDITION";
|
|
120
|
+
return "OK";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/http.ts
|
|
124
|
+
var ALREADY_DONE = /* @__PURE__ */ Symbol.for("karpoland.already_done");
|
|
125
|
+
var RETRY_ACTIONS = /* @__PURE__ */ new Set(["retry", "retry_later"]);
|
|
126
|
+
function shouldRetry(e) {
|
|
127
|
+
if (e.action === "give_up" || e.action === "fix_request") return false;
|
|
128
|
+
return RETRY_ACTIONS.has(e.action) || e.httpStatus === 429 || e.httpStatus === 503;
|
|
129
|
+
}
|
|
130
|
+
var sleep = (ms, signal) => new Promise((resolve2, reject) => {
|
|
131
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
132
|
+
const t = setTimeout(resolve2, ms);
|
|
133
|
+
signal?.addEventListener("abort", () => (clearTimeout(t), reject(signal.reason)), { once: true });
|
|
134
|
+
});
|
|
135
|
+
function buildURL(base, path, query) {
|
|
136
|
+
const url = new URL(base.replace(/\/+$/, "") + path);
|
|
137
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
138
|
+
if (v === void 0 || v === null || v === "") continue;
|
|
139
|
+
url.searchParams.set(k, String(v));
|
|
140
|
+
}
|
|
141
|
+
return url.toString();
|
|
142
|
+
}
|
|
143
|
+
function createTransport(cfg) {
|
|
144
|
+
const doFetch = cfg.fetch ?? ((i, init) => globalThis.fetch(i, init));
|
|
145
|
+
return {
|
|
146
|
+
async request(method, path, opts = {}) {
|
|
147
|
+
const r = opts.retry === false || cfg.retry === false ? { retries: 0 } : { ...cfg.retry || {}, ...opts.retry || {} };
|
|
148
|
+
const retries = r.retries ?? 3;
|
|
149
|
+
const base = r.baseDelayMs ?? 200;
|
|
150
|
+
const maxDelay = r.maxDelayMs ?? 5e3;
|
|
151
|
+
const maxWait = r.maxWaitMs ?? 1e4;
|
|
152
|
+
const url = buildURL(cfg.base, path, opts.query);
|
|
153
|
+
const raw = opts.body instanceof Uint8Array || opts.body instanceof ArrayBuffer || typeof Blob !== "undefined" && opts.body instanceof Blob;
|
|
154
|
+
const idempotentMethod = opts.idempotent || method === "GET" || method === "PUT" || method === "DELETE";
|
|
155
|
+
let reauthed = false;
|
|
156
|
+
for (let attempt = 0; ; attempt++) {
|
|
157
|
+
const headers = { Accept: "application/json", ...cfg.userAgent ? { "User-Agent": cfg.userAgent } : {}, ...cfg.headers(), ...opts.headers };
|
|
158
|
+
if (opts.body !== void 0 && !raw && !headers["Content-Type"]) headers["Content-Type"] = "application/json";
|
|
159
|
+
let res;
|
|
160
|
+
try {
|
|
161
|
+
res = await doFetch(url, {
|
|
162
|
+
method,
|
|
163
|
+
headers,
|
|
164
|
+
body: opts.body === void 0 ? void 0 : raw ? opts.body : JSON.stringify(opts.body),
|
|
165
|
+
signal: opts.signal
|
|
166
|
+
});
|
|
167
|
+
} catch (err2) {
|
|
168
|
+
if (opts.signal?.aborted || !idempotentMethod || attempt >= retries) throw err2;
|
|
169
|
+
await sleep(backoff(attempt, base, maxDelay), opts.signal);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const text = await res.text();
|
|
173
|
+
let data = void 0;
|
|
174
|
+
if (text) {
|
|
175
|
+
try {
|
|
176
|
+
data = JSON.parse(text);
|
|
177
|
+
} catch {
|
|
178
|
+
data = res.ok ? text : { message: text };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (res.ok) return data ?? {};
|
|
182
|
+
const err = new PlatformError(res.status, data ?? {}, res.headers.get("retry-after"));
|
|
183
|
+
if (attempt > 0 && opts.doneOnRetry && err.reason === opts.doneOnRetry) return ALREADY_DONE;
|
|
184
|
+
if (res.status === 401 && cfg.onUnauthorized && !reauthed) {
|
|
185
|
+
reauthed = true;
|
|
186
|
+
if (await cfg.onUnauthorized()) {
|
|
187
|
+
attempt--;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (attempt >= retries || !shouldRetry(err)) throw err;
|
|
192
|
+
const wait = err.retryAfterMs ?? backoff(attempt, base, maxDelay);
|
|
193
|
+
if (wait > maxWait) throw err;
|
|
194
|
+
await sleep(wait, opts.signal);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
function backoff(attempt, base, max) {
|
|
200
|
+
const d = Math.min(max, base * 2 ** attempt);
|
|
201
|
+
return Math.round(d / 2 + Math.random() * (d / 2));
|
|
202
|
+
}
|
|
203
|
+
var enc = (s) => encodeURIComponent(String(s));
|
|
204
|
+
|
|
205
|
+
// src/version.ts
|
|
206
|
+
var SDK_VERSION = "1.0.0";
|
|
207
|
+
var USER_AGENT = `karpoland-sdk-ts/${SDK_VERSION}`;
|
|
208
|
+
|
|
209
|
+
// src/developer.ts
|
|
210
|
+
var bundleSha = (uri) => uri.slice(uri.lastIndexOf("/") + 1);
|
|
211
|
+
function createDeveloperClient(opts) {
|
|
212
|
+
if (!opts.token) throw new TypeError("createDeveloperClient: token (kat_\u2026) is required");
|
|
213
|
+
const t = createTransport({
|
|
214
|
+
base: opts.platform.replace(/\/+$/, "") + "/v1",
|
|
215
|
+
fetch: opts.fetch,
|
|
216
|
+
retry: opts.retry,
|
|
217
|
+
userAgent: USER_AGENT,
|
|
218
|
+
headers: () => ({ Authorization: `Bearer ${opts.token}` })
|
|
219
|
+
});
|
|
220
|
+
const a = (app) => {
|
|
221
|
+
if (!/^\d+$/.test(String(app))) throw new TypeError(`app is the app's numeric id (KARPO_APP_ID), not ${JSON.stringify(app)}; apps.ensureBySlug gives it`);
|
|
222
|
+
return `/apps/${enc(app)}`;
|
|
223
|
+
};
|
|
224
|
+
const tr = (id) => `/app-transfers/${enc(id)}`;
|
|
225
|
+
const one = async (key, p) => (await p)?.[key];
|
|
226
|
+
const list = async (key, p) => (await p)?.[key] ?? [];
|
|
227
|
+
return {
|
|
228
|
+
request: (method, path, body, query) => t.request(method, path, { body, query }),
|
|
229
|
+
apps: {
|
|
230
|
+
ensureBySlug: async (slug, input = {}) => {
|
|
231
|
+
const r = await t.request("PUT", `/apps/by-slug/${enc(slug)}`, { body: input });
|
|
232
|
+
return r?.app ?? { id: String(r?.app_id ?? "") };
|
|
233
|
+
},
|
|
234
|
+
get: (app) => t.request("GET", a(app)),
|
|
235
|
+
list: (query = {}) => list("apps", t.request("GET", "/apps", { query })),
|
|
236
|
+
update: (app, input) => one("app", t.request("PUT", a(app), { body: input })),
|
|
237
|
+
verifyDomain: (app, serviceUrl) => one("app", t.request("POST", `${a(app)}/domain/verify`, { body: { service_url: serviceUrl }, retry: false }))
|
|
238
|
+
},
|
|
239
|
+
keys: {
|
|
240
|
+
issue: (app, label = "") => t.request("POST", `${a(app)}/keys`, { body: { label } }),
|
|
241
|
+
list: (app) => list("keys", t.request("GET", `${a(app)}/keys`)),
|
|
242
|
+
revoke: async (app, keyId) => void await t.request("DELETE", `${a(app)}/keys/${enc(keyId)}`)
|
|
243
|
+
},
|
|
244
|
+
signing: {
|
|
245
|
+
rotate: (app, o = {}) => t.request("POST", `${a(app)}/signing-rotations`, { body: { revoke_all_keys: !!o.revokeAllKeys }, retry: false })
|
|
246
|
+
},
|
|
247
|
+
members: {
|
|
248
|
+
list: (app) => list("members", t.request("GET", `${a(app)}/members`)),
|
|
249
|
+
set: (app, resident, o = {}) => one("member", t.request("PUT", `${a(app)}/members/${enc(resident)}`, { body: o.bootstrap === void 0 ? {} : { bootstrap: o.bootstrap } })),
|
|
250
|
+
remove: async (app, resident) => void await t.request("DELETE", `${a(app)}/members/${enc(resident)}`)
|
|
251
|
+
},
|
|
252
|
+
transfers: {
|
|
253
|
+
create: (app, input) => one("transfer", t.request("POST", `${a(app)}/transfers`, { body: input, retry: false })),
|
|
254
|
+
list: (app, query = {}) => t.request("GET", `${a(app)}/transfers`, { query }),
|
|
255
|
+
mine: (query = {}) => t.request("GET", "/me/app-transfers", { query }),
|
|
256
|
+
accept: (id, o = {}) => one("transfer", t.request("POST", `${tr(id)}/accept`, { body: o.cutOff ? { cut_off: true } : {}, retry: false })),
|
|
257
|
+
decline: (id) => one("transfer", t.request("POST", `${tr(id)}/decline`, { body: {} })),
|
|
258
|
+
cancel: (id) => one("transfer", t.request("POST", `${tr(id)}/cancel`, { body: {} }))
|
|
259
|
+
},
|
|
260
|
+
bundles: {
|
|
261
|
+
upload: (app, zip2) => t.request("POST", `${a(app)}/bundles`, { body: zip2, headers: { "Content-Type": "application/zip" }, retry: false })
|
|
262
|
+
},
|
|
263
|
+
versions: {
|
|
264
|
+
list: (app) => list("versions", t.request("GET", `${a(app)}/versions`)),
|
|
265
|
+
publish: (app, input) => {
|
|
266
|
+
const m = input.manifest;
|
|
267
|
+
const body = { manifest: m, version: m.version };
|
|
268
|
+
if (input.bundle_uri) Object.assign(body, { bundle_uri: input.bundle_uri, bundle_sha256: bundleSha(input.bundle_uri) });
|
|
269
|
+
return t.request("POST", `${a(app)}/versions`, { body, retry: false });
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
installs: {
|
|
273
|
+
list: (app, query = {}) => t.request("GET", `${a(app)}/installs`, { query })
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/manifest.ts
|
|
279
|
+
var SCOPES = ["room:post", "session:rw", "board:rw", "message:send", "relation:read", "contacts:read", "timer:rw", "room:read", "room:gate"];
|
|
280
|
+
var HOOK_EVENTS = [
|
|
281
|
+
"app.installed",
|
|
282
|
+
"app.uninstalled",
|
|
283
|
+
"resident.first_seen",
|
|
284
|
+
"message.created",
|
|
285
|
+
"member.joined",
|
|
286
|
+
"member.left",
|
|
287
|
+
"member.join",
|
|
288
|
+
"session.created",
|
|
289
|
+
"session.started",
|
|
290
|
+
"session.paused",
|
|
291
|
+
"session.resumed",
|
|
292
|
+
"session.ended",
|
|
293
|
+
"session.cancelled",
|
|
294
|
+
"participant.changed",
|
|
295
|
+
"timer.fired",
|
|
296
|
+
"app.message.replied",
|
|
297
|
+
"app.upgraded"
|
|
298
|
+
];
|
|
299
|
+
var BASE_OUTCOMES = ["none", "won", "lost", "tied", "ranked", "quit", "timed_out", "disqualified"];
|
|
300
|
+
var LISTING_CATEGORIES = ["game", "social", "tool", "fun", "work"];
|
|
301
|
+
var CARD_SIZES = ["standard", "tall"];
|
|
302
|
+
var MAX_SESSION_BOARDS = 4;
|
|
303
|
+
var MAX_RELEASE_NOTES = 500;
|
|
304
|
+
var reName = /^[a-z][a-z0-9_]{0,63}$/;
|
|
305
|
+
var reKey = /^[a-z][a-z0-9_]{0,31}$/;
|
|
306
|
+
var reVersion = /^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;
|
|
307
|
+
var runes = (s) => typeof s === "string" ? [...s].length : 0;
|
|
308
|
+
var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
309
|
+
function validZone(tz) {
|
|
310
|
+
try {
|
|
311
|
+
new Intl.DateTimeFormat("en", { timeZone: tz });
|
|
312
|
+
return true;
|
|
313
|
+
} catch {
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function intChoice(c, def) {
|
|
318
|
+
if (c === void 0) return def;
|
|
319
|
+
if (typeof c === "number") return { default: c, min: c, max: c };
|
|
320
|
+
let { default: d, min = 0, max = 0 } = c;
|
|
321
|
+
if (min === 0 && max === 0) min = d, max = d;
|
|
322
|
+
return { default: d, min, max };
|
|
323
|
+
}
|
|
324
|
+
var MAX_CONNECT = 10;
|
|
325
|
+
var TOP_KEYS = ["name", "version", "pages", "connect", "scopes", "install_policy", "sessions", "boards", "tools", "commands", "hooks", "install_config", "listing", "release_notes", "labels"];
|
|
326
|
+
var TOOL_KEYS = ["name", "description", "parameters", "visibility", "example"];
|
|
327
|
+
var HOOK_KEYS = ["on", "filter", "handler", "say", "verify", "gate"];
|
|
328
|
+
var KIND_KEYS = ["kind", "title", "scopes", "create", "open_create", "join_modes", "default_join_mode", "listed", "capacity", "max_open", "open_ttl", "auto_start", "auto_end", "keep_seat_on_left_room", "invite_by", "boards", "outcomes", "labels", "serial", "card"];
|
|
329
|
+
var REFUSED = {
|
|
330
|
+
points: "points are not open to apps yet; remove manifest.points",
|
|
331
|
+
achievements: "app-defined achievements are not open yet; remove manifest.achievements",
|
|
332
|
+
"hooks[].call": "declarative call hooks are gone: use handler: true and call the tool's logic in the handler",
|
|
333
|
+
"sessions[].board": "a session kind's boards are a list: write boards: [ \u2026 ]"
|
|
334
|
+
};
|
|
335
|
+
var reCommandLiteral = /^[^{\s]+$/;
|
|
336
|
+
var rePagePath = /^(\/[A-Za-z0-9._~-]+)*\/?$/;
|
|
337
|
+
var reConnectHost = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
338
|
+
var LAND_DOMAINS = ["karpo.land", "karpo.ai"];
|
|
339
|
+
function oneEdit(a, b) {
|
|
340
|
+
if (Math.abs(a.length - b.length) > 1 || a === b) return false;
|
|
341
|
+
let i = 0;
|
|
342
|
+
let j = 0;
|
|
343
|
+
let edits = 0;
|
|
344
|
+
while (i < a.length && j < b.length) {
|
|
345
|
+
if (a[i] === b[j]) i++, j++;
|
|
346
|
+
else {
|
|
347
|
+
if (++edits > 1) return false;
|
|
348
|
+
if (a.length > b.length) i++;
|
|
349
|
+
else if (b.length > a.length) j++;
|
|
350
|
+
else i++, j++;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return edits + (a.length - i) + (b.length - j) <= 1;
|
|
354
|
+
}
|
|
355
|
+
function unknownKey(key, known) {
|
|
356
|
+
const near = known.find((k) => k === key + "s" || oneEdit(key, k));
|
|
357
|
+
return `unknown field "${key}"` + (near ? `; did you mean "${near}"?` : "");
|
|
358
|
+
}
|
|
359
|
+
function checkKeys(obj, known, at, ignored, refusedAt, bad) {
|
|
360
|
+
for (const k of Object.keys(obj)) {
|
|
361
|
+
if (known.includes(k) || ignored.includes(k)) continue;
|
|
362
|
+
const field = at ? `${at}.${k}` : k;
|
|
363
|
+
bad(field, REFUSED[refusedAt ? `${refusedAt}.${k}` : k] ?? unknownKey(k, known));
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function checkConnectOrigin(s, allowHttp = false) {
|
|
367
|
+
const want = "an origin is https:// or wss:// and a host, e.g. https://api.example.com or https://*.example.com";
|
|
368
|
+
if (typeof s !== "string") return want;
|
|
369
|
+
const m = s.toLowerCase().replace(/\/$/, "").match(/^([a-z]+):\/\/([^/?#@]+)$/);
|
|
370
|
+
if (!m) return want;
|
|
371
|
+
const [, scheme, hostport] = m;
|
|
372
|
+
if (scheme !== "https" && scheme !== "wss" && !(allowHttp && (scheme === "http" || scheme === "ws"))) return want;
|
|
373
|
+
const host = hostport.replace(/:\d+$/, "").replace(/^\*\./, "");
|
|
374
|
+
if (!reConnectHost.test(host)) return want;
|
|
375
|
+
if (LAND_DOMAINS.some((d) => host === d || host.endsWith("." + d))) return `${s} is Karpo Land's own host: pages reach Land without connect`;
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
function validateManifest(m, opts = {}) {
|
|
379
|
+
const issues = [];
|
|
380
|
+
const bad = (field, message) => issues.push({ field: "manifest" + (field ? "." + field : ""), message });
|
|
381
|
+
if (!isObj(m)) {
|
|
382
|
+
bad("", "manifest is a JSON object");
|
|
383
|
+
return issues;
|
|
384
|
+
}
|
|
385
|
+
const man = m;
|
|
386
|
+
checkKeys(m, TOP_KEYS, "", ["summary", "icon", "color", "default_locale", "service_url"], "", bad);
|
|
387
|
+
if (runes(man.name) === 0 || runes(man.name) > 40) bad("name", "name must be 1 to 40 characters (the platform still requires it in the manifest)");
|
|
388
|
+
if (typeof man.version !== "string" || !reVersion.test(man.version)) bad("version", "version must be MAJOR.MINOR.PATCH, e.g. 1.2.0");
|
|
389
|
+
if (man.install_policy !== void 0 && man.install_policy !== "anyone" && man.install_policy !== "developer") bad("install_policy", "install_policy is anyone or developer");
|
|
390
|
+
if (man.connect !== void 0) {
|
|
391
|
+
if (!Array.isArray(man.connect)) bad("connect", "connect is a list of origins");
|
|
392
|
+
else {
|
|
393
|
+
if (man.connect.length > MAX_CONNECT) bad("connect", `connect lists at most ${MAX_CONNECT} origins`);
|
|
394
|
+
man.connect.forEach((o, i) => {
|
|
395
|
+
const e = checkConnectOrigin(o, !!opts.allowHttp);
|
|
396
|
+
if (e) bad(`connect[${i}]`, e);
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
(man.pages ?? []).forEach((p, i) => {
|
|
401
|
+
if (!p?.name || typeof p.path !== "string" || !p.path.startsWith("/")) return bad(`pages[${i}]`, "a page needs a name and a path starting with /");
|
|
402
|
+
const segs = p.path.split("/");
|
|
403
|
+
if (!rePagePath.test(p.path) || segs.includes(".") || segs.includes("..")) bad(`pages[${i}]`, "a page path is plain segments of A-Z a-z 0-9 . _ ~ - (no . or .. segments, no %, \\, ? or #)");
|
|
404
|
+
});
|
|
405
|
+
(man.scopes ?? []).forEach((s, i) => {
|
|
406
|
+
if (!SCOPES.includes(s)) bad(`scopes[${i}]`, `unknown scope "${s}"`);
|
|
407
|
+
});
|
|
408
|
+
const tools = /* @__PURE__ */ new Set();
|
|
409
|
+
if ((man.tools ?? []).length > 100) bad("tools", "at most 100 tools");
|
|
410
|
+
(man.tools ?? []).forEach((t, i) => {
|
|
411
|
+
const f = `tools[${i}]`;
|
|
412
|
+
if (isObj(t)) checkKeys(t, TOOL_KEYS, f, [], "tools[]", bad);
|
|
413
|
+
if (typeof t?.name !== "string" || !reName.test(t.name)) bad(f + ".name", "tool names are a-z, 0-9 and _, starting with a letter");
|
|
414
|
+
else if (tools.has(t.name)) bad(f + ".name", `tool "${t.name}" is declared twice`);
|
|
415
|
+
else tools.add(t.name);
|
|
416
|
+
if (t?.visibility !== void 0 && t.visibility !== "room" && t.visibility !== "caller") bad(f + ".visibility", "visibility is room or caller");
|
|
417
|
+
if (t?.parameters !== void 0) {
|
|
418
|
+
if (!isObj(t.parameters)) bad(f + ".parameters", "parameters is not a valid JSON Schema: must be an object");
|
|
419
|
+
else if (t.parameters.type !== void 0 && t.parameters.type !== "object") bad(f + ".parameters", 'arguments are a JSON object: parameters.type must be "object"');
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
const boards = /* @__PURE__ */ new Set();
|
|
423
|
+
const addBoard = (b, field, sessionBoard) => {
|
|
424
|
+
if (!isObj(b)) return bad(field, "a board is an object");
|
|
425
|
+
if (typeof b.key !== "string" || !reKey.test(b.key)) return bad(field, "board keys are a-z, 0-9 and _, starting with a letter, at most 32");
|
|
426
|
+
if (boards.has(b.key)) return bad(field, `board "${b.key}" is declared twice`);
|
|
427
|
+
if (runes(b.name) === 0 || runes(b.name) > 20) return bad(field, "board name is 1 to 20 characters");
|
|
428
|
+
const owner = sessionBoard ? "session" : b.owner ?? "install";
|
|
429
|
+
if (!["session", "install", "app"].includes(owner)) return bad(field, "an app's board belongs to a session, an install or the app");
|
|
430
|
+
const period = b.period ?? "none";
|
|
431
|
+
if (!["none", "day", "week", "month", "manual"].includes(period)) return bad(field, "period is none, day, week, month or manual");
|
|
432
|
+
if (owner === "session" && period !== "none") return bad(field, "a session board has one period");
|
|
433
|
+
if (b.order !== void 0 && b.order !== "asc" && b.order !== "desc") return bad(field, "order is asc or desc");
|
|
434
|
+
const detail = b.detail ?? "full";
|
|
435
|
+
if (detail !== "full" && detail !== "top") return bad(field, "detail is full or top");
|
|
436
|
+
if (owner === "session" && detail !== "full") return bad(field, "a session board keeps every score");
|
|
437
|
+
if (b.visibility !== void 0 && !["app_only", "self", "participants", "room_members", "public"].includes(b.visibility)) return bad(field, `unknown visibility "${b.visibility}"`);
|
|
438
|
+
if (b.tz && !validZone(b.tz)) return bad(field, `unknown time zone "${b.tz}"`);
|
|
439
|
+
if (b.square !== void 0 && b.square !== null && typeof b.square !== "boolean") return bad(field, "square is true or false");
|
|
440
|
+
if (b.square && (owner !== "app" || (b.visibility ?? "public") !== "public")) return bad(field, "only a public app board shows on the square");
|
|
441
|
+
boards.add(b.key);
|
|
442
|
+
};
|
|
443
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
444
|
+
(man.sessions ?? []).forEach((k, i) => {
|
|
445
|
+
const f = `sessions[${i}]`;
|
|
446
|
+
if (isObj(k)) checkKeys(k, KIND_KEYS, f, [], "sessions[]", bad);
|
|
447
|
+
const err = sessionKindError(k);
|
|
448
|
+
if (err) return bad(f, err);
|
|
449
|
+
if (kinds.has(k.kind)) return bad(f + ".kind", `session kind "${k.kind}" is declared twice`);
|
|
450
|
+
if (k.card !== void 0 && k.card !== null) {
|
|
451
|
+
if (!isObj(k.card)) return bad(f + ".card", "card is an object");
|
|
452
|
+
if (k.card.size !== void 0 && !CARD_SIZES.includes(k.card.size)) return bad(f + ".card.size", "card.size is standard or tall");
|
|
453
|
+
}
|
|
454
|
+
kinds.add(k.kind);
|
|
455
|
+
if (k.boards !== void 0) {
|
|
456
|
+
if (!Array.isArray(k.boards)) return bad(f + ".boards", "boards is a list");
|
|
457
|
+
if (k.boards.length > MAX_SESSION_BOARDS) return bad(f + ".boards", `at most ${MAX_SESSION_BOARDS} boards per session kind`);
|
|
458
|
+
k.boards.forEach((b, j) => addBoard({ ...b, owner: "session" }, `${f}.boards[${j}]`, true));
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
(man.boards ?? []).forEach((b, i) => addBoard(b, `boards[${i}]`, false));
|
|
462
|
+
(man.commands ?? []).forEach((c, i) => {
|
|
463
|
+
const f = `commands[${i}]`;
|
|
464
|
+
if (!tools.has(c?.tool)) return bad(f + ".tool", `command calls unknown tool "${c?.tool}"`);
|
|
465
|
+
if (c.reply_to !== void 0 && c.reply_to !== "app_post" && c.reply_to !== "session_post") return bad(f + ".reply_to", "reply_to is app_post or session_post");
|
|
466
|
+
const p = typeof c.pattern === "string" ? c.pattern.trim() : "";
|
|
467
|
+
if (p === "" || runes(p) > 100) return bad(f + ".pattern", "a command pattern is 1 to 100 characters");
|
|
468
|
+
if (c.reply_to === void 0 && !reCommandLiteral.test(p.split(/\s+/)[0] ?? "")) bad(f + ".pattern", "a command without reply_to starts with a literal word (no {variable}); for any text use reply_to or a message.created hook with room:read");
|
|
469
|
+
});
|
|
470
|
+
(man.hooks ?? []).forEach((h, i) => {
|
|
471
|
+
const f = `hooks[${i}]`;
|
|
472
|
+
if (isObj(h)) checkKeys(h, HOOK_KEYS, f, ["timeout", "default"], "hooks[]", bad);
|
|
473
|
+
if (!HOOK_EVENTS.includes(h?.on)) return bad(f + ".on", `unknown event "${h?.on}"`);
|
|
474
|
+
let forms = [!!h.handler, h.say != null, h.verify != null].filter(Boolean).length;
|
|
475
|
+
if (h.gate && forms === 0) forms = 1;
|
|
476
|
+
if (forms !== 1 && h.call == null) return bad(f, "a hook has exactly one of handler, say and verify");
|
|
477
|
+
if (h.verify) {
|
|
478
|
+
if (h.on !== "member.join") return bad(f + ".verify", "verify answers member.join only");
|
|
479
|
+
if (!h.verify.questions?.length) return bad(f + ".verify.questions", "verify needs at least one question");
|
|
480
|
+
}
|
|
481
|
+
if (h.say && (!h.say.text || runes(h.say.text) > 500)) return bad(f + ".say.text", "say text is 1 to 500 characters");
|
|
482
|
+
if (h.gate && h.on !== "member.join") return bad(f + ".gate", "only member.join hooks gate");
|
|
483
|
+
if (h.filter?.pattern) {
|
|
484
|
+
try {
|
|
485
|
+
new RegExp(h.filter.pattern);
|
|
486
|
+
} catch (e) {
|
|
487
|
+
return bad(f + ".filter.pattern", e.message);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (h.on === "message.created" && !h.filter?.reply_to && !(man.scopes ?? []).includes("room:read"))
|
|
491
|
+
return bad(f, "a message.created hook without filter.reply_to receives every room message: declare the room:read scope");
|
|
492
|
+
if (h.on === "member.join" && !(man.scopes ?? []).includes("room:gate")) return bad(f, "member.join hooks see join requests: declare the room:gate scope");
|
|
493
|
+
});
|
|
494
|
+
if (man.listing !== void 0 && man.listing !== null) {
|
|
495
|
+
const l = man.listing;
|
|
496
|
+
if (!isObj(l)) bad("listing", "listing is an object");
|
|
497
|
+
else {
|
|
498
|
+
if (l.square !== void 0 && typeof l.square !== "boolean") bad("listing.square", "square is true or false");
|
|
499
|
+
if (!LISTING_CATEGORIES.includes(l.category)) bad("listing.category", "category is game, social, tool, fun or work");
|
|
500
|
+
if (l.tagline !== void 0 && (typeof l.tagline !== "string" || runes(l.tagline) > 30)) bad("listing.tagline", "tagline is at most 30 characters");
|
|
501
|
+
if (l.cover_color !== void 0 && typeof l.cover_color !== "string") bad("listing.cover_color", "cover_color is a string");
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (man.install_policy === "developer") {
|
|
505
|
+
if (isObj(man.listing) && man.listing.square === true) bad("install_policy", "install_policy developer keeps the app in its developers' rooms: it cannot list on the square (listing.square)");
|
|
506
|
+
else if ((man.sessions ?? []).some((k) => isObj(k) && Array.isArray(k.scopes) && k.scopes.includes("open")))
|
|
507
|
+
bad("install_policy", "install_policy developer keeps the app in its developers' rooms: it cannot declare an open-scope session kind");
|
|
508
|
+
}
|
|
509
|
+
if (man.release_notes !== void 0 && man.release_notes !== null) {
|
|
510
|
+
if (typeof man.release_notes !== "string") bad("release_notes", "release_notes is text");
|
|
511
|
+
else if (runes(man.release_notes) > MAX_RELEASE_NOTES) bad("release_notes", `release_notes is at most ${MAX_RELEASE_NOTES} characters`);
|
|
512
|
+
}
|
|
513
|
+
if (man.install_config !== void 0 && man.install_config !== null && !isObj(man.install_config)) bad("install_config", "install_config is not a valid JSON Schema: must be an object");
|
|
514
|
+
return issues;
|
|
515
|
+
}
|
|
516
|
+
function sessionKindError(k) {
|
|
517
|
+
if (!isObj(k) || typeof k.kind !== "string" || !reKey.test(k.kind)) return "kind is a-z, 0-9 and _, starting with a letter";
|
|
518
|
+
for (const s of k.scopes ?? []) if (!["room", "multi_room", "open"].includes(s)) return "scopes are room, multi_room and open";
|
|
519
|
+
if (k.create !== void 0 && !["owner", "admin", "member"].includes(k.create)) return "create is owner, admin or member";
|
|
520
|
+
if (k.open_create !== void 0 && !["anyone", "app"].includes(k.open_create)) return "open_create is anyone or app";
|
|
521
|
+
const modes = k.join_modes?.length ? k.join_modes : ["open", "approval", "invite"];
|
|
522
|
+
for (const j of modes) if (!["open", "approval", "invite"].includes(j)) return "join modes are open, approval and invite";
|
|
523
|
+
if (k.default_join_mode !== void 0 && !modes.includes(k.default_join_mode)) return "default_join_mode must be one of join_modes";
|
|
524
|
+
if (k.invite_by !== void 0 && !["host", "participants"].includes(k.invite_by)) return "invite_by is host or participants";
|
|
525
|
+
const c = k.capacity ?? {};
|
|
526
|
+
const ranges = [
|
|
527
|
+
intChoice(c.min_players, { default: 1, min: 1, max: 1e3 }),
|
|
528
|
+
intChoice(c.max_players, { default: 0, min: 0, max: 1e3 }),
|
|
529
|
+
intChoice(c.max_observers, { default: 0, min: 0, max: 1e3 })
|
|
530
|
+
];
|
|
531
|
+
for (const r of ranges) {
|
|
532
|
+
if (r.min > r.default || r.max > 0 && r.default > r.max || r.max > 1e3 || r.min < 0) return "capacity defaults must lie within their ranges, at most 1000";
|
|
533
|
+
}
|
|
534
|
+
if (k.auto_end !== void 0 && (k.auto_end < 0 || k.auto_end > 30 * 24 * 3600)) return "auto_end is at most 30 days";
|
|
535
|
+
if (k.serial !== void 0 && typeof k.serial !== "boolean") return "serial is true or false";
|
|
536
|
+
if ((k.outcomes ?? []).length > 10) return "at most 10 custom outcomes";
|
|
537
|
+
for (const o of k.outcomes ?? []) {
|
|
538
|
+
if (!BASE_OUTCOMES.includes(o?.base) || !reKey.test(o?.code ?? "")) return "a custom outcome has a code and a base outcome";
|
|
539
|
+
}
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// src/zip.ts
|
|
544
|
+
var table = (() => {
|
|
545
|
+
const t = new Uint32Array(256);
|
|
546
|
+
for (let n = 0; n < 256; n++) {
|
|
547
|
+
let c = n;
|
|
548
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
549
|
+
t[n] = c >>> 0;
|
|
550
|
+
}
|
|
551
|
+
return t;
|
|
552
|
+
})();
|
|
553
|
+
function crc32(buf) {
|
|
554
|
+
let c = 4294967295;
|
|
555
|
+
for (let i = 0; i < buf.length; i++) c = table[(c ^ buf[i]) & 255] ^ c >>> 8;
|
|
556
|
+
return (c ^ 4294967295) >>> 0;
|
|
557
|
+
}
|
|
558
|
+
function zip(files, opts = {}) {
|
|
559
|
+
const te = new TextEncoder();
|
|
560
|
+
const parts = [];
|
|
561
|
+
const central = [];
|
|
562
|
+
let offset = 0;
|
|
563
|
+
const names = Object.keys(files).sort();
|
|
564
|
+
for (const path of names) {
|
|
565
|
+
const raw = files[path];
|
|
566
|
+
const data = typeof raw === "string" ? te.encode(raw) : raw;
|
|
567
|
+
const name = te.encode(path.replace(/\\/g, "/").replace(/^\/+/, ""));
|
|
568
|
+
const crc = crc32(data);
|
|
569
|
+
let body = data;
|
|
570
|
+
let method = 0;
|
|
571
|
+
if (opts.deflateRaw && data.length > 64) {
|
|
572
|
+
const d = opts.deflateRaw(data);
|
|
573
|
+
if (d.length < data.length) body = d, method = 8;
|
|
574
|
+
}
|
|
575
|
+
const local = new Uint8Array(30);
|
|
576
|
+
const lv = new DataView(local.buffer);
|
|
577
|
+
lv.setUint32(0, 67324752, true);
|
|
578
|
+
lv.setUint16(4, 20, true);
|
|
579
|
+
lv.setUint16(6, 2048, true);
|
|
580
|
+
lv.setUint16(8, method, true);
|
|
581
|
+
lv.setUint32(14, crc, true);
|
|
582
|
+
lv.setUint32(18, body.length, true);
|
|
583
|
+
lv.setUint32(22, data.length, true);
|
|
584
|
+
lv.setUint16(26, name.length, true);
|
|
585
|
+
parts.push(local, name, body);
|
|
586
|
+
const c = new Uint8Array(46);
|
|
587
|
+
const cv = new DataView(c.buffer);
|
|
588
|
+
cv.setUint32(0, 33639248, true);
|
|
589
|
+
cv.setUint16(4, 20, true);
|
|
590
|
+
cv.setUint16(6, 20, true);
|
|
591
|
+
cv.setUint16(8, 2048, true);
|
|
592
|
+
cv.setUint16(10, method, true);
|
|
593
|
+
cv.setUint32(16, crc, true);
|
|
594
|
+
cv.setUint32(20, body.length, true);
|
|
595
|
+
cv.setUint32(24, data.length, true);
|
|
596
|
+
cv.setUint16(28, name.length, true);
|
|
597
|
+
cv.setUint32(42, offset, true);
|
|
598
|
+
central.push(c, name);
|
|
599
|
+
offset += local.length + name.length + body.length;
|
|
600
|
+
}
|
|
601
|
+
const cdSize = central.reduce((n, p) => n + p.length, 0);
|
|
602
|
+
const end = new Uint8Array(22);
|
|
603
|
+
const ev = new DataView(end.buffer);
|
|
604
|
+
ev.setUint32(0, 101010256, true);
|
|
605
|
+
ev.setUint16(8, names.length, true);
|
|
606
|
+
ev.setUint16(10, names.length, true);
|
|
607
|
+
ev.setUint32(12, cdSize, true);
|
|
608
|
+
ev.setUint32(16, offset, true);
|
|
609
|
+
const all = [...parts, ...central, end];
|
|
610
|
+
const out = new Uint8Array(all.reduce((n, p) => n + p.length, 0));
|
|
611
|
+
let o = 0;
|
|
612
|
+
for (const p of all) {
|
|
613
|
+
out.set(p, o);
|
|
614
|
+
o += p.length;
|
|
615
|
+
}
|
|
616
|
+
return out;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// src/cli.ts
|
|
620
|
+
var HELP = `karpoland \u2014 Karpo Land mini app CLI (npm exec --no -- karpoland \u2026)
|
|
621
|
+
|
|
622
|
+
karpoland version print the SDK version
|
|
623
|
+
karpoland zip <dir> [-o bundle.zip] pack a page directory; prints its sha256
|
|
624
|
+
karpoland validate --manifest <file> check a manifest like the platform does
|
|
625
|
+
karpoland register --slug <s> [--name <n>] [--service-url <url>] [--summary <s>] [--icon-url <u>] [--color <c>]
|
|
626
|
+
register the slug, or find your app's id; prints export KARPO_APP_ID=\u2026
|
|
627
|
+
karpoland key [--label <l>] issue a kap_ key (shown once) for the service's config
|
|
628
|
+
karpoland keys list the app's keys
|
|
629
|
+
karpoland installs rooms with the app, counted by version
|
|
630
|
+
karpoland publish --manifest <file> [--version <x.y.z>] [--pages <dir>] [--notes <text>]
|
|
631
|
+
checks the manifest, verifies the domain when needed,
|
|
632
|
+
uploads --pages (left out: the live pages stay) and
|
|
633
|
+
publishes; without a version, the next patch after the
|
|
634
|
+
live one, or "unchanged" when nothing changed
|
|
635
|
+
karpoland verify --service-url <url> move the service to another domain
|
|
636
|
+
|
|
637
|
+
Options: --app <id> (or KARPO_APP_ID; the numeric app id, not the slug),
|
|
638
|
+
--api <origin> (or KARPO_API), --allow-http (local stacks), --json.
|
|
639
|
+
KARPO_TOKEN is the developer token: an agent's kat_ (people use the creator
|
|
640
|
+
console); it is never printed. A step only a person may take answers with a
|
|
641
|
+
link: give it to your owner.`;
|
|
642
|
+
var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["allow-http", "json", "help"]);
|
|
643
|
+
function parseArgs(argv) {
|
|
644
|
+
const out = { _: [] };
|
|
645
|
+
for (let i = 0; i < argv.length; i++) {
|
|
646
|
+
const a = argv[i];
|
|
647
|
+
if (a === "-o") out.out = argv[++i] ?? "";
|
|
648
|
+
else if (a.startsWith("--")) {
|
|
649
|
+
const [k, v] = a.slice(2).split("=", 2);
|
|
650
|
+
if (v !== void 0) out[k] = v;
|
|
651
|
+
else if (!BOOLEAN_FLAGS.has(k) && i + 1 < argv.length && !argv[i + 1].startsWith("-")) out[k] = argv[++i];
|
|
652
|
+
else out[k] = true;
|
|
653
|
+
} else out._.push(a);
|
|
654
|
+
}
|
|
655
|
+
return out;
|
|
656
|
+
}
|
|
657
|
+
function readDir(dir) {
|
|
658
|
+
const root = resolve(dir);
|
|
659
|
+
const files = {};
|
|
660
|
+
const walk = (d) => {
|
|
661
|
+
for (const name of readdirSync(d)) {
|
|
662
|
+
if (name.startsWith(".")) continue;
|
|
663
|
+
const p = join(d, name);
|
|
664
|
+
if (statSync(p).isDirectory()) walk(p);
|
|
665
|
+
else files[relative(root, p).split("\\").join("/")] = readFileSync(p);
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
walk(root);
|
|
669
|
+
return files;
|
|
670
|
+
}
|
|
671
|
+
function packDir(dir) {
|
|
672
|
+
const files = readDir(dir);
|
|
673
|
+
if (!Object.keys(files).length) throw new Error(`${dir}: no files`);
|
|
674
|
+
if (!files["index.html"]) process.stderr.write(`warning: ${dir} has no index.html at its root
|
|
675
|
+
`);
|
|
676
|
+
return zip(files, { deflateRaw: (d) => deflateRawSync(d) });
|
|
677
|
+
}
|
|
678
|
+
function str(args, k) {
|
|
679
|
+
const v = args[k];
|
|
680
|
+
return typeof v === "string" ? v : void 0;
|
|
681
|
+
}
|
|
682
|
+
function need(args, k) {
|
|
683
|
+
const v = str(args, k);
|
|
684
|
+
if (!v) throw new Error(`--${k} is required`);
|
|
685
|
+
return v;
|
|
686
|
+
}
|
|
687
|
+
function developer(args) {
|
|
688
|
+
const token = process.env.KARPO_TOKEN;
|
|
689
|
+
if (!token) throw new Error("set KARPO_TOKEN to the developer token (an agent's kat_\u2026)");
|
|
690
|
+
const platform = str(args, "api") ?? process.env.KARPO_API;
|
|
691
|
+
if (!platform) throw new Error("set KARPO_API or --api to the Karpo Land API origin");
|
|
692
|
+
return createDeveloperClient({ token, platform });
|
|
693
|
+
}
|
|
694
|
+
function appId(args) {
|
|
695
|
+
const v = str(args, "app") ?? process.env.KARPO_APP_ID;
|
|
696
|
+
if (!v) throw new Error("set KARPO_APP_ID or --app to the app's id (karpoland register prints it)");
|
|
697
|
+
if (!/^\d+$/.test(v)) throw new Error(`--app takes the app's numeric id, not "${v}" (karpoland register --slug ${v} prints it)`);
|
|
698
|
+
return v;
|
|
699
|
+
}
|
|
700
|
+
function readManifest(file) {
|
|
701
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
702
|
+
}
|
|
703
|
+
function nextPatch(v) {
|
|
704
|
+
const [a, b, c] = v.split(".").map(Number);
|
|
705
|
+
return `${a}.${b}.${(c ?? 0) + 1}`;
|
|
706
|
+
}
|
|
707
|
+
function versionLess(a, b) {
|
|
708
|
+
const x = a.split(".").map(Number);
|
|
709
|
+
const y = b.split(".").map(Number);
|
|
710
|
+
for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0);
|
|
711
|
+
return false;
|
|
712
|
+
}
|
|
713
|
+
function content(m) {
|
|
714
|
+
const sort = (v) => Array.isArray(v) ? v.map(sort) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
|
|
715
|
+
const { version: _v, release_notes: _n, ...rest } = m ?? {};
|
|
716
|
+
return JSON.stringify(sort(rest));
|
|
717
|
+
}
|
|
718
|
+
function explain(e, out) {
|
|
719
|
+
if (e.code) {
|
|
720
|
+
out(`error: ${e.code}: ${e.message}${e.hint ? `
|
|
721
|
+
${e.hint}` : ""}`);
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
out(`error: ${e.status} ${e.reason} ${e.message}${e.detail?.field ? ` (field ${e.detail.field})` : ""}`);
|
|
725
|
+
const human = e.detail?.needs_human;
|
|
726
|
+
if (human?.url) out(` only a person can do this${human.name ? ` (${human.name})` : ""}: give your owner this link: ${human.url}`);
|
|
727
|
+
if (isReason(e, "app.SLUG_TAKEN") && e.detail?.cause === "use_app_id") out(" you are a member of the app with this slug: put its app_id in your config (KARPO_APP_ID) instead of registering");
|
|
728
|
+
else if (isReason(e, "app.SLUG_TAKEN")) out(" the slug is another app's: pick another --slug");
|
|
729
|
+
if (isReason(e, "key.INVALID")) out(" the app key is revoked or unknown: issue a new one (karpoland key) and configure the service");
|
|
730
|
+
}
|
|
731
|
+
async function main(argv, out = (s) => process.stdout.write(s + "\n")) {
|
|
732
|
+
const args = parseArgs(argv);
|
|
733
|
+
const cmd = args._[0];
|
|
734
|
+
const print = (human, data) => out(args.json ? JSON.stringify(data) : human);
|
|
735
|
+
if (args.help || args.h) {
|
|
736
|
+
out(HELP);
|
|
737
|
+
return 0;
|
|
738
|
+
}
|
|
739
|
+
try {
|
|
740
|
+
switch (cmd) {
|
|
741
|
+
case "version":
|
|
742
|
+
print(`karpoland ${SDK_VERSION}`, { version: SDK_VERSION });
|
|
743
|
+
return 0;
|
|
744
|
+
case "zip": {
|
|
745
|
+
const dir = args._[1];
|
|
746
|
+
if (!dir) throw new Error("usage: karpoland zip <dir> [-o bundle.zip]");
|
|
747
|
+
const z = packDir(dir);
|
|
748
|
+
const file = str(args, "out") ?? "bundle.zip";
|
|
749
|
+
writeFileSync(file, z);
|
|
750
|
+
const sha256 = createHash("sha256").update(z).digest("hex");
|
|
751
|
+
print(`${file}: ${Object.keys(readDir(dir)).length} files, ${z.length} bytes, sha256 ${sha256}`, { file, bytes: z.length, sha256 });
|
|
752
|
+
return 0;
|
|
753
|
+
}
|
|
754
|
+
case "validate": {
|
|
755
|
+
const m = readManifest(need(args, "manifest"));
|
|
756
|
+
const issues = validateManifest(m, { allowHttp: !!args["allow-http"] });
|
|
757
|
+
if (issues.length) {
|
|
758
|
+
for (const i of issues) out(`${i.field}: ${i.message}`);
|
|
759
|
+
return 1;
|
|
760
|
+
}
|
|
761
|
+
print(`ok: ${m.version ?? "(no version)"}, ${m.tools?.length ?? 0} tools`, { ok: true });
|
|
762
|
+
return 0;
|
|
763
|
+
}
|
|
764
|
+
case "register": {
|
|
765
|
+
const dev = developer(args);
|
|
766
|
+
const slug = need(args, "slug");
|
|
767
|
+
const r = await dev.apps.ensureBySlug(slug, {
|
|
768
|
+
name: str(args, "name"),
|
|
769
|
+
summary: str(args, "summary"),
|
|
770
|
+
icon_url: str(args, "icon-url"),
|
|
771
|
+
color: str(args, "color")
|
|
772
|
+
});
|
|
773
|
+
const id = String(r.id ?? "");
|
|
774
|
+
const url = str(args, "service-url");
|
|
775
|
+
if (url && r.service_url !== url) await dev.apps.update(id, { service_url: url });
|
|
776
|
+
print(`${slug}: app_id ${id}
|
|
777
|
+
export KARPO_APP_ID=${id}`, { app_id: id, slug });
|
|
778
|
+
return 0;
|
|
779
|
+
}
|
|
780
|
+
case "verify": {
|
|
781
|
+
const r = await developer(args).apps.verifyDomain(appId(args), need(args, "service-url"));
|
|
782
|
+
print(`${r.slug}: ${r.service_url} verified`, r);
|
|
783
|
+
return 0;
|
|
784
|
+
}
|
|
785
|
+
case "key": {
|
|
786
|
+
const r = await developer(args).keys.issue(appId(args), str(args, "label") ?? "cli");
|
|
787
|
+
print(`key ${r.key_id}: ${r.token}
|
|
788
|
+
shown once: put it in the service's secret config (KARPO_APP_KEY)`, r);
|
|
789
|
+
return 0;
|
|
790
|
+
}
|
|
791
|
+
case "keys": {
|
|
792
|
+
const r = await developer(args).keys.list(appId(args));
|
|
793
|
+
const lines = r.map((k) => `${k.id} ${k.label || "-"} created ${k.created_at}${k.last_used_at ? `, used ${k.last_used_at}` : ""}${k.revoked_at ? `, revoked ${k.revoked_at}` : ""}`);
|
|
794
|
+
print(lines.length ? lines.join("\n") : "no keys", { keys: r });
|
|
795
|
+
return 0;
|
|
796
|
+
}
|
|
797
|
+
case "installs": {
|
|
798
|
+
const r = await developer(args).installs.list(appId(args), { limit: 100 });
|
|
799
|
+
const by = /* @__PURE__ */ new Map();
|
|
800
|
+
for (const i of r.installs ?? []) by.set(i.version || "?", (by.get(i.version || "?") ?? 0) + 1);
|
|
801
|
+
const lines = [...by].sort((x, y) => y[1] - x[1]).map(([v, n]) => `${v} ${n} room${n === 1 ? "" : "s"}`);
|
|
802
|
+
print(lines.length ? lines.join("\n") + (r.next_offset ? "\n(first 100 rooms)" : "") : "not installed anywhere", r);
|
|
803
|
+
return 0;
|
|
804
|
+
}
|
|
805
|
+
case "publish": {
|
|
806
|
+
const app = appId(args);
|
|
807
|
+
const manifest = readManifest(need(args, "manifest"));
|
|
808
|
+
const given = str(args, "version");
|
|
809
|
+
if (given) manifest.version = given;
|
|
810
|
+
const notes = str(args, "notes");
|
|
811
|
+
if (notes !== void 0) manifest.release_notes = notes.replace(/\\n/g, "\n").trim();
|
|
812
|
+
const issues = validateManifest({ ...manifest, version: manifest.version || "0.0.0" }, { allowHttp: !!args["allow-http"] });
|
|
813
|
+
if (issues.length) throw new Error("invalid manifest:\n" + issues.map((i) => ` ${i.field}: ${i.message}`).join("\n"));
|
|
814
|
+
const dev = developer(args);
|
|
815
|
+
const { app: info } = await dev.apps.get(app);
|
|
816
|
+
const pages = str(args, "pages");
|
|
817
|
+
const packed = pages ? packDir(pages) : void 0;
|
|
818
|
+
if (!given && !(manifest.version && (!info.live_version || versionLess(info.live_version, manifest.version)))) {
|
|
819
|
+
if (!info.live_version) manifest.version = "1.0.0";
|
|
820
|
+
else {
|
|
821
|
+
const live = (await dev.versions.list(app)).find((v) => v.version === info.live_version);
|
|
822
|
+
const samePages = !packed || (live?.bundle_sha256 || "") === createHash("sha256").update(packed).digest("hex");
|
|
823
|
+
if (live && samePages && content(live.manifest) === content(manifest)) {
|
|
824
|
+
print(`unchanged: ${info.live_version} is live with this manifest and these pages`, { unchanged: true, version: info.live_version });
|
|
825
|
+
return 0;
|
|
826
|
+
}
|
|
827
|
+
manifest.version = nextPatch(info.live_version);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
if (info.domain_verified === false && info.service_url) {
|
|
831
|
+
await dev.apps.verifyDomain(app, info.service_url);
|
|
832
|
+
out(`verified ${info.service_url}`);
|
|
833
|
+
}
|
|
834
|
+
let bundle_uri;
|
|
835
|
+
if (packed) {
|
|
836
|
+
const up = await dev.bundles.upload(app, packed);
|
|
837
|
+
out(`uploaded ${up.files} files (${up.bytes} bytes) \u2192 ${up.bundle_uri}`);
|
|
838
|
+
bundle_uri = up.bundle_uri;
|
|
839
|
+
} else if (manifest.pages?.length && info.live_version) {
|
|
840
|
+
const live = (await dev.versions.list(app)).find((v) => v.version === info.live_version);
|
|
841
|
+
bundle_uri = live?.bundle_uri || void 0;
|
|
842
|
+
}
|
|
843
|
+
const r = await dev.versions.publish(app, { manifest, ...bundle_uri ? { bundle_uri } : {} });
|
|
844
|
+
print(`published ${r.app.slug} ${r.app.live_version} (handshake ${r.version.handshake_at})`, r);
|
|
845
|
+
return 0;
|
|
846
|
+
}
|
|
847
|
+
case void 0:
|
|
848
|
+
case "help":
|
|
849
|
+
case "--help":
|
|
850
|
+
out(HELP);
|
|
851
|
+
return cmd ? 0 : 1;
|
|
852
|
+
default:
|
|
853
|
+
out(`unknown command ${cmd}
|
|
854
|
+
|
|
855
|
+
${HELP}`);
|
|
856
|
+
return 1;
|
|
857
|
+
}
|
|
858
|
+
} catch (e) {
|
|
859
|
+
if (e instanceof PlatformError) explain(e, out);
|
|
860
|
+
else out(`error: ${e.message}`);
|
|
861
|
+
return 1;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
var invoked = process.argv[1] ? resolve(process.argv[1]) : "";
|
|
865
|
+
if (/(?:^|[\\/])(cli\.(?:js|ts|mjs)|karpoland)$/.test(invoked)) {
|
|
866
|
+
main(process.argv.slice(2)).then((code) => process.exit(code));
|
|
867
|
+
}
|
|
868
|
+
export {
|
|
869
|
+
main,
|
|
870
|
+
nextPatch,
|
|
871
|
+
packDir,
|
|
872
|
+
parseArgs,
|
|
873
|
+
readDir,
|
|
874
|
+
versionLess
|
|
875
|
+
};
|