@evopos/cli 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +76 -2
- package/dist/bin.js +8 -0
- package/dist/bin.js.map +1 -0
- package/dist/chunk-ZQ6F743F.js +1196 -0
- package/dist/chunk-ZQ6F743F.js.map +1 -0
- package/dist/index.d.ts +342 -0
- package/dist/index.js +83 -0
- package/dist/index.js.map +1 -0
- package/package.json +37 -5
|
@@ -0,0 +1,1196 @@
|
|
|
1
|
+
// src/api-base.ts
|
|
2
|
+
var DEFAULT_API_BASE = "https://developers.evopos.az";
|
|
3
|
+
var ApiBaseError = class extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "ApiBaseError";
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
function isLocalHost(hostname2) {
|
|
10
|
+
const h = hostname2.toLowerCase();
|
|
11
|
+
return h === "localhost" || h === "127.0.0.1" || h === "[::1]" || h.endsWith(".localhost") || h.endsWith(".test");
|
|
12
|
+
}
|
|
13
|
+
function normalizeApiBase(raw) {
|
|
14
|
+
let url;
|
|
15
|
+
try {
|
|
16
|
+
url = new URL(raw.trim());
|
|
17
|
+
} catch {
|
|
18
|
+
throw new ApiBaseError(`Invalid API address: ${raw}`);
|
|
19
|
+
}
|
|
20
|
+
if (url.username !== "" || url.password !== "") {
|
|
21
|
+
throw new ApiBaseError("The API address must not contain credentials.");
|
|
22
|
+
}
|
|
23
|
+
if (url.search !== "" || url.hash !== "") {
|
|
24
|
+
throw new ApiBaseError("The API address must not contain a query or a fragment.");
|
|
25
|
+
}
|
|
26
|
+
if (url.protocol === "http:") {
|
|
27
|
+
if (!isLocalHost(url.hostname)) {
|
|
28
|
+
throw new ApiBaseError(
|
|
29
|
+
`Plain http is allowed only for localhost, 127.0.0.1, [::1], *.localhost and *.test (got ${url.hostname}). Use https.`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
} else if (url.protocol !== "https:") {
|
|
33
|
+
throw new ApiBaseError(`Unsupported protocol ${url.protocol} in the API address (https only).`);
|
|
34
|
+
}
|
|
35
|
+
const base = (url.origin + url.pathname).replace(/\/+$/, "");
|
|
36
|
+
return { base, origin: url.origin };
|
|
37
|
+
}
|
|
38
|
+
function resolveApiBase(flag2, env = process.env) {
|
|
39
|
+
const chosen = flag2?.trim() || env.EVOPOS_API_BASE?.trim() || DEFAULT_API_BASE;
|
|
40
|
+
return normalizeApiBase(chosen);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/version.ts
|
|
44
|
+
var VERSION = "0.1.0";
|
|
45
|
+
function userAgent() {
|
|
46
|
+
return `evopos-cli/${VERSION} node/${process.versions.node}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/credentials.ts
|
|
50
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
|
|
51
|
+
import { homedir } from "os";
|
|
52
|
+
import { join } from "path";
|
|
53
|
+
var TOKEN_PATTERN = /^evo_cli_[A-Za-z0-9]{40}$/;
|
|
54
|
+
function isValidToken(value) {
|
|
55
|
+
return typeof value === "string" && TOKEN_PATTERN.test(value);
|
|
56
|
+
}
|
|
57
|
+
function configDir(env = process.env, platform = process.platform, home = homedir()) {
|
|
58
|
+
const override = env.EVOPOS_CONFIG_DIR?.trim();
|
|
59
|
+
if (override) return override;
|
|
60
|
+
if (platform === "win32") {
|
|
61
|
+
return join(env.APPDATA?.trim() || join(home, "AppData", "Roaming"), "evopos");
|
|
62
|
+
}
|
|
63
|
+
return join(env.XDG_CONFIG_HOME?.trim() || join(home, ".config"), "evopos");
|
|
64
|
+
}
|
|
65
|
+
function credentialsPath(env = process.env) {
|
|
66
|
+
return join(configDir(env), "credentials.json");
|
|
67
|
+
}
|
|
68
|
+
function parseExpiry(value) {
|
|
69
|
+
if (typeof value !== "string" || value === "") return null;
|
|
70
|
+
const bare = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(value);
|
|
71
|
+
const ms = Date.parse(bare ? value.replace(" ", "T") + "Z" : value);
|
|
72
|
+
return Number.isNaN(ms) ? null : ms;
|
|
73
|
+
}
|
|
74
|
+
function normalizeExpiry(value) {
|
|
75
|
+
const ms = parseExpiry(value);
|
|
76
|
+
return ms === null ? null : new Date(ms).toISOString();
|
|
77
|
+
}
|
|
78
|
+
var warnedPaths = /* @__PURE__ */ new Set();
|
|
79
|
+
function emptyFile() {
|
|
80
|
+
return { version: 1, hosts: {} };
|
|
81
|
+
}
|
|
82
|
+
function readCredentials(options = {}) {
|
|
83
|
+
const file = credentialsPath(options.env);
|
|
84
|
+
let raw;
|
|
85
|
+
try {
|
|
86
|
+
if (process.platform !== "win32" && options.warn && !warnedPaths.has(file)) {
|
|
87
|
+
const mode = statSync(file).mode;
|
|
88
|
+
if ((mode & 63) !== 0) {
|
|
89
|
+
warnedPaths.add(file);
|
|
90
|
+
options.warn(
|
|
91
|
+
`${file} is readable by other users (mode ${(mode & 511).toString(8)}). Run: chmod 600 "${file}"`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
raw = readFileSync(file, "utf8");
|
|
96
|
+
} catch {
|
|
97
|
+
return emptyFile();
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const json = JSON.parse(raw);
|
|
101
|
+
if (typeof json !== "object" || json === null) return emptyFile();
|
|
102
|
+
const hostsRaw = json.hosts;
|
|
103
|
+
const hosts = {};
|
|
104
|
+
if (typeof hostsRaw === "object" && hostsRaw !== null) {
|
|
105
|
+
for (const [origin, value] of Object.entries(hostsRaw)) {
|
|
106
|
+
const v = value;
|
|
107
|
+
if (v && typeof v.token === "string") {
|
|
108
|
+
hosts[origin] = {
|
|
109
|
+
token: v.token,
|
|
110
|
+
expires_at: typeof v.expires_at === "string" ? v.expires_at : null,
|
|
111
|
+
saved_at: typeof v.saved_at === "string" ? v.saved_at : ""
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return { version: 1, hosts };
|
|
117
|
+
} catch {
|
|
118
|
+
return emptyFile();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function writeCredentials(file, env) {
|
|
122
|
+
const dir = configDir(env);
|
|
123
|
+
const path = join(dir, "credentials.json");
|
|
124
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
125
|
+
if (process.platform !== "win32") chmodSync(dir, 448);
|
|
126
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
127
|
+
try {
|
|
128
|
+
writeFileSync(tmp, JSON.stringify(file, null, 4) + "\n", { mode: 384 });
|
|
129
|
+
if (process.platform !== "win32") chmodSync(tmp, 384);
|
|
130
|
+
renameSync(tmp, path);
|
|
131
|
+
} catch (e) {
|
|
132
|
+
rmSync(tmp, { force: true });
|
|
133
|
+
throw e;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function saveToken(origin, token, expiresAt, options = {}) {
|
|
137
|
+
if (!isValidToken(token)) throw new Error("Refusing to save a malformed token.");
|
|
138
|
+
const file = readCredentials({ env: options.env });
|
|
139
|
+
file.hosts[origin] = {
|
|
140
|
+
token,
|
|
141
|
+
expires_at: expiresAt,
|
|
142
|
+
saved_at: (options.now ? options.now() : /* @__PURE__ */ new Date()).toISOString()
|
|
143
|
+
};
|
|
144
|
+
writeCredentials(file, options.env);
|
|
145
|
+
}
|
|
146
|
+
function removeToken(origin, options = {}) {
|
|
147
|
+
const file = readCredentials({ env: options.env });
|
|
148
|
+
if (!(origin in file.hosts)) return false;
|
|
149
|
+
delete file.hosts[origin];
|
|
150
|
+
if (Object.keys(file.hosts).length === 0) {
|
|
151
|
+
rmSync(credentialsPath(options.env), { force: true });
|
|
152
|
+
} else {
|
|
153
|
+
writeCredentials(file, options.env);
|
|
154
|
+
}
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
function lookupToken(origin, options = {}) {
|
|
158
|
+
const env = options.env ?? process.env;
|
|
159
|
+
const now = options.now ? options.now() : Date.now();
|
|
160
|
+
const fromEnv = env.EVOPOS_TOKEN?.trim();
|
|
161
|
+
if (fromEnv) {
|
|
162
|
+
if (!isValidToken(fromEnv)) {
|
|
163
|
+
return {
|
|
164
|
+
ok: false,
|
|
165
|
+
reason: "invalid_format",
|
|
166
|
+
source: "env",
|
|
167
|
+
message: "EVOPOS_TOKEN is set but is not a valid CLI token (expected evo_cli_ followed by 40 letters or digits)."
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return { ok: true, token: fromEnv, source: "env", expiresAt: null };
|
|
171
|
+
}
|
|
172
|
+
const entry = readCredentials(options).hosts[origin];
|
|
173
|
+
if (!entry) {
|
|
174
|
+
return { ok: false, reason: "missing", source: null, message: `Not logged in to ${origin}. Run \`evopos login\`.` };
|
|
175
|
+
}
|
|
176
|
+
if (!isValidToken(entry.token)) {
|
|
177
|
+
return {
|
|
178
|
+
ok: false,
|
|
179
|
+
reason: "invalid_format",
|
|
180
|
+
source: "file",
|
|
181
|
+
message: `The saved token for ${origin} is malformed. Run \`evopos login\` again.`
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const expires = parseExpiry(entry.expires_at);
|
|
185
|
+
if (expires !== null && expires <= now) {
|
|
186
|
+
return {
|
|
187
|
+
ok: false,
|
|
188
|
+
reason: "expired",
|
|
189
|
+
source: "file",
|
|
190
|
+
message: `The saved token for ${origin} expired on ${new Date(expires).toISOString()}. Run \`evopos login\` again.`
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return { ok: true, token: entry.token, source: "file", expiresAt: entry.expires_at };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/client.ts
|
|
197
|
+
var EvoposApiError = class extends Error {
|
|
198
|
+
status;
|
|
199
|
+
code;
|
|
200
|
+
errors;
|
|
201
|
+
/** Что делать дальше (если известно). */
|
|
202
|
+
hint;
|
|
203
|
+
constructor(status, code, message, errors = [], hint) {
|
|
204
|
+
super(message);
|
|
205
|
+
this.name = "EvoposApiError";
|
|
206
|
+
this.status = status;
|
|
207
|
+
this.code = code;
|
|
208
|
+
this.errors = errors;
|
|
209
|
+
if (hint !== void 0) this.hint = hint;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
var POLL_STATES = /* @__PURE__ */ new Set(["authorization_pending", "slow_down", "expired_token", "access_denied"]);
|
|
213
|
+
function isRecord(v) {
|
|
214
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
215
|
+
}
|
|
216
|
+
var EvoposClient = class {
|
|
217
|
+
base;
|
|
218
|
+
token;
|
|
219
|
+
tokenSource;
|
|
220
|
+
fetchImpl;
|
|
221
|
+
timeoutMs;
|
|
222
|
+
uploadTimeoutMs;
|
|
223
|
+
constructor(options) {
|
|
224
|
+
if (options.token !== void 0 && !isValidToken(options.token)) {
|
|
225
|
+
throw new Error("Malformed CLI token.");
|
|
226
|
+
}
|
|
227
|
+
this.base = options.base.replace(/\/+$/, "");
|
|
228
|
+
this.token = options.token;
|
|
229
|
+
this.tokenSource = options.tokenSource;
|
|
230
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
231
|
+
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
232
|
+
this.uploadTimeoutMs = options.uploadTimeoutMs ?? 12e4;
|
|
233
|
+
}
|
|
234
|
+
unauthorizedHint() {
|
|
235
|
+
return this.tokenSource === "env" ? "The token in EVOPOS_TOKEN is invalid, expired or revoked. Issue a new one (evopos login) and update the variable, or unset it." : "Run `evopos login` to sign in again.";
|
|
236
|
+
}
|
|
237
|
+
async request(method, path, options = {}) {
|
|
238
|
+
const headers = {
|
|
239
|
+
Accept: "application/json",
|
|
240
|
+
"User-Agent": userAgent()
|
|
241
|
+
};
|
|
242
|
+
if (options.auth !== false && this.token) headers.Authorization = `Bearer ${this.token}`;
|
|
243
|
+
let body;
|
|
244
|
+
if (options.json !== void 0) {
|
|
245
|
+
headers["Content-Type"] = "application/json";
|
|
246
|
+
body = JSON.stringify(options.json);
|
|
247
|
+
} else if (options.form) {
|
|
248
|
+
body = options.form;
|
|
249
|
+
}
|
|
250
|
+
let res;
|
|
251
|
+
try {
|
|
252
|
+
res = await this.fetchImpl(`${this.base}/console/api${path}`, {
|
|
253
|
+
method,
|
|
254
|
+
headers,
|
|
255
|
+
...body !== void 0 ? { body } : {},
|
|
256
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? this.timeoutMs),
|
|
257
|
+
redirect: "error"
|
|
258
|
+
});
|
|
259
|
+
} catch (e) {
|
|
260
|
+
const err = e;
|
|
261
|
+
const reason = err.name === "TimeoutError" || err.name === "AbortError" ? "the request timed out" : err.cause?.code ?? err.message ?? "network failure";
|
|
262
|
+
throw new EvoposApiError(0, "network_error", `Cannot reach ${this.base}: ${reason}.`);
|
|
263
|
+
}
|
|
264
|
+
const text = await res.text().catch(() => "");
|
|
265
|
+
let parsed;
|
|
266
|
+
try {
|
|
267
|
+
parsed = text === "" ? void 0 : JSON.parse(text);
|
|
268
|
+
} catch {
|
|
269
|
+
parsed = void 0;
|
|
270
|
+
}
|
|
271
|
+
if (!res.ok) {
|
|
272
|
+
const obj = isRecord(parsed) ? parsed : {};
|
|
273
|
+
const code = typeof obj.error === "string" ? obj.error : parsed === void 0 ? "bad_response" : `http_${res.status}`;
|
|
274
|
+
const message = typeof obj.message === "string" && obj.message !== "" ? obj.message : parsed === void 0 ? `The server answered ${res.status} with a non-JSON body.` : `The server answered ${res.status}.`;
|
|
275
|
+
const errors = Array.isArray(obj.errors) ? obj.errors.filter((x) => typeof x === "string") : [];
|
|
276
|
+
const err = new EvoposApiError(res.status, code, message, errors);
|
|
277
|
+
if (res.status === 401) err.hint = this.unauthorizedHint();
|
|
278
|
+
throw err;
|
|
279
|
+
}
|
|
280
|
+
if (parsed === void 0 || !isRecord(parsed)) {
|
|
281
|
+
throw new EvoposApiError(res.status, "bad_response", `The server answered ${res.status} with a non-JSON body.`);
|
|
282
|
+
}
|
|
283
|
+
return { status: res.status, body: parsed };
|
|
284
|
+
}
|
|
285
|
+
/** Начать вход по коду устройства. */
|
|
286
|
+
async startDeviceFlow(clientName2) {
|
|
287
|
+
const { body } = await this.request("POST", "/cli/device", {
|
|
288
|
+
json: { client_name: clientName2 },
|
|
289
|
+
auth: false
|
|
290
|
+
});
|
|
291
|
+
return body;
|
|
292
|
+
}
|
|
293
|
+
/** Один опрос: токен или одно из состояний ожидания (`authorization_pending` и т. д.). Остальные ошибки — исключением. */
|
|
294
|
+
async pollToken(deviceCode) {
|
|
295
|
+
try {
|
|
296
|
+
const { body } = await this.request(
|
|
297
|
+
"POST",
|
|
298
|
+
"/cli/token",
|
|
299
|
+
{ json: { device_code: deviceCode }, auth: false }
|
|
300
|
+
);
|
|
301
|
+
if (!isValidToken(body.access_token)) {
|
|
302
|
+
throw new EvoposApiError(200, "bad_response", "The server returned a malformed token.");
|
|
303
|
+
}
|
|
304
|
+
return { state: "ok", access_token: body.access_token, token_type: body.token_type, expires_at: body.expires_at };
|
|
305
|
+
} catch (e) {
|
|
306
|
+
if (e instanceof EvoposApiError && e.status === 400 && POLL_STATES.has(e.code)) {
|
|
307
|
+
return { state: e.code };
|
|
308
|
+
}
|
|
309
|
+
throw e;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
async me() {
|
|
313
|
+
return (await this.request("GET", "/me")).body;
|
|
314
|
+
}
|
|
315
|
+
/** Отозвать текущий токен на сервере. */
|
|
316
|
+
async logout() {
|
|
317
|
+
return (await this.request("DELETE", "/cli/token")).body;
|
|
318
|
+
}
|
|
319
|
+
/** Загрузить zip (поле `package`). */
|
|
320
|
+
async uploadPackage(zip, filename = "plugin.zip") {
|
|
321
|
+
const form = new FormData();
|
|
322
|
+
form.append("package", new Blob([zip], { type: "application/zip" }), filename);
|
|
323
|
+
return (await this.request("POST", "/plugins/versions", { form, timeoutMs: this.uploadTimeoutMs })).body;
|
|
324
|
+
}
|
|
325
|
+
async submit(pluginId, version) {
|
|
326
|
+
const path = `/plugins/${encodeURIComponent(pluginId)}/versions/${encodeURIComponent(version)}/submit`;
|
|
327
|
+
return (await this.request("POST", path)).body;
|
|
328
|
+
}
|
|
329
|
+
async putDevSession(manifest, url) {
|
|
330
|
+
return (await this.request("PUT", "/sandbox/dev-session", { json: { manifest, url } })).body;
|
|
331
|
+
}
|
|
332
|
+
async deleteDevSession(pluginId) {
|
|
333
|
+
const query = pluginId ? `?id=${encodeURIComponent(pluginId)}` : "";
|
|
334
|
+
return (await this.request("DELETE", `/sandbox/dev-session${query}`)).body;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
function createClient(options) {
|
|
338
|
+
return new EvoposClient(options);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/device-flow.ts
|
|
342
|
+
var defaultSleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
343
|
+
async function runDeviceFlow(options) {
|
|
344
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
345
|
+
const now = options.now ?? Date.now;
|
|
346
|
+
const start = await options.client.startDeviceFlow(options.clientName);
|
|
347
|
+
await options.onCode?.(start);
|
|
348
|
+
const deadline = now() + start.expires_in * 1e3;
|
|
349
|
+
let interval = Math.max(1, start.interval);
|
|
350
|
+
for (; ; ) {
|
|
351
|
+
await sleep(interval * 1e3);
|
|
352
|
+
if (now() >= deadline) {
|
|
353
|
+
throw new EvoposApiError(400, "expired_token", "The login code expired before it was approved. Run `evopos login` again.");
|
|
354
|
+
}
|
|
355
|
+
const result = await options.client.pollToken(start.device_code);
|
|
356
|
+
switch (result.state) {
|
|
357
|
+
case "ok":
|
|
358
|
+
return { token: result.access_token, expiresAt: result.expires_at };
|
|
359
|
+
case "authorization_pending":
|
|
360
|
+
break;
|
|
361
|
+
case "slow_down":
|
|
362
|
+
interval += 5;
|
|
363
|
+
break;
|
|
364
|
+
case "expired_token":
|
|
365
|
+
throw new EvoposApiError(400, "expired_token", "The login code expired. Run `evopos login` again.");
|
|
366
|
+
case "access_denied":
|
|
367
|
+
throw new EvoposApiError(400, "access_denied", "The login was denied in the browser.");
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/zip.ts
|
|
373
|
+
import { deflateRawSync } from "zlib";
|
|
374
|
+
var CRC_TABLE = (() => {
|
|
375
|
+
const t = new Uint32Array(256);
|
|
376
|
+
for (let n = 0; n < 256; n++) {
|
|
377
|
+
let c = n;
|
|
378
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
379
|
+
t[n] = c >>> 0;
|
|
380
|
+
}
|
|
381
|
+
return t;
|
|
382
|
+
})();
|
|
383
|
+
function crc32(buf) {
|
|
384
|
+
let c = 4294967295;
|
|
385
|
+
for (const b of buf) c = CRC_TABLE[(c ^ b) & 255] ^ c >>> 8;
|
|
386
|
+
return (c ^ 4294967295) >>> 0;
|
|
387
|
+
}
|
|
388
|
+
function makeZip(entries) {
|
|
389
|
+
const DOS_TIME = 0;
|
|
390
|
+
const DOS_DATE = 2026 - 1980 << 9 | 11 << 5 | 18;
|
|
391
|
+
const locals = [];
|
|
392
|
+
const centrals = [];
|
|
393
|
+
let offset = 0;
|
|
394
|
+
for (const { name, data } of entries) {
|
|
395
|
+
const nameBuf = Buffer.from(name, "utf8");
|
|
396
|
+
const raw = Buffer.from(data);
|
|
397
|
+
const packed = deflateRawSync(raw, { level: 9 });
|
|
398
|
+
const useDeflate = packed.length < raw.length;
|
|
399
|
+
const body = useDeflate ? packed : raw;
|
|
400
|
+
const crc = crc32(raw);
|
|
401
|
+
const local = Buffer.alloc(30);
|
|
402
|
+
local.writeUInt32LE(67324752, 0);
|
|
403
|
+
local.writeUInt16LE(20, 4);
|
|
404
|
+
local.writeUInt16LE(2048, 6);
|
|
405
|
+
local.writeUInt16LE(useDeflate ? 8 : 0, 8);
|
|
406
|
+
local.writeUInt16LE(DOS_TIME, 10);
|
|
407
|
+
local.writeUInt16LE(DOS_DATE, 12);
|
|
408
|
+
local.writeUInt32LE(crc, 14);
|
|
409
|
+
local.writeUInt32LE(body.length, 18);
|
|
410
|
+
local.writeUInt32LE(raw.length, 22);
|
|
411
|
+
local.writeUInt16LE(nameBuf.length, 26);
|
|
412
|
+
local.writeUInt16LE(0, 28);
|
|
413
|
+
locals.push(local, nameBuf, body);
|
|
414
|
+
const central = Buffer.alloc(46);
|
|
415
|
+
central.writeUInt32LE(33639248, 0);
|
|
416
|
+
central.writeUInt16LE(20, 4);
|
|
417
|
+
central.writeUInt16LE(20, 6);
|
|
418
|
+
central.writeUInt16LE(2048, 8);
|
|
419
|
+
central.writeUInt16LE(useDeflate ? 8 : 0, 10);
|
|
420
|
+
central.writeUInt16LE(DOS_TIME, 12);
|
|
421
|
+
central.writeUInt16LE(DOS_DATE, 14);
|
|
422
|
+
central.writeUInt32LE(crc, 16);
|
|
423
|
+
central.writeUInt32LE(body.length, 20);
|
|
424
|
+
central.writeUInt32LE(raw.length, 24);
|
|
425
|
+
central.writeUInt16LE(nameBuf.length, 28);
|
|
426
|
+
central.writeUInt32LE(offset, 42);
|
|
427
|
+
centrals.push(central, nameBuf);
|
|
428
|
+
offset += local.length + nameBuf.length + body.length;
|
|
429
|
+
}
|
|
430
|
+
const centralBuf = Buffer.concat(centrals);
|
|
431
|
+
const end = Buffer.alloc(22);
|
|
432
|
+
end.writeUInt32LE(101010256, 0);
|
|
433
|
+
end.writeUInt16LE(entries.length, 8);
|
|
434
|
+
end.writeUInt16LE(entries.length, 10);
|
|
435
|
+
end.writeUInt32LE(centralBuf.length, 12);
|
|
436
|
+
end.writeUInt32LE(offset, 16);
|
|
437
|
+
return Buffer.concat([...locals, centralBuf, end]);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// src/package.ts
|
|
441
|
+
import { createHash } from "crypto";
|
|
442
|
+
import { existsSync as existsSync2, lstatSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, readdirSync, writeFileSync as writeFileSync2 } from "fs";
|
|
443
|
+
import { dirname, join as join2, relative, resolve } from "path";
|
|
444
|
+
import { validateDriverManifest, validatePluginManifest } from "@evopos/contracts";
|
|
445
|
+
var MAX_ZIP_BYTES = 5 * 1024 * 1024;
|
|
446
|
+
var MAX_FILES = 200;
|
|
447
|
+
var MAX_TOTAL_BYTES = 20 * 1024 * 1024;
|
|
448
|
+
var MAX_NAME_LENGTH = 200;
|
|
449
|
+
var ALLOWED_EXTENSIONS = ["html", "js", "mjs", "css", "json", "png", "svg", "webp", "jpg", "woff2"];
|
|
450
|
+
var SKIP = /* @__PURE__ */ new Set(["dist", "node_modules", "package.json", "package-lock.json", "README.md", ".DS_Store"]);
|
|
451
|
+
var MAX_REPORTED = 20;
|
|
452
|
+
var PackageError = class extends Error {
|
|
453
|
+
code;
|
|
454
|
+
errors;
|
|
455
|
+
constructor(code, message, errors = []) {
|
|
456
|
+
super(message);
|
|
457
|
+
this.name = "PackageError";
|
|
458
|
+
this.code = code;
|
|
459
|
+
this.errors = errors;
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
function resolvePackageDir(dir) {
|
|
463
|
+
const project = resolve(dir);
|
|
464
|
+
if (existsSync2(join2(project, "dist", "manifest.json"))) {
|
|
465
|
+
return { project, root: join2(project, "dist"), kind: "dist" };
|
|
466
|
+
}
|
|
467
|
+
if (existsSync2(join2(project, "manifest.json"))) {
|
|
468
|
+
return { project, root: project, kind: "source" };
|
|
469
|
+
}
|
|
470
|
+
throw new PackageError(
|
|
471
|
+
"no_manifest",
|
|
472
|
+
`No manifest.json in ${project} or ${join2(project, "dist")}. Run the command in the plugin folder (or build the project first).`
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
function listFiles(root, kind, skipPath) {
|
|
476
|
+
const out = [];
|
|
477
|
+
const walk = (dir) => {
|
|
478
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
|
|
479
|
+
if (entry.name.startsWith(".")) continue;
|
|
480
|
+
if (kind === "source" && SKIP.has(entry.name)) continue;
|
|
481
|
+
const full = join2(dir, entry.name);
|
|
482
|
+
if (skipPath !== void 0 && full === skipPath) continue;
|
|
483
|
+
if (entry.isDirectory()) walk(full);
|
|
484
|
+
else if (entry.isFile()) out.push(relative(root, full).split("\\").join("/"));
|
|
485
|
+
else throw new PackageError("unsupported_file", `${relative(root, full)}: symlinks and special files cannot be packed.`);
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
walk(root);
|
|
489
|
+
return out;
|
|
490
|
+
}
|
|
491
|
+
function nameProblem(name) {
|
|
492
|
+
if (name === "" || name.length > MAX_NAME_LENGTH || name.startsWith("/") || /[\\:\u0000-\u001f\u007f]/.test(name)) {
|
|
493
|
+
return `${printable(name)}: unsafe or too long file name (max ${MAX_NAME_LENGTH} characters, no \\ or :)`;
|
|
494
|
+
}
|
|
495
|
+
for (const segment of name.split("/")) {
|
|
496
|
+
if (segment === "" || segment === "." || segment === "..") {
|
|
497
|
+
return `${printable(name)}: unsafe path`;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
function printable(name) {
|
|
503
|
+
return name.replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, 80);
|
|
504
|
+
}
|
|
505
|
+
function checkEntries(files) {
|
|
506
|
+
const errors = [];
|
|
507
|
+
const push = (e) => {
|
|
508
|
+
if (errors.length < MAX_REPORTED) errors.push(e);
|
|
509
|
+
};
|
|
510
|
+
if (files.length === 0) push("The package is empty.");
|
|
511
|
+
if (files.length > MAX_FILES) push(`Too many files: ${files.length} (max ${MAX_FILES}).`);
|
|
512
|
+
const seen = /* @__PURE__ */ new Set();
|
|
513
|
+
let total = 0;
|
|
514
|
+
for (const f of files) {
|
|
515
|
+
total += f.size;
|
|
516
|
+
const problem = nameProblem(f.name);
|
|
517
|
+
if (problem) {
|
|
518
|
+
push(problem);
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
const ext = f.name.includes(".") ? f.name.slice(f.name.lastIndexOf(".") + 1).toLowerCase() : "";
|
|
522
|
+
if (!ALLOWED_EXTENSIONS.includes(ext)) {
|
|
523
|
+
push(`${f.name}: file type not allowed (allowed: ${ALLOWED_EXTENSIONS.join(", ")}).`);
|
|
524
|
+
}
|
|
525
|
+
const key = f.name.toLowerCase();
|
|
526
|
+
if (seen.has(key)) push(`${f.name}: duplicate name (case-insensitive).`);
|
|
527
|
+
seen.add(key);
|
|
528
|
+
}
|
|
529
|
+
if (total > MAX_TOTAL_BYTES) push(`Unpacked size ${total} bytes exceeds the limit of ${MAX_TOTAL_BYTES / 1024 / 1024} MB.`);
|
|
530
|
+
return errors;
|
|
531
|
+
}
|
|
532
|
+
function checkReferences(manifest, names) {
|
|
533
|
+
const errors = [];
|
|
534
|
+
const m = manifest;
|
|
535
|
+
if (m.kind === "driver") {
|
|
536
|
+
if (typeof m.entry === "string" && !names.has(m.entry)) errors.push(`/entry: file ${m.entry} is not in the package.`);
|
|
537
|
+
return errors;
|
|
538
|
+
}
|
|
539
|
+
(m.slots ?? []).forEach((slot, i) => {
|
|
540
|
+
const entry = slot.entry;
|
|
541
|
+
if (typeof entry !== "string") return;
|
|
542
|
+
if (!/\.html$/i.test(entry)) errors.push(`/slots/${i}/entry: ${entry} must be an .html file.`);
|
|
543
|
+
if (!names.has(entry)) errors.push(`/slots/${i}/entry: file ${entry} is not in the package.`);
|
|
544
|
+
});
|
|
545
|
+
return errors;
|
|
546
|
+
}
|
|
547
|
+
function inspectPackage(dir, options = {}) {
|
|
548
|
+
const pkg = resolvePackageDir(dir);
|
|
549
|
+
const manifestPath = join2(pkg.root, "manifest.json");
|
|
550
|
+
let json;
|
|
551
|
+
try {
|
|
552
|
+
json = JSON.parse(readFileSync2(manifestPath, "utf8"));
|
|
553
|
+
} catch (e) {
|
|
554
|
+
throw new PackageError("manifest_json", `manifest.json is not valid JSON: ${e.message}`);
|
|
555
|
+
}
|
|
556
|
+
const isDriver = typeof json === "object" && json !== null && json.kind === "driver";
|
|
557
|
+
const result = isDriver ? validateDriverManifest(json) : validatePluginManifest(json);
|
|
558
|
+
if (!result.ok) {
|
|
559
|
+
throw new PackageError("manifest_invalid", "manifest.json failed validation.", result.errors);
|
|
560
|
+
}
|
|
561
|
+
const extras = new Map((options.extraFiles ?? []).map((f) => [f.name, f]));
|
|
562
|
+
const files = [];
|
|
563
|
+
for (const name of listFiles(pkg.root, pkg.kind, options.skipPath)) {
|
|
564
|
+
if (extras.has(name)) continue;
|
|
565
|
+
const path = join2(pkg.root, name);
|
|
566
|
+
files.push({ name, path, size: lstatSync(path).size });
|
|
567
|
+
}
|
|
568
|
+
for (const f of extras.values()) files.push({ name: f.name, size: f.data.byteLength });
|
|
569
|
+
files.sort(compareNames);
|
|
570
|
+
const errors = [...checkEntries(files), ...checkReferences(json, new Set(files.map((f) => f.name)))];
|
|
571
|
+
if (errors.length > 0) throw new PackageError("package_invalid", "The package does not pass the checks.", errors);
|
|
572
|
+
return { ...pkg, manifest: result.manifest, files };
|
|
573
|
+
}
|
|
574
|
+
function compareNames(a, b) {
|
|
575
|
+
if (a.name === "manifest.json") return -1;
|
|
576
|
+
if (b.name === "manifest.json") return 1;
|
|
577
|
+
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
578
|
+
}
|
|
579
|
+
function validateManifestFile(dir, options = {}) {
|
|
580
|
+
try {
|
|
581
|
+
const p = inspectPackage(dir, options);
|
|
582
|
+
return { ok: true, manifest: p.manifest, root: p.root, files: p.files.map((f) => f.name), errors: [] };
|
|
583
|
+
} catch (e) {
|
|
584
|
+
if (e instanceof PackageError) return { ok: false, code: e.code, errors: e.errors.length ? e.errors : [e.message] };
|
|
585
|
+
throw e;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
function defaultOutPath(project, id, version) {
|
|
589
|
+
return join2(project, ".evopos", `${id}-${version}.zip`);
|
|
590
|
+
}
|
|
591
|
+
function packPlugin(options) {
|
|
592
|
+
const project = resolve(options.dir);
|
|
593
|
+
const pkg = resolvePackageDir(project);
|
|
594
|
+
let outPath = typeof options.out === "string" ? resolve(options.out) : null;
|
|
595
|
+
const preliminary = outPath ?? void 0;
|
|
596
|
+
let info = inspectPackage(project, { extraFiles: options.extraFiles, ...preliminary ? { skipPath: preliminary } : {} });
|
|
597
|
+
if (outPath === null) {
|
|
598
|
+
const { id, version } = info.manifest;
|
|
599
|
+
outPath = resolve(typeof options.out === "function" ? options.out({ id, version }) : defaultOutPath(pkg.project, id, version));
|
|
600
|
+
info = inspectPackage(project, { extraFiles: options.extraFiles, skipPath: outPath });
|
|
601
|
+
}
|
|
602
|
+
const extras = new Map((options.extraFiles ?? []).map((f) => [f.name, f.data]));
|
|
603
|
+
const entries = info.files.map((f) => ({
|
|
604
|
+
name: f.name,
|
|
605
|
+
data: f.path ? readFileSync2(f.path) : extras.get(f.name)
|
|
606
|
+
}));
|
|
607
|
+
const zip = makeZip(entries);
|
|
608
|
+
if (zip.length > MAX_ZIP_BYTES) {
|
|
609
|
+
throw new PackageError(
|
|
610
|
+
"zip_too_big",
|
|
611
|
+
`The archive is ${zip.length} bytes; the server accepts at most ${MAX_ZIP_BYTES / 1024 / 1024} MB.`
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
mkdirSync2(dirname(outPath), { recursive: true });
|
|
615
|
+
writeFileSync2(outPath, zip);
|
|
616
|
+
return {
|
|
617
|
+
file: outPath,
|
|
618
|
+
bytes: zip.length,
|
|
619
|
+
files: entries.map((e) => e.name),
|
|
620
|
+
sha256: createHash("sha256").update(zip).digest("hex"),
|
|
621
|
+
manifest: info.manifest
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// src/browser.ts
|
|
626
|
+
import { spawn as nodeSpawn } from "child_process";
|
|
627
|
+
function browserCommand(url, platform) {
|
|
628
|
+
if (platform === "darwin") return { command: "open", args: [url] };
|
|
629
|
+
if (platform === "win32") return { command: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
|
|
630
|
+
return { command: "xdg-open", args: [url] };
|
|
631
|
+
}
|
|
632
|
+
function openInBrowser(rawUrl, deps = {}) {
|
|
633
|
+
let url;
|
|
634
|
+
try {
|
|
635
|
+
url = new URL(rawUrl);
|
|
636
|
+
} catch {
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") return false;
|
|
640
|
+
const { command, args } = browserCommand(url.href, deps.platform ?? process.platform);
|
|
641
|
+
try {
|
|
642
|
+
const child = (deps.spawn ?? nodeSpawn)(command, args, { detached: true, stdio: "ignore", shell: false });
|
|
643
|
+
child.on("error", () => void 0);
|
|
644
|
+
child.unref();
|
|
645
|
+
return true;
|
|
646
|
+
} catch {
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// src/cli/context.ts
|
|
652
|
+
import { spawn } from "child_process";
|
|
653
|
+
import { hostname } from "os";
|
|
654
|
+
function defaultRunBuild(dir, json) {
|
|
655
|
+
return new Promise((resolve3) => {
|
|
656
|
+
const child = spawn(process.platform === "win32" ? "npm.cmd" : "npm", ["run", "build"], {
|
|
657
|
+
cwd: dir,
|
|
658
|
+
// с --json вывод сборки не должен попасть в stdout, где один JSON-объект
|
|
659
|
+
stdio: json ? ["inherit", 2, 2] : "inherit",
|
|
660
|
+
// .cmd без shell на Windows не запускается; аргументы константные
|
|
661
|
+
shell: process.platform === "win32"
|
|
662
|
+
});
|
|
663
|
+
child.on("error", () => resolve3(1));
|
|
664
|
+
child.on("close", (code) => resolve3(code ?? 1));
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
function defaultContext() {
|
|
668
|
+
const noColor = (process.env.NO_COLOR ?? "") !== "";
|
|
669
|
+
return {
|
|
670
|
+
env: process.env,
|
|
671
|
+
stdout: process.stdout,
|
|
672
|
+
stderr: process.stderr,
|
|
673
|
+
stdin: process.stdin,
|
|
674
|
+
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
675
|
+
color: Boolean(process.stderr.isTTY && process.stdout.isTTY) && !noColor,
|
|
676
|
+
cwd: process.cwd(),
|
|
677
|
+
hostname: hostname(),
|
|
678
|
+
openUrl: (url) => openInBrowser(url),
|
|
679
|
+
runBuild: defaultRunBuild
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// src/cli/main.ts
|
|
684
|
+
import { parseArgs } from "util";
|
|
685
|
+
|
|
686
|
+
// src/cli/commands.ts
|
|
687
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
688
|
+
import { basename, join as join3, relative as relative2, resolve as resolve2 } from "path";
|
|
689
|
+
|
|
690
|
+
// src/cli/errors.ts
|
|
691
|
+
var CliError = class extends Error {
|
|
692
|
+
code;
|
|
693
|
+
errors;
|
|
694
|
+
hint;
|
|
695
|
+
exitCode;
|
|
696
|
+
constructor(code, message, options = {}) {
|
|
697
|
+
super(message);
|
|
698
|
+
this.name = "CliError";
|
|
699
|
+
this.code = code;
|
|
700
|
+
this.errors = options.errors ?? [];
|
|
701
|
+
this.hint = options.hint;
|
|
702
|
+
this.exitCode = options.exitCode ?? 1;
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
var UsageError = class extends CliError {
|
|
706
|
+
constructor(message) {
|
|
707
|
+
super("usage", message, { exitCode: 2 });
|
|
708
|
+
this.name = "UsageError";
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
function apiHint(e, base) {
|
|
712
|
+
if (e.hint) return e.hint;
|
|
713
|
+
switch (e.code) {
|
|
714
|
+
case "version_exists":
|
|
715
|
+
return "This version is already in review or approved. Raise `version` in manifest.json and deploy again.";
|
|
716
|
+
case "plugin_id_taken":
|
|
717
|
+
return "This plugin id belongs to another developer account. Choose a different `id` in manifest.json.";
|
|
718
|
+
case "sandbox_unavailable":
|
|
719
|
+
return `You have no sandbox yet. Create one in ${base}/console and try again.`;
|
|
720
|
+
case "bad_status":
|
|
721
|
+
return "Only a draft version can be submitted for review.";
|
|
722
|
+
case "plugin_not_found":
|
|
723
|
+
return "Upload the version first: `evopos deploy`.";
|
|
724
|
+
default:
|
|
725
|
+
return e.status >= 500 ? "This is a problem on the server side. Try again later." : void 0;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
function describeError(e, base) {
|
|
729
|
+
if (e instanceof CliError) {
|
|
730
|
+
return { code: e.code, message: e.message, errors: e.errors, ...e.hint ? { hint: e.hint } : {}, exitCode: e.exitCode };
|
|
731
|
+
}
|
|
732
|
+
if (e instanceof EvoposApiError) {
|
|
733
|
+
const hint = apiHint(e, base);
|
|
734
|
+
return { code: e.code, message: e.message, errors: e.errors, ...hint ? { hint } : {}, exitCode: 1 };
|
|
735
|
+
}
|
|
736
|
+
if (e instanceof PackageError) {
|
|
737
|
+
return { code: e.code, message: e.message, errors: e.errors, exitCode: 1 };
|
|
738
|
+
}
|
|
739
|
+
if (e instanceof ApiBaseError) {
|
|
740
|
+
return { code: "invalid_api_base", message: e.message, errors: [], exitCode: 2 };
|
|
741
|
+
}
|
|
742
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
743
|
+
return { code: "internal_error", message, errors: [], exitCode: 1 };
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// src/cli/commands.ts
|
|
747
|
+
var str = (v) => typeof v === "string" ? v : void 0;
|
|
748
|
+
var flag = (v) => v === true;
|
|
749
|
+
function dirArg(env) {
|
|
750
|
+
if (env.args.positionals.length > 1) throw new UsageError("Too many arguments.");
|
|
751
|
+
return resolve2(env.ctx.cwd, env.args.positionals[0] ?? ".");
|
|
752
|
+
}
|
|
753
|
+
function noPositionals(env) {
|
|
754
|
+
if (env.args.positionals.length > 0) throw new UsageError(`Unexpected argument: ${env.args.positionals[0]}`);
|
|
755
|
+
}
|
|
756
|
+
function newClient(env, token, source) {
|
|
757
|
+
return createClient({
|
|
758
|
+
base: env.base,
|
|
759
|
+
...token ? { token } : {},
|
|
760
|
+
...source ? { tokenSource: source } : {},
|
|
761
|
+
...env.ctx.fetch ? { fetch: env.ctx.fetch } : {}
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
function authedClient(env) {
|
|
765
|
+
const found = lookupToken(env.origin, {
|
|
766
|
+
env: env.ctx.env,
|
|
767
|
+
warn: (m) => env.out.warn(m),
|
|
768
|
+
...env.ctx.now ? { now: env.ctx.now } : {}
|
|
769
|
+
});
|
|
770
|
+
if (!found.ok) {
|
|
771
|
+
throw new CliError(found.reason === "expired" ? "token_expired" : found.reason === "missing" ? "not_logged_in" : "invalid_token", found.message);
|
|
772
|
+
}
|
|
773
|
+
return newClient(env, found.token, found.source);
|
|
774
|
+
}
|
|
775
|
+
async function readStdin(ctx) {
|
|
776
|
+
let data = "";
|
|
777
|
+
for await (const chunk of ctx.stdin) {
|
|
778
|
+
data += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
|
|
779
|
+
if (data.length > 65536) throw new UsageError("Token input is too long.");
|
|
780
|
+
}
|
|
781
|
+
return data.trim();
|
|
782
|
+
}
|
|
783
|
+
function clientName(ctx) {
|
|
784
|
+
const host = ctx.hostname.replace(/[\u0000-\u001f\u007f]/g, "").trim() || "unknown host";
|
|
785
|
+
return `EvoPOS CLI on ${host}`.slice(0, 100);
|
|
786
|
+
}
|
|
787
|
+
async function login(env) {
|
|
788
|
+
const { ctx, out, args } = env;
|
|
789
|
+
noPositionals(env);
|
|
790
|
+
const withToken = flag(args.values["with-token"]);
|
|
791
|
+
const tokenFlag = str(args.values.token);
|
|
792
|
+
if (withToken && tokenFlag !== void 0) throw new UsageError("Use either --with-token or --token, not both.");
|
|
793
|
+
if (ctx.env.EVOPOS_TOKEN?.trim()) {
|
|
794
|
+
out.warn("EVOPOS_TOKEN is set and takes priority over the saved token. Unset it to use the login saved by this command.");
|
|
795
|
+
}
|
|
796
|
+
let token;
|
|
797
|
+
let expiresAt = null;
|
|
798
|
+
let source;
|
|
799
|
+
if (withToken || tokenFlag !== void 0) {
|
|
800
|
+
source = "flag";
|
|
801
|
+
if (withToken) {
|
|
802
|
+
if (ctx.stdin.isTTY) out.say("Paste the token, then press Ctrl-D:");
|
|
803
|
+
token = await readStdin(ctx);
|
|
804
|
+
} else {
|
|
805
|
+
out.warn("--token leaves the token in your shell history and process list. Prefer `evopos login --with-token < file` or EVOPOS_TOKEN.");
|
|
806
|
+
token = tokenFlag.trim();
|
|
807
|
+
}
|
|
808
|
+
if (!isValidToken(token)) {
|
|
809
|
+
throw new CliError("invalid_token", "That is not a valid CLI token (expected evo_cli_ followed by 40 letters or digits).");
|
|
810
|
+
}
|
|
811
|
+
} else {
|
|
812
|
+
source = "device";
|
|
813
|
+
const flow = await runDeviceFlow({
|
|
814
|
+
client: newClient(env),
|
|
815
|
+
clientName: clientName(ctx),
|
|
816
|
+
...ctx.sleep ? { sleep: ctx.sleep } : {},
|
|
817
|
+
...ctx.now ? { now: ctx.now } : {},
|
|
818
|
+
onCode: (start) => {
|
|
819
|
+
out.say(`First, copy your one-time code: ${out.bold(start.user_code)}`);
|
|
820
|
+
const sameOrigin = sameOriginAs(start.verification_uri_complete, env.origin);
|
|
821
|
+
const opened = sameOrigin && !flag(args.values["no-browser"]) && ctx.interactive && ctx.openUrl(start.verification_uri_complete);
|
|
822
|
+
if (opened) out.say(`Opening ${start.verification_uri} in your browser...`);
|
|
823
|
+
else out.say(`Open ${start.verification_uri_complete} in your browser and approve the code.`);
|
|
824
|
+
out.say("Waiting for approval...");
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
token = flow.token;
|
|
828
|
+
expiresAt = flow.expiresAt;
|
|
829
|
+
}
|
|
830
|
+
const me = await newClient(env, token, source).me();
|
|
831
|
+
saveToken(env.origin, token, expiresAt ?? normalizeExpiry(me.token.expires_at), {
|
|
832
|
+
env: ctx.env,
|
|
833
|
+
...ctx.now ? { now: () => new Date(ctx.now()) } : {}
|
|
834
|
+
});
|
|
835
|
+
out.result(`Logged in as ${me.account.email}`, {
|
|
836
|
+
logged_in: true,
|
|
837
|
+
api: env.base,
|
|
838
|
+
account: me.account,
|
|
839
|
+
token: { name: me.token.name, expires_at: me.token.expires_at },
|
|
840
|
+
sandbox: me.sandbox
|
|
841
|
+
});
|
|
842
|
+
return 0;
|
|
843
|
+
}
|
|
844
|
+
async function logout(env) {
|
|
845
|
+
const { ctx, out } = env;
|
|
846
|
+
noPositionals(env);
|
|
847
|
+
const envNote = ctx.env.EVOPOS_TOKEN?.trim() ? "EVOPOS_TOKEN is set in the environment; it was not touched." : null;
|
|
848
|
+
const found = lookupToken(env.origin, { env: { ...ctx.env, EVOPOS_TOKEN: void 0 }, warn: (m) => out.warn(m) });
|
|
849
|
+
let revoked = null;
|
|
850
|
+
if (found.ok) {
|
|
851
|
+
try {
|
|
852
|
+
revoked = (await newClient(env, found.token, "file").logout()).revoked;
|
|
853
|
+
} catch (e) {
|
|
854
|
+
if (e instanceof EvoposApiError && e.status === 401) {
|
|
855
|
+
revoked = false;
|
|
856
|
+
} else {
|
|
857
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
858
|
+
out.warn(`Could not revoke the token on the server (${reason}). Revoke it manually at ${env.base}/console/cli.`);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
const removed = removeToken(env.origin, { env: ctx.env });
|
|
863
|
+
if (envNote) out.warn(envNote);
|
|
864
|
+
out.result(removed ? `Logged out of ${env.origin}.` : `You were not logged in to ${env.origin}.`, {
|
|
865
|
+
logged_out: removed,
|
|
866
|
+
revoked,
|
|
867
|
+
api: env.base
|
|
868
|
+
});
|
|
869
|
+
return 0;
|
|
870
|
+
}
|
|
871
|
+
async function whoami(env) {
|
|
872
|
+
noPositionals(env);
|
|
873
|
+
const found = lookupToken(env.origin, { env: env.ctx.env, warn: (m) => env.out.warn(m) });
|
|
874
|
+
const me = await authedClient(env).me();
|
|
875
|
+
const lines = [
|
|
876
|
+
`Account: ${me.account.email}${me.account.name ? ` (${me.account.name})` : ""}`,
|
|
877
|
+
`Token: ${me.token.name}, expires ${me.token.expires_at}${found.ok && found.source === "env" ? " (from EVOPOS_TOKEN)" : ""}`,
|
|
878
|
+
`Sandbox: ${me.sandbox ? `${me.sandbox.company_slug}: ${me.sandbox.kassa_url}` : "none"}`,
|
|
879
|
+
`API: ${env.base}`
|
|
880
|
+
];
|
|
881
|
+
env.out.result(lines.join("\n"), { ...me, api: env.base });
|
|
882
|
+
return 0;
|
|
883
|
+
}
|
|
884
|
+
function validate(env) {
|
|
885
|
+
const dir = dirArg(env);
|
|
886
|
+
const p = inspectPackage(dir);
|
|
887
|
+
const m = p.manifest;
|
|
888
|
+
env.out.result(`${env.out.success("OK")} ${m.id}@${m.version}: ${p.files.length} files (package root: ${relative2(env.ctx.cwd, p.root) || "."})`, {
|
|
889
|
+
ok: true,
|
|
890
|
+
id: m.id,
|
|
891
|
+
version: m.version,
|
|
892
|
+
root: p.root,
|
|
893
|
+
files: p.files.map((f) => f.name)
|
|
894
|
+
});
|
|
895
|
+
return 0;
|
|
896
|
+
}
|
|
897
|
+
function pack(env) {
|
|
898
|
+
const dir = dirArg(env);
|
|
899
|
+
const out = str(env.args.values.out);
|
|
900
|
+
const res = packPlugin({ dir, ...out ? { out: resolve2(env.ctx.cwd, out) } : {} });
|
|
901
|
+
env.out.result(
|
|
902
|
+
[`${res.manifest.id}@${res.manifest.version}`, `File: ${res.file}`, `Size: ${res.bytes} bytes`, `Files: ${res.files.length}`, `sha256: ${res.sha256}`].join("\n"),
|
|
903
|
+
{ id: res.manifest.id, version: res.manifest.version, file: res.file, bytes: res.bytes, files: res.files.length, sha256: res.sha256 }
|
|
904
|
+
);
|
|
905
|
+
return 0;
|
|
906
|
+
}
|
|
907
|
+
function hasBuildScript(dir) {
|
|
908
|
+
try {
|
|
909
|
+
const pkg = JSON.parse(readFileSync3(join3(dir, "package.json"), "utf8"));
|
|
910
|
+
return typeof pkg.scripts?.build === "string";
|
|
911
|
+
} catch {
|
|
912
|
+
return false;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
async function deploy(env) {
|
|
916
|
+
const { ctx, out, args } = env;
|
|
917
|
+
const dir = dirArg(env);
|
|
918
|
+
const client = authedClient(env);
|
|
919
|
+
if (!flag(args.values["no-build"]) && hasBuildScript(dir)) {
|
|
920
|
+
out.say("Running `npm run build`...");
|
|
921
|
+
if (await ctx.runBuild(dir, out.json) !== 0) throw new CliError("build_failed", "`npm run build` failed.");
|
|
922
|
+
}
|
|
923
|
+
const packed = packPlugin({ dir });
|
|
924
|
+
out.say(`Packed ${packed.manifest.id}@${packed.manifest.version}: ${packed.bytes} bytes, ${packed.files.length} files.`);
|
|
925
|
+
const uploaded = await client.uploadPackage(readFileSync3(packed.file), basename(packed.file));
|
|
926
|
+
const line = `Uploaded ${uploaded.plugin_id}@${uploaded.version} (${uploaded.status}) -> sandbox ${uploaded.sandbox.company_slug}: ${uploaded.sandbox.kassa_url}`;
|
|
927
|
+
const info = { file: packed.file, bytes: packed.bytes, files: packed.files.length, sha256: packed.sha256 };
|
|
928
|
+
if (!flag(args.values.submit)) {
|
|
929
|
+
out.result(line, { ...uploaded, package: info, submitted: false });
|
|
930
|
+
return 0;
|
|
931
|
+
}
|
|
932
|
+
out.say(line);
|
|
933
|
+
const submitted = await client.submit(uploaded.plugin_id, uploaded.version);
|
|
934
|
+
out.result(`Submitted ${submitted.plugin_id}@${submitted.version} for review (${submitted.status}).`, {
|
|
935
|
+
...uploaded,
|
|
936
|
+
status: submitted.status,
|
|
937
|
+
package: info,
|
|
938
|
+
submitted: true
|
|
939
|
+
});
|
|
940
|
+
return 0;
|
|
941
|
+
}
|
|
942
|
+
async function submit(env) {
|
|
943
|
+
const { out, args } = env;
|
|
944
|
+
const dir = dirArg(env);
|
|
945
|
+
const client = authedClient(env);
|
|
946
|
+
let id = str(args.values.id);
|
|
947
|
+
let version = str(args.values.version);
|
|
948
|
+
if (!id || !version) {
|
|
949
|
+
const pkg = resolvePackageDir(dir);
|
|
950
|
+
let m;
|
|
951
|
+
try {
|
|
952
|
+
m = JSON.parse(readFileSync3(join3(pkg.root, "manifest.json"), "utf8"));
|
|
953
|
+
} catch (e) {
|
|
954
|
+
throw new CliError("manifest_json", `manifest.json is not valid JSON: ${e.message}`);
|
|
955
|
+
}
|
|
956
|
+
if (!id && typeof m.id === "string") id = m.id;
|
|
957
|
+
if (!version && typeof m.version === "string") version = m.version;
|
|
958
|
+
}
|
|
959
|
+
if (!id || !version) throw new UsageError("Cannot determine the plugin id and version: pass --id and --version.");
|
|
960
|
+
const res = await client.submit(id, version);
|
|
961
|
+
out.result(`Submitted ${res.plugin_id}@${res.version} for review (${res.status}).`, res);
|
|
962
|
+
return 0;
|
|
963
|
+
}
|
|
964
|
+
async function open(env) {
|
|
965
|
+
const { ctx, out, args } = env;
|
|
966
|
+
noPositionals(env);
|
|
967
|
+
const me = await authedClient(env).me();
|
|
968
|
+
if (!me.sandbox) {
|
|
969
|
+
throw new CliError("sandbox_unavailable", "You have no sandbox yet.", {
|
|
970
|
+
hint: `Create a sandbox in ${env.base}/console and try again.`
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
const url = me.sandbox.kassa_url;
|
|
974
|
+
const print = flag(args.values.print);
|
|
975
|
+
if (!print && ctx.interactive && ctx.openUrl(url)) out.say(`Opening ${url}`);
|
|
976
|
+
out.result(url, { url, company_slug: me.sandbox.company_slug });
|
|
977
|
+
return 0;
|
|
978
|
+
}
|
|
979
|
+
function sameOriginAs(rawUrl, origin) {
|
|
980
|
+
try {
|
|
981
|
+
return new URL(rawUrl).origin === origin;
|
|
982
|
+
} catch {
|
|
983
|
+
return false;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// src/cli/output.ts
|
|
988
|
+
var esc = (code) => (s) => `\x1B[${code}m${s}\x1B[0m`;
|
|
989
|
+
var Output = class {
|
|
990
|
+
constructor(ctx, json) {
|
|
991
|
+
this.ctx = ctx;
|
|
992
|
+
this.json = json;
|
|
993
|
+
}
|
|
994
|
+
ctx;
|
|
995
|
+
json;
|
|
996
|
+
paint(fn, s) {
|
|
997
|
+
return this.ctx.color ? fn(s) : s;
|
|
998
|
+
}
|
|
999
|
+
/** Ход работы. */
|
|
1000
|
+
say(text) {
|
|
1001
|
+
(this.json ? this.ctx.stderr : this.ctx.stdout).write(text + "\n");
|
|
1002
|
+
}
|
|
1003
|
+
warn(text) {
|
|
1004
|
+
this.ctx.stderr.write(`${this.paint(esc(33), "warning:")} ${text}
|
|
1005
|
+
`);
|
|
1006
|
+
}
|
|
1007
|
+
success(text) {
|
|
1008
|
+
return this.paint(esc(32), text);
|
|
1009
|
+
}
|
|
1010
|
+
bold(text) {
|
|
1011
|
+
return this.paint(esc(1), text);
|
|
1012
|
+
}
|
|
1013
|
+
/** Итог команды: текст для человека или JSON. */
|
|
1014
|
+
result(text, data) {
|
|
1015
|
+
this.ctx.stdout.write(this.json ? JSON.stringify(data) + "\n" : text + "\n");
|
|
1016
|
+
}
|
|
1017
|
+
fail(d) {
|
|
1018
|
+
if (this.json) {
|
|
1019
|
+
const body = { error: d.code, message: d.message };
|
|
1020
|
+
if (d.errors.length > 0) body.errors = d.errors;
|
|
1021
|
+
if (d.hint) body.hint = d.hint;
|
|
1022
|
+
this.ctx.stdout.write(JSON.stringify(body) + "\n");
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
const lines = [`${this.paint(esc(31), "error:")} ${d.message}`];
|
|
1026
|
+
for (const line of d.errors) lines.push(` - ${line}`);
|
|
1027
|
+
if (d.hint) lines.push(d.hint);
|
|
1028
|
+
this.ctx.stderr.write(lines.join("\n") + "\n");
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
1031
|
+
|
|
1032
|
+
// src/cli/main.ts
|
|
1033
|
+
var COMMON = {
|
|
1034
|
+
api: { type: "string" },
|
|
1035
|
+
json: { type: "boolean" },
|
|
1036
|
+
help: { type: "boolean", short: "h" },
|
|
1037
|
+
version: { type: "boolean", short: "v" }
|
|
1038
|
+
};
|
|
1039
|
+
var COMMANDS = {
|
|
1040
|
+
login: {
|
|
1041
|
+
usage: "evopos login [--no-browser] [--with-token | --token <token>]",
|
|
1042
|
+
summary: "Sign in with a one-time code approved in the browser",
|
|
1043
|
+
options: { "no-browser": { type: "boolean" }, "with-token": { type: "boolean" }, token: { type: "string" } },
|
|
1044
|
+
run: login,
|
|
1045
|
+
details: " --no-browser Do not open the browser, only print the address\n --with-token Read an existing token from stdin (CI)\n --token <token> Use this token (it stays in shell history: prefer --with-token)"
|
|
1046
|
+
},
|
|
1047
|
+
logout: { usage: "evopos logout", summary: "Revoke the saved token and forget it", run: logout },
|
|
1048
|
+
whoami: { usage: "evopos whoami", summary: "Show the account, token and sandbox", run: whoami },
|
|
1049
|
+
validate: { usage: "evopos validate [dir]", summary: "Check manifest.json and the package files", run: validate },
|
|
1050
|
+
pack: {
|
|
1051
|
+
usage: "evopos pack [dir] [--out <file>]",
|
|
1052
|
+
summary: "Build the plugin .zip",
|
|
1053
|
+
options: { out: { type: "string" } },
|
|
1054
|
+
run: pack,
|
|
1055
|
+
details: " --out <file> Where to write the archive (default: .evopos/<id>-<version>.zip)"
|
|
1056
|
+
},
|
|
1057
|
+
deploy: {
|
|
1058
|
+
usage: "evopos deploy [dir] [--submit] [--no-build]",
|
|
1059
|
+
summary: "Build, check, pack and upload to your sandbox",
|
|
1060
|
+
options: { submit: { type: "boolean" }, "no-build": { type: "boolean" } },
|
|
1061
|
+
run: deploy,
|
|
1062
|
+
details: " --submit Send the uploaded version for review right away\n --no-build Skip `npm run build` even if package.json has it"
|
|
1063
|
+
},
|
|
1064
|
+
submit: {
|
|
1065
|
+
usage: "evopos submit [dir] [--id <id>] [--version <version>]",
|
|
1066
|
+
summary: "Send a draft version for review",
|
|
1067
|
+
options: { id: { type: "string" }, version: { type: "string" } },
|
|
1068
|
+
ownVersion: true,
|
|
1069
|
+
run: submit,
|
|
1070
|
+
details: " --id, --version Default to the values from manifest.json"
|
|
1071
|
+
},
|
|
1072
|
+
open: {
|
|
1073
|
+
usage: "evopos open [--print]",
|
|
1074
|
+
summary: "Open your sandbox kassa in the browser",
|
|
1075
|
+
options: { print: { type: "boolean" } },
|
|
1076
|
+
run: open,
|
|
1077
|
+
details: " --print Only print the address"
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
var GLOBAL_HELP = ` --api <url> API address (default: $EVOPOS_API_BASE or https://developers.evopos.az)
|
|
1081
|
+
--json Machine-readable output: one JSON object on stdout
|
|
1082
|
+
-h, --help Show help
|
|
1083
|
+
-v, --version Show the version`;
|
|
1084
|
+
function helpText(command) {
|
|
1085
|
+
const spec = command ? COMMANDS[command] : void 0;
|
|
1086
|
+
if (spec) {
|
|
1087
|
+
return [`${spec.usage}`, "", spec.summary, "", "Options:", ...spec.details ? [spec.details] : [], GLOBAL_HELP.replace(" -v, --version Show the version\n", "")].join("\n") + "\n";
|
|
1088
|
+
}
|
|
1089
|
+
const rows = Object.entries(COMMANDS).map(([name, s]) => ` ${name.padEnd(10)}${s.summary}`);
|
|
1090
|
+
return [
|
|
1091
|
+
`evopos ${VERSION}: EvoPOS plugin developer CLI`,
|
|
1092
|
+
"",
|
|
1093
|
+
"Usage: evopos <command> [options]",
|
|
1094
|
+
"",
|
|
1095
|
+
"Commands:",
|
|
1096
|
+
...rows,
|
|
1097
|
+
"",
|
|
1098
|
+
"Options:",
|
|
1099
|
+
GLOBAL_HELP,
|
|
1100
|
+
"",
|
|
1101
|
+
"Environment: EVOPOS_TOKEN, EVOPOS_API_BASE, EVOPOS_CONFIG_DIR",
|
|
1102
|
+
"Exit codes: 0 success, 1 error, 2 usage error",
|
|
1103
|
+
""
|
|
1104
|
+
].join("\n");
|
|
1105
|
+
}
|
|
1106
|
+
async function main(argv, ctx = defaultContext()) {
|
|
1107
|
+
const first = argv[0];
|
|
1108
|
+
const wantsJson = argv.includes("--json");
|
|
1109
|
+
if (first === void 0 || first === "-h" || first === "--help" || first === "help") {
|
|
1110
|
+
ctx.stdout.write(helpText(first === "help" ? argv[1] : void 0));
|
|
1111
|
+
return 0;
|
|
1112
|
+
}
|
|
1113
|
+
if (first === "-v" || first === "--version") {
|
|
1114
|
+
ctx.stdout.write(VERSION + "\n");
|
|
1115
|
+
return 0;
|
|
1116
|
+
}
|
|
1117
|
+
let out = new Output(ctx, wantsJson);
|
|
1118
|
+
let base = "https://developers.evopos.az";
|
|
1119
|
+
try {
|
|
1120
|
+
const spec = Object.hasOwn(COMMANDS, first) ? COMMANDS[first] : void 0;
|
|
1121
|
+
if (!spec) throw new UsageError(`Unknown command: ${first}. Run \`evopos --help\`.`);
|
|
1122
|
+
const common = { ...COMMON };
|
|
1123
|
+
if (spec.ownVersion) delete common.version;
|
|
1124
|
+
let parsed;
|
|
1125
|
+
try {
|
|
1126
|
+
parsed = parseArgs({
|
|
1127
|
+
args: argv.slice(1),
|
|
1128
|
+
options: { ...common, ...spec.options },
|
|
1129
|
+
allowPositionals: true,
|
|
1130
|
+
strict: true
|
|
1131
|
+
});
|
|
1132
|
+
} catch (e) {
|
|
1133
|
+
throw new UsageError(e.message.split(". To specify")[0] ?? "Invalid arguments.");
|
|
1134
|
+
}
|
|
1135
|
+
const values = parsed.values;
|
|
1136
|
+
out = new Output(ctx, values.json === true);
|
|
1137
|
+
if (values.help === true) {
|
|
1138
|
+
ctx.stdout.write(helpText(first));
|
|
1139
|
+
return 0;
|
|
1140
|
+
}
|
|
1141
|
+
if (values.version === true) {
|
|
1142
|
+
ctx.stdout.write(VERSION + "\n");
|
|
1143
|
+
return 0;
|
|
1144
|
+
}
|
|
1145
|
+
const resolved = resolveApiBase(typeof values.api === "string" ? values.api : void 0, ctx.env);
|
|
1146
|
+
base = resolved.base;
|
|
1147
|
+
return await spec.run({ ctx, out, base: resolved.base, origin: resolved.origin, args: { values, positionals: parsed.positionals } });
|
|
1148
|
+
} catch (e) {
|
|
1149
|
+
const d = describeError(e, base);
|
|
1150
|
+
out.fail(d);
|
|
1151
|
+
return d.exitCode;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
export {
|
|
1156
|
+
DEFAULT_API_BASE,
|
|
1157
|
+
ApiBaseError,
|
|
1158
|
+
normalizeApiBase,
|
|
1159
|
+
resolveApiBase,
|
|
1160
|
+
VERSION,
|
|
1161
|
+
userAgent,
|
|
1162
|
+
TOKEN_PATTERN,
|
|
1163
|
+
isValidToken,
|
|
1164
|
+
configDir,
|
|
1165
|
+
credentialsPath,
|
|
1166
|
+
parseExpiry,
|
|
1167
|
+
normalizeExpiry,
|
|
1168
|
+
readCredentials,
|
|
1169
|
+
saveToken,
|
|
1170
|
+
removeToken,
|
|
1171
|
+
lookupToken,
|
|
1172
|
+
EvoposApiError,
|
|
1173
|
+
EvoposClient,
|
|
1174
|
+
createClient,
|
|
1175
|
+
runDeviceFlow,
|
|
1176
|
+
crc32,
|
|
1177
|
+
makeZip,
|
|
1178
|
+
MAX_ZIP_BYTES,
|
|
1179
|
+
MAX_FILES,
|
|
1180
|
+
MAX_TOTAL_BYTES,
|
|
1181
|
+
MAX_NAME_LENGTH,
|
|
1182
|
+
ALLOWED_EXTENSIONS,
|
|
1183
|
+
PackageError,
|
|
1184
|
+
resolvePackageDir,
|
|
1185
|
+
nameProblem,
|
|
1186
|
+
checkEntries,
|
|
1187
|
+
inspectPackage,
|
|
1188
|
+
validateManifestFile,
|
|
1189
|
+
defaultOutPath,
|
|
1190
|
+
packPlugin,
|
|
1191
|
+
browserCommand,
|
|
1192
|
+
openInBrowser,
|
|
1193
|
+
defaultContext,
|
|
1194
|
+
main
|
|
1195
|
+
};
|
|
1196
|
+
//# sourceMappingURL=chunk-ZQ6F743F.js.map
|