@evopos/vite-plugin 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/dist/index.js ADDED
@@ -0,0 +1,602 @@
1
+ // src/index.ts
2
+ import { existsSync as existsSync3 } from "fs";
3
+ import { resolve as resolve2, sep } from "path";
4
+ import { version as viteVersion } from "vite";
5
+
6
+ // src/cors.ts
7
+ var DEV_CORS_ORIGINS = [
8
+ "null",
9
+ /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|[a-z0-9-]+\.localhost)(:\d+)?$/i
10
+ ];
11
+ function devCors() {
12
+ return { origin: [...DEV_CORS_ORIGINS] };
13
+ }
14
+ function privateNetworkMiddleware(req, res, next) {
15
+ if (req.method === "OPTIONS" && req.headers["access-control-request-private-network"] === "true") {
16
+ res.setHeader("Access-Control-Allow-Private-Network", "true");
17
+ }
18
+ next();
19
+ }
20
+
21
+ // src/dev-session.ts
22
+ import { EvoposApiError, createClient, lookupToken, resolveApiBase } from "@evopos/cli";
23
+ function resolveSessionClient(options) {
24
+ const env = options.env ?? process.env;
25
+ let resolved;
26
+ try {
27
+ resolved = resolveApiBase(options.api, env);
28
+ } catch (e) {
29
+ options.logger.warn(`Sandbox dev mode is off: ${e.message}`);
30
+ return null;
31
+ }
32
+ const lookup = lookupToken(resolved.origin, {
33
+ env,
34
+ ...options.now ? { now: options.now } : {},
35
+ warn: (m) => options.logger.warn(m)
36
+ });
37
+ if (!lookup.ok) {
38
+ options.logger.info(`Sandbox dev mode is off: ${lookup.message}`);
39
+ return null;
40
+ }
41
+ const input = { base: resolved.base, token: lookup.token, tokenSource: lookup.source };
42
+ if (options.createClient) return options.createClient(input);
43
+ return createClient({ base: input.base, token: input.token, tokenSource: input.tokenSource });
44
+ }
45
+ var MIN_PULSE_MS = 1e4;
46
+ var MAX_PULSE_MS = 5 * 6e4;
47
+ function pulseInterval(ttlSeconds) {
48
+ const ttl = typeof ttlSeconds === "number" && Number.isFinite(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds * 1e3 : 15 * 6e4;
49
+ return Math.min(MAX_PULSE_MS, Math.max(MIN_PULSE_MS, Math.floor(ttl / 3)));
50
+ }
51
+ function describe(e) {
52
+ if (e instanceof EvoposApiError) {
53
+ const detail = e.errors.length > 0 ? ` ${e.errors.join("; ")}` : "";
54
+ return `${e.message}${detail}${e.hint ? ` ${e.hint}` : ""}`;
55
+ }
56
+ return e instanceof Error ? e.message : String(e);
57
+ }
58
+ var DevSessionController = class {
59
+ constructor(client, logger) {
60
+ this.client = client;
61
+ this.logger = logger;
62
+ }
63
+ client;
64
+ logger;
65
+ manifest = null;
66
+ manifestKey = "";
67
+ url = "";
68
+ timer = null;
69
+ queue = Promise.resolve();
70
+ active = false;
71
+ announced = false;
72
+ /** Сервер отказал насовсем (нет прав, токен отозван): пульс бессмысленен. */
73
+ halted = false;
74
+ get running() {
75
+ return this.active;
76
+ }
77
+ enqueue(task) {
78
+ const next = this.queue.then(task, task);
79
+ this.queue = next.catch(() => void 0);
80
+ return next;
81
+ }
82
+ /** Зарегистрировать сессию и запустить пульс. */
83
+ start(manifest, url) {
84
+ this.active = true;
85
+ this.halted = false;
86
+ this.url = url;
87
+ this.manifest = manifest;
88
+ this.manifestKey = JSON.stringify(manifest);
89
+ return this.enqueue(() => this.push(true));
90
+ }
91
+ /** Манифест исправлен: повторить PUT, если он изменился. */
92
+ update(manifest) {
93
+ if (!this.active) return Promise.resolve();
94
+ const key = JSON.stringify(manifest);
95
+ if (key === this.manifestKey && !this.halted) return Promise.resolve();
96
+ this.manifest = manifest;
97
+ this.manifestKey = key;
98
+ this.halted = false;
99
+ return this.enqueue(() => this.push(false));
100
+ }
101
+ schedule(ms) {
102
+ if (this.timer) clearInterval(this.timer);
103
+ this.timer = setInterval(() => {
104
+ if (!this.active || this.halted) return;
105
+ void this.enqueue(() => this.push(false, true));
106
+ }, ms);
107
+ this.timer.unref?.();
108
+ }
109
+ async push(first, pulse = false) {
110
+ if (!this.active || !this.manifest) return;
111
+ try {
112
+ const res = await this.client.putDevSession(this.manifest, this.url);
113
+ this.schedule(pulseInterval(res.ttl));
114
+ if (first || !this.announced) {
115
+ this.announced = true;
116
+ this.logger.info(
117
+ `Sandbox dev session is on: ${res.plugin_id} \u2190 ${this.url}
118
+ Open the sandbox kassa: ${res.sandbox.kassa_url} (venue ${res.sandbox.company_slug})`
119
+ );
120
+ } else if (!pulse) {
121
+ this.logger.info(`Sandbox dev session updated (${res.plugin_id}).`);
122
+ }
123
+ } catch (e) {
124
+ if (e instanceof EvoposApiError) {
125
+ if (e.status === 401 || e.status === 403) {
126
+ this.halted = true;
127
+ this.logger.error(`Sandbox dev session was refused: ${describe(e)}`);
128
+ return;
129
+ }
130
+ if (e.status === 0) {
131
+ this.logger.warn(`Sandbox dev session: ${describe(e)} Will retry.`);
132
+ if (!this.timer) this.schedule(pulseInterval(void 0));
133
+ return;
134
+ }
135
+ this.logger.error(`Sandbox dev session was not accepted: ${describe(e)}`);
136
+ if (!this.timer) this.schedule(pulseInterval(void 0));
137
+ return;
138
+ }
139
+ this.logger.warn(`Sandbox dev session failed: ${describe(e)}`);
140
+ }
141
+ }
142
+ /** Снять сессию и остановить пульс. Повторный вызов ничего не делает. */
143
+ stop() {
144
+ if (!this.active) return this.queue;
145
+ this.active = false;
146
+ if (this.timer) {
147
+ clearInterval(this.timer);
148
+ this.timer = null;
149
+ }
150
+ const id = typeof this.manifest?.id === "string" ? this.manifest.id : void 0;
151
+ return this.enqueue(async () => {
152
+ try {
153
+ await this.client.deleteDevSession(id);
154
+ this.logger.info("Sandbox dev session removed.");
155
+ } catch (e) {
156
+ this.logger.warn(`Could not remove the sandbox dev session (it expires on its own in 15 minutes): ${describe(e)}`);
157
+ }
158
+ });
159
+ }
160
+ };
161
+
162
+ // src/entries.ts
163
+ import { readdirSync, realpathSync } from "fs";
164
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "path";
165
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist"]);
166
+ function walk(dir, root, out) {
167
+ let entries;
168
+ try {
169
+ entries = readdirSync(dir, { withFileTypes: true });
170
+ } catch {
171
+ return;
172
+ }
173
+ for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
174
+ if (entry.name.startsWith(".")) continue;
175
+ const full = join(dir, entry.name);
176
+ if (entry.isDirectory()) {
177
+ if (!SKIP_DIRS.has(entry.name)) walk(full, root, out);
178
+ } else if (entry.isFile() && /\.html$/i.test(entry.name)) {
179
+ out.push(toPosix(relative(root, full)));
180
+ }
181
+ }
182
+ }
183
+ function toPosix(path) {
184
+ return path.split("\\").join("/");
185
+ }
186
+ function findEntries(root, pagesDir = "pages") {
187
+ const found = [];
188
+ let top;
189
+ try {
190
+ top = readdirSync(root, { withFileTypes: true });
191
+ } catch {
192
+ top = [];
193
+ }
194
+ for (const entry of top) {
195
+ if (entry.isFile() && !entry.name.startsWith(".") && /\.html$/i.test(entry.name)) found.push(entry.name);
196
+ }
197
+ if (pagesDir !== "" && pagesDir !== ".") {
198
+ const pages = [];
199
+ walk(resolve(root, pagesDir), root, pages);
200
+ found.push(...pages);
201
+ }
202
+ return [...new Set(found)].sort();
203
+ }
204
+ function real(path) {
205
+ try {
206
+ return realpathSync(path);
207
+ } catch {
208
+ const parent = dirname(path);
209
+ return parent === path ? path : join(real(parent), basename(path));
210
+ }
211
+ }
212
+ function inputToEntries(input, root) {
213
+ const list = [];
214
+ if (typeof input === "string") list.push(input);
215
+ else if (Array.isArray(input)) list.push(...input.filter((x) => typeof x === "string"));
216
+ else if (typeof input === "object" && input !== null) {
217
+ list.push(...Object.values(input).filter((x) => typeof x === "string"));
218
+ }
219
+ const base = real(root);
220
+ return list.filter((p) => /\.html$/i.test(p)).map((p) => toPosix(relative(base, real(isAbsolute(p) ? p : resolve(root, p))))).sort();
221
+ }
222
+ function normalizeEntry(entry) {
223
+ return entry.replace(/^(\.\/)+/, "");
224
+ }
225
+
226
+ // src/fake-kassa.ts
227
+ import { existsSync, readFileSync } from "fs";
228
+ import { fileURLToPath } from "url";
229
+ var FAKE_KASSA_PATH = "/__evopos/";
230
+ var FAKE_KASSA_CLIENT_PATH = "/__evopos/client.js";
231
+ function findClientFile(base = import.meta.url) {
232
+ for (const rel of ["./client/main.js", "../dist/client/main.js"]) {
233
+ const file = fileURLToPath(new URL(rel, base));
234
+ if (existsSync(file)) return file;
235
+ }
236
+ return null;
237
+ }
238
+ function renderFakeKassaPage(config) {
239
+ const json = JSON.stringify(config).replace(/</g, "\\u003c");
240
+ return `<!doctype html>
241
+ <html lang="en">
242
+ <head>
243
+ <meta charset="utf-8">
244
+ <meta name="viewport" content="width=device-width, initial-scale=1">
245
+ <title>EvoPOS fake kassa</title>
246
+ <link rel="icon" href="data:,">
247
+ </head>
248
+ <body>
249
+ <div id="app"></div>
250
+ <script type="application/json" id="evopos-config">${json}</script>
251
+ <script type="module" src="/@vite/client"></script>
252
+ <script type="module" src="${FAKE_KASSA_CLIENT_PATH}"></script>
253
+ </body>
254
+ </html>
255
+ `;
256
+ }
257
+ function fakeKassaMiddleware(options) {
258
+ return function fakeKassa(req, res, next) {
259
+ const url = (req.url ?? "").split("?")[0] ?? "";
260
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
261
+ if (url === "/__evopos") {
262
+ res.statusCode = 302;
263
+ res.setHeader("Location", FAKE_KASSA_PATH);
264
+ res.end();
265
+ return;
266
+ }
267
+ if (url === FAKE_KASSA_PATH) {
268
+ res.statusCode = 200;
269
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
270
+ res.setHeader("Cache-Control", "no-cache");
271
+ res.end(req.method === "HEAD" ? void 0 : renderFakeKassaPage({ manifestUrl: options.manifestUrl }));
272
+ return;
273
+ }
274
+ if (url === FAKE_KASSA_CLIENT_PATH) {
275
+ if (!options.clientFile) {
276
+ res.statusCode = 500;
277
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
278
+ res.end("@evopos/vite-plugin: the fake kassa client is not built (dist/client/main.js is missing). Reinstall the package.");
279
+ return;
280
+ }
281
+ let client;
282
+ try {
283
+ client = readFileSync(options.clientFile, "utf8");
284
+ } catch {
285
+ return next();
286
+ }
287
+ res.statusCode = 200;
288
+ res.setHeader("Content-Type", "text/javascript; charset=utf-8");
289
+ res.setHeader("Cache-Control", "no-cache");
290
+ res.end(req.method === "HEAD" ? void 0 : client);
291
+ return;
292
+ }
293
+ next();
294
+ };
295
+ }
296
+
297
+ // src/manifest.ts
298
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
299
+ import { validateDriverManifest, validatePluginManifest } from "@evopos/contracts";
300
+ function pageList(entries) {
301
+ if (entries.length === 0) return "No HTML pages found: put them in the project root or in pages/.";
302
+ const shown = entries.slice(0, 10).join(", ");
303
+ return `Pages of this project: ${shown}${entries.length > 10 ? ", \u2026" : ""}.`;
304
+ }
305
+ function checkManifest(options) {
306
+ const { file, label, entries } = options;
307
+ if (!existsSync2(file)) {
308
+ return {
309
+ ok: false,
310
+ raw: null,
311
+ errors: [`${label} not found (${file}). Create it next to index.html, or point the \`manifest\` option of evopos() to it.`]
312
+ };
313
+ }
314
+ const raw = readFileSync2(file, "utf8");
315
+ let json;
316
+ try {
317
+ json = JSON.parse(raw);
318
+ } catch (e) {
319
+ return { ok: false, raw, errors: [`${label} is not valid JSON: ${e.message}`] };
320
+ }
321
+ const isDriver = typeof json === "object" && json !== null && json.kind === "driver";
322
+ const result = isDriver ? validateDriverManifest(json) : validatePluginManifest(json);
323
+ if (!result.ok) return { ok: false, raw, errors: result.errors.map((e) => `${label}: ${e}`) };
324
+ const errors = [];
325
+ const manifest = result.manifest;
326
+ if (isDriver) {
327
+ const entry = manifest.entry;
328
+ const exists = options.fileExists ?? (() => true);
329
+ if (typeof entry === "string" && !exists(normalizeEntry(entry))) {
330
+ errors.push(`${label}: /entry: driver file ${entry} not found in public/ (it is copied to the build as is).`);
331
+ }
332
+ } else {
333
+ const known = new Set(entries.map(normalizeEntry));
334
+ (manifest.slots ?? []).forEach((slot, i) => {
335
+ if (typeof slot.entry === "string" && !known.has(normalizeEntry(slot.entry))) {
336
+ errors.push(`${label}: /slots/${i}/entry: page "${slot.entry}" is not among the build inputs. ${pageList(entries)}`);
337
+ }
338
+ });
339
+ }
340
+ if (errors.length > 0) return { ok: false, raw, errors };
341
+ return { ok: true, raw, manifest };
342
+ }
343
+ function formatErrors(errors) {
344
+ return [`EvoPOS manifest is invalid (${errors.length} problem${errors.length === 1 ? "" : "s"}):`, ...errors.map((e) => ` - ${e}`)].join("\n");
345
+ }
346
+
347
+ // src/index.ts
348
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
349
+ var RECHECK_DELAY_MS = 120;
350
+ function viteMajor() {
351
+ return Number.parseInt(String(viteVersion).split(".")[0] ?? "0", 10) || 0;
352
+ }
353
+ function colorEnabled(env = process.env) {
354
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
355
+ const force = env.FORCE_COLOR;
356
+ if (force !== void 0) return force !== "0" && force !== "false";
357
+ return process.stdout.isTTY === true && env.TERM !== "dumb";
358
+ }
359
+ var timeFormatter;
360
+ function formatLogLine(kind, message, colors = colorEnabled(), now = /* @__PURE__ */ new Date()) {
361
+ timeFormatter ??= new Intl.DateTimeFormat(void 0, { hour: "numeric", minute: "numeric", second: "numeric" });
362
+ const time = timeFormatter.format(now);
363
+ const tag = "[evopos]";
364
+ if (!colors) return `${time} ${tag} ${message}`;
365
+ const code = kind === "info" ? 36 : kind === "warn" ? 33 : 31;
366
+ return `\x1B[2m${time}\x1B[22m \x1B[${code}m\x1B[1m${tag}\x1B[22m\x1B[39m ${message}`;
367
+ }
368
+ function serverLogger(server) {
369
+ const logger = server.config.logger;
370
+ return {
371
+ info: (m) => logger.info(formatLogLine("info", m)),
372
+ warn: (m) => logger.warn(formatLogLine("warn", m)),
373
+ error: (m) => logger.error(formatLogLine("error", m))
374
+ };
375
+ }
376
+ function evopos(options = {}) {
377
+ const manifestName = options.manifest ?? "manifest.json";
378
+ const pagesDir = options.pagesDir ?? "pages";
379
+ const env = options.env ?? process.env;
380
+ let config;
381
+ let root = process.cwd();
382
+ let customInput = null;
383
+ const manifestFile = () => resolve2(root, manifestName);
384
+ const currentEntries = () => customInput ?? findEntries(root, pagesDir);
385
+ function read() {
386
+ return checkManifest({
387
+ file: manifestFile(),
388
+ label: manifestName,
389
+ entries: currentEntries(),
390
+ fileExists: (rel) => config?.publicDir ? existsSync3(resolve2(config.publicDir, rel)) : false
391
+ });
392
+ }
393
+ const listeners = [];
394
+ let state = null;
395
+ const core = {
396
+ name: "evopos",
397
+ config(userConfig) {
398
+ const rootDir = resolve2(userConfig.root ?? process.cwd());
399
+ const out = {};
400
+ if (userConfig.base === void 0) out.base = "./";
401
+ const buildOptions = userConfig.build;
402
+ const hasInput = buildOptions?.rolldownOptions?.input ?? buildOptions?.rollupOptions?.input;
403
+ if (hasInput === void 0) {
404
+ const found = findEntries(rootDir, pagesDir);
405
+ if (found.length > 0) {
406
+ const input = Object.fromEntries(found.map((f) => [f.replace(/\.html$/i, ""), resolve2(rootDir, f)]));
407
+ const key = viteMajor() >= 8 ? "rolldownOptions" : "rollupOptions";
408
+ out.build = { [key]: { input } };
409
+ }
410
+ }
411
+ if (userConfig.server?.cors === void 0) out.server = { cors: devCors() };
412
+ return out;
413
+ },
414
+ configResolved(resolved) {
415
+ config = resolved;
416
+ root = resolved.root;
417
+ const build = resolved.build;
418
+ const input = build.rolldownOptions?.input ?? build.rollupOptions?.input;
419
+ const fromInput = input === void 0 ? [] : inputToEntries(input, root);
420
+ const own = findEntries(root, pagesDir);
421
+ customInput = fromInput.length > 0 && JSON.stringify(fromInput) !== JSON.stringify(own) ? fromInput : null;
422
+ },
423
+ buildStart() {
424
+ if (config.command !== "build") return;
425
+ const result = read();
426
+ if (!result.ok) {
427
+ config.logger.error(formatErrors(result.errors));
428
+ this.error(formatErrors(result.errors));
429
+ }
430
+ },
431
+ generateBundle() {
432
+ if (config.command !== "build") return;
433
+ const result = read();
434
+ if (!result.ok) return;
435
+ if (config.publicDir && existsSync3(resolve2(config.publicDir, "manifest.json"))) return;
436
+ this.emitFile({ type: "asset", fileName: "manifest.json", source: result.raw });
437
+ },
438
+ configureServer(server) {
439
+ const logger = serverLogger(server);
440
+ server.middlewares.stack.unshift({ route: "", handle: privateNetworkMiddleware });
441
+ state = read();
442
+ let lastLogged = state.ok ? "" : state.errors.join("\n");
443
+ if (!state.ok) logger.error(formatErrors(state.errors));
444
+ server.middlewares.use("/manifest.json", (req, res, next) => {
445
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
446
+ if ((req.url ?? "").includes("?") || req.headers["sec-fetch-dest"] === "script") return next();
447
+ const current = read();
448
+ if (current.ok) {
449
+ res.statusCode = 200;
450
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
451
+ res.setHeader("Cache-Control", "no-cache");
452
+ res.end(req.method === "HEAD" ? void 0 : current.raw);
453
+ return;
454
+ }
455
+ res.statusCode = 422;
456
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
457
+ res.end(req.method === "HEAD" ? void 0 : JSON.stringify({ ok: false, errors: current.errors }));
458
+ });
459
+ const sendOverlay = (errors) => {
460
+ server.ws.send({ type: "error", err: { message: formatErrors(errors), stack: "", plugin: "evopos" } });
461
+ };
462
+ server.ws.on("connection", () => {
463
+ if (state && !state.ok) sendOverlay(state.errors);
464
+ });
465
+ let timer = null;
466
+ const recheck = () => {
467
+ const before = state;
468
+ const next = read();
469
+ state = next;
470
+ if (!next.ok) {
471
+ const text = next.errors.join("\n");
472
+ if (text !== lastLogged) {
473
+ lastLogged = text;
474
+ logger.error(formatErrors(next.errors));
475
+ }
476
+ sendOverlay(next.errors);
477
+ } else {
478
+ lastLogged = "";
479
+ if (!before || !before.ok || before.raw !== next.raw) {
480
+ if (before && !before.ok) logger.info(`${manifestName} is valid now.`);
481
+ server.ws.send({ type: "full-reload" });
482
+ }
483
+ }
484
+ for (const l of listeners) l(next);
485
+ };
486
+ const onFile = (file) => {
487
+ const isManifest = file === manifestFile();
488
+ const isPage = file.toLowerCase().endsWith(".html") && file.startsWith(root + sep);
489
+ if (!isManifest && !isPage) return;
490
+ if (timer) clearTimeout(timer);
491
+ timer = setTimeout(recheck, RECHECK_DELAY_MS);
492
+ timer.unref?.();
493
+ };
494
+ server.watcher.on("change", onFile);
495
+ server.watcher.on("add", onFile);
496
+ server.watcher.on("unlink", onFile);
497
+ server.httpServer?.once("close", () => {
498
+ if (timer) clearTimeout(timer);
499
+ });
500
+ }
501
+ };
502
+ const plugins = [core];
503
+ if (options.fakeKassa !== false) {
504
+ plugins.push({
505
+ name: "evopos:fake-kassa",
506
+ apply: "serve",
507
+ configureServer(server) {
508
+ server.middlewares.use(fakeKassaMiddleware({ manifestUrl: "/manifest.json", clientFile: findClientFile() }));
509
+ }
510
+ });
511
+ }
512
+ let controller = null;
513
+ let stopSignal = null;
514
+ plugins.push({
515
+ name: "evopos:dev-session",
516
+ apply: "serve",
517
+ configureServer(server) {
518
+ const http = server.httpServer;
519
+ if (!http) return;
520
+ const logger = serverLogger(server);
521
+ const banner = server.printUrls.bind(server);
522
+ server.printUrls = () => {
523
+ banner();
524
+ const local = server.resolvedUrls?.local[0];
525
+ if (local && options.fakeKassa !== false) {
526
+ server.config.logger.info(` \u279C EvoPOS: ${new URL(FAKE_KASSA_PATH, local).href}`);
527
+ }
528
+ };
529
+ http.once("listening", () => {
530
+ const address = http.address();
531
+ const port = typeof address === "object" && address ? address.port : server.config.server.port;
532
+ const secure = Boolean(server.config.server.https);
533
+ const host = server.config.server.host;
534
+ if (host && !LOOPBACK_HOSTS.has(String(host)) && !secure) {
535
+ logger.warn(
536
+ `The dev server is open to the network over plain http. A kassa on another device (phone, second computer) cannot load an http:// iframe from a secure page. Serve the dev server over https with a certificate that device trusts (mkcert) and set \`devUrl\` to https://<this machine>:${port}/. The kassa on this computer works with http://localhost.`
537
+ );
538
+ }
539
+ if (options.devSession === false) return;
540
+ const devUrl = options.devUrl ?? env.EVOPOS_DEV_URL?.trim() ?? `${secure ? "https" : "http"}://localhost:${port}/`;
541
+ try {
542
+ new URL(devUrl);
543
+ } catch {
544
+ logger.warn(`Sandbox dev mode is off: devUrl "${devUrl}" is not a valid URL.`);
545
+ return;
546
+ }
547
+ const client = resolveSessionClient({
548
+ api: options.api,
549
+ env,
550
+ now: options.now,
551
+ createClient: options.createClient,
552
+ logger
553
+ });
554
+ if (!client) return;
555
+ const session = new DevSessionController(client, logger);
556
+ controller = session;
557
+ let started = false;
558
+ const apply = (current) => {
559
+ if (!current.ok) return;
560
+ if (current.manifest.kind === "driver") {
561
+ if (!started) logger.info("Sandbox dev mode is off: a driver manifest has no pages to open.");
562
+ started = true;
563
+ return;
564
+ }
565
+ if (!started) {
566
+ started = true;
567
+ void session.start(current.manifest, devUrl);
568
+ } else {
569
+ void session.update(current.manifest);
570
+ }
571
+ };
572
+ listeners.push(apply);
573
+ if (state) apply(state);
574
+ const onSigint = () => {
575
+ void server.close().finally(() => process.exit(130));
576
+ };
577
+ process.once("SIGINT", onSigint);
578
+ stopSignal = () => process.removeListener("SIGINT", onSigint);
579
+ });
580
+ },
581
+ async closeBundle() {
582
+ stopSignal?.();
583
+ stopSignal = null;
584
+ const current = controller;
585
+ controller = null;
586
+ await current?.stop();
587
+ }
588
+ });
589
+ return plugins;
590
+ }
591
+ var index_default = evopos;
592
+ export {
593
+ DEV_CORS_ORIGINS,
594
+ DevSessionController,
595
+ checkManifest,
596
+ index_default as default,
597
+ evopos,
598
+ findEntries,
599
+ formatErrors,
600
+ resolveSessionClient
601
+ };
602
+ //# sourceMappingURL=index.js.map